xref: /freebsd/contrib/llvm-project/clang/lib/Serialization/ASTReader.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
10b57cec5SDimitry Andric //===- ASTReader.cpp - AST File Reader ------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file defines the ASTReader class, which reads AST files.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "ASTCommon.h"
140b57cec5SDimitry Andric #include "ASTReaderInternals.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTConsumer.h"
160b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
170b57cec5SDimitry Andric #include "clang/AST/ASTMutationListener.h"
1881ad6265SDimitry Andric #include "clang/AST/ASTStructuralEquivalence.h"
190b57cec5SDimitry Andric #include "clang/AST/ASTUnresolvedSet.h"
20349cc55cSDimitry Andric #include "clang/AST/AbstractTypeReader.h"
210b57cec5SDimitry Andric #include "clang/AST/Decl.h"
220b57cec5SDimitry Andric #include "clang/AST/DeclBase.h"
230b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
240b57cec5SDimitry Andric #include "clang/AST/DeclFriend.h"
250b57cec5SDimitry Andric #include "clang/AST/DeclGroup.h"
260b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
270b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
280b57cec5SDimitry Andric #include "clang/AST/DeclarationName.h"
290b57cec5SDimitry Andric #include "clang/AST/Expr.h"
300b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
310b57cec5SDimitry Andric #include "clang/AST/ExternalASTSource.h"
320b57cec5SDimitry Andric #include "clang/AST/NestedNameSpecifier.h"
33*bdd1243dSDimitry Andric #include "clang/AST/ODRDiagsEmitter.h"
340b57cec5SDimitry Andric #include "clang/AST/ODRHash.h"
35349cc55cSDimitry Andric #include "clang/AST/OpenMPClause.h"
360b57cec5SDimitry Andric #include "clang/AST/RawCommentList.h"
370b57cec5SDimitry Andric #include "clang/AST/TemplateBase.h"
380b57cec5SDimitry Andric #include "clang/AST/TemplateName.h"
390b57cec5SDimitry Andric #include "clang/AST/Type.h"
400b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
410b57cec5SDimitry Andric #include "clang/AST/TypeLocVisitor.h"
420b57cec5SDimitry Andric #include "clang/AST/UnresolvedSet.h"
430b57cec5SDimitry Andric #include "clang/Basic/CommentOptions.h"
440b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
45349cc55cSDimitry Andric #include "clang/Basic/DiagnosticError.h"
460b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
4781ad6265SDimitry Andric #include "clang/Basic/DiagnosticSema.h"
480b57cec5SDimitry Andric #include "clang/Basic/ExceptionSpecificationType.h"
490b57cec5SDimitry Andric #include "clang/Basic/FileManager.h"
500b57cec5SDimitry Andric #include "clang/Basic/FileSystemOptions.h"
510b57cec5SDimitry Andric #include "clang/Basic/IdentifierTable.h"
520b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
530b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
540b57cec5SDimitry Andric #include "clang/Basic/Module.h"
550b57cec5SDimitry Andric #include "clang/Basic/ObjCRuntime.h"
56349cc55cSDimitry Andric #include "clang/Basic/OpenMPKinds.h"
570b57cec5SDimitry Andric #include "clang/Basic/OperatorKinds.h"
580b57cec5SDimitry Andric #include "clang/Basic/PragmaKinds.h"
590b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.h"
600b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
610b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
620b57cec5SDimitry Andric #include "clang/Basic/SourceManagerInternals.h"
630b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h"
640b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
650b57cec5SDimitry Andric #include "clang/Basic/TargetOptions.h"
660b57cec5SDimitry Andric #include "clang/Basic/TokenKinds.h"
670b57cec5SDimitry Andric #include "clang/Basic/Version.h"
680b57cec5SDimitry Andric #include "clang/Lex/HeaderSearch.h"
690b57cec5SDimitry Andric #include "clang/Lex/HeaderSearchOptions.h"
700b57cec5SDimitry Andric #include "clang/Lex/MacroInfo.h"
710b57cec5SDimitry Andric #include "clang/Lex/ModuleMap.h"
720b57cec5SDimitry Andric #include "clang/Lex/PreprocessingRecord.h"
730b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
740b57cec5SDimitry Andric #include "clang/Lex/PreprocessorOptions.h"
750b57cec5SDimitry Andric #include "clang/Lex/Token.h"
760b57cec5SDimitry Andric #include "clang/Sema/ObjCMethodList.h"
770b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
780b57cec5SDimitry Andric #include "clang/Sema/Sema.h"
790b57cec5SDimitry Andric #include "clang/Sema/Weak.h"
800b57cec5SDimitry Andric #include "clang/Serialization/ASTBitCodes.h"
810b57cec5SDimitry Andric #include "clang/Serialization/ASTDeserializationListener.h"
82349cc55cSDimitry Andric #include "clang/Serialization/ASTRecordReader.h"
830b57cec5SDimitry Andric #include "clang/Serialization/ContinuousRangeMap.h"
840b57cec5SDimitry Andric #include "clang/Serialization/GlobalModuleIndex.h"
850b57cec5SDimitry Andric #include "clang/Serialization/InMemoryModuleCache.h"
86480093f4SDimitry Andric #include "clang/Serialization/ModuleFile.h"
870b57cec5SDimitry Andric #include "clang/Serialization/ModuleFileExtension.h"
880b57cec5SDimitry Andric #include "clang/Serialization/ModuleManager.h"
890b57cec5SDimitry Andric #include "clang/Serialization/PCHContainerOperations.h"
900b57cec5SDimitry Andric #include "clang/Serialization/SerializationDiagnostic.h"
910b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
920b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
930b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
940b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
950b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
965ffd83dbSDimitry Andric #include "llvm/ADT/FloatingPointMode.h"
970b57cec5SDimitry Andric #include "llvm/ADT/FoldingSet.h"
980b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
990b57cec5SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h"
1000b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
1010b57cec5SDimitry Andric #include "llvm/ADT/ScopeExit.h"
1020b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
1030b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
1040b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
1050b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
1060b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
1070b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
1080b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
1090b57cec5SDimitry Andric #include "llvm/ADT/iterator_range.h"
1100b57cec5SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
1110b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
1120b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
1130b57cec5SDimitry Andric #include "llvm/Support/Compression.h"
1140b57cec5SDimitry Andric #include "llvm/Support/DJB.h"
1150b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
1160b57cec5SDimitry Andric #include "llvm/Support/Error.h"
1170b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
1180b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
119fe6060f1SDimitry Andric #include "llvm/Support/LEB128.h"
1200b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
1210b57cec5SDimitry Andric #include "llvm/Support/Path.h"
1220b57cec5SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
123*bdd1243dSDimitry Andric #include "llvm/Support/TimeProfiler.h"
1240b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
1250b57cec5SDimitry Andric #include "llvm/Support/VersionTuple.h"
1260b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
1270b57cec5SDimitry Andric #include <algorithm>
1280b57cec5SDimitry Andric #include <cassert>
1290b57cec5SDimitry Andric #include <cstddef>
1300b57cec5SDimitry Andric #include <cstdint>
1310b57cec5SDimitry Andric #include <cstdio>
1320b57cec5SDimitry Andric #include <ctime>
1330b57cec5SDimitry Andric #include <iterator>
1340b57cec5SDimitry Andric #include <limits>
1350b57cec5SDimitry Andric #include <map>
1360b57cec5SDimitry Andric #include <memory>
137*bdd1243dSDimitry Andric #include <optional>
1380b57cec5SDimitry Andric #include <string>
1390b57cec5SDimitry Andric #include <system_error>
1400b57cec5SDimitry Andric #include <tuple>
1410b57cec5SDimitry Andric #include <utility>
1420b57cec5SDimitry Andric #include <vector>
1430b57cec5SDimitry Andric 
1440b57cec5SDimitry Andric using namespace clang;
1450b57cec5SDimitry Andric using namespace clang::serialization;
1460b57cec5SDimitry Andric using namespace clang::serialization::reader;
1470b57cec5SDimitry Andric using llvm::BitstreamCursor;
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1500b57cec5SDimitry Andric // ChainedASTReaderListener implementation
1510b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric bool
1540b57cec5SDimitry Andric ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
1550b57cec5SDimitry Andric   return First->ReadFullVersionInformation(FullVersion) ||
1560b57cec5SDimitry Andric          Second->ReadFullVersionInformation(FullVersion);
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
1600b57cec5SDimitry Andric   First->ReadModuleName(ModuleName);
1610b57cec5SDimitry Andric   Second->ReadModuleName(ModuleName);
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
1650b57cec5SDimitry Andric   First->ReadModuleMapFile(ModuleMapPath);
1660b57cec5SDimitry Andric   Second->ReadModuleMapFile(ModuleMapPath);
1670b57cec5SDimitry Andric }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric bool
1700b57cec5SDimitry Andric ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
1710b57cec5SDimitry Andric                                               bool Complain,
1720b57cec5SDimitry Andric                                               bool AllowCompatibleDifferences) {
1730b57cec5SDimitry Andric   return First->ReadLanguageOptions(LangOpts, Complain,
1740b57cec5SDimitry Andric                                     AllowCompatibleDifferences) ||
1750b57cec5SDimitry Andric          Second->ReadLanguageOptions(LangOpts, Complain,
1760b57cec5SDimitry Andric                                      AllowCompatibleDifferences);
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadTargetOptions(
1800b57cec5SDimitry Andric     const TargetOptions &TargetOpts, bool Complain,
1810b57cec5SDimitry Andric     bool AllowCompatibleDifferences) {
1820b57cec5SDimitry Andric   return First->ReadTargetOptions(TargetOpts, Complain,
1830b57cec5SDimitry Andric                                   AllowCompatibleDifferences) ||
1840b57cec5SDimitry Andric          Second->ReadTargetOptions(TargetOpts, Complain,
1850b57cec5SDimitry Andric                                    AllowCompatibleDifferences);
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadDiagnosticOptions(
1890b57cec5SDimitry Andric     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
1900b57cec5SDimitry Andric   return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
1910b57cec5SDimitry Andric          Second->ReadDiagnosticOptions(DiagOpts, Complain);
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric bool
1950b57cec5SDimitry Andric ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
1960b57cec5SDimitry Andric                                                 bool Complain) {
1970b57cec5SDimitry Andric   return First->ReadFileSystemOptions(FSOpts, Complain) ||
1980b57cec5SDimitry Andric          Second->ReadFileSystemOptions(FSOpts, Complain);
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadHeaderSearchOptions(
2020b57cec5SDimitry Andric     const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
2030b57cec5SDimitry Andric     bool Complain) {
2040b57cec5SDimitry Andric   return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
2050b57cec5SDimitry Andric                                         Complain) ||
2060b57cec5SDimitry Andric          Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
2070b57cec5SDimitry Andric                                          Complain);
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric bool ChainedASTReaderListener::ReadPreprocessorOptions(
2110b57cec5SDimitry Andric     const PreprocessorOptions &PPOpts, bool Complain,
2120b57cec5SDimitry Andric     std::string &SuggestedPredefines) {
2130b57cec5SDimitry Andric   return First->ReadPreprocessorOptions(PPOpts, Complain,
2140b57cec5SDimitry Andric                                         SuggestedPredefines) ||
2150b57cec5SDimitry Andric          Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
2160b57cec5SDimitry Andric }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
2190b57cec5SDimitry Andric                                            unsigned Value) {
2200b57cec5SDimitry Andric   First->ReadCounter(M, Value);
2210b57cec5SDimitry Andric   Second->ReadCounter(M, Value);
2220b57cec5SDimitry Andric }
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric bool ChainedASTReaderListener::needsInputFileVisitation() {
2250b57cec5SDimitry Andric   return First->needsInputFileVisitation() ||
2260b57cec5SDimitry Andric          Second->needsInputFileVisitation();
2270b57cec5SDimitry Andric }
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
2300b57cec5SDimitry Andric   return First->needsSystemInputFileVisitation() ||
2310b57cec5SDimitry Andric   Second->needsSystemInputFileVisitation();
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
2350b57cec5SDimitry Andric                                                ModuleKind Kind) {
2360b57cec5SDimitry Andric   First->visitModuleFile(Filename, Kind);
2370b57cec5SDimitry Andric   Second->visitModuleFile(Filename, Kind);
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
2410b57cec5SDimitry Andric                                               bool isSystem,
2420b57cec5SDimitry Andric                                               bool isOverridden,
2430b57cec5SDimitry Andric                                               bool isExplicitModule) {
2440b57cec5SDimitry Andric   bool Continue = false;
2450b57cec5SDimitry Andric   if (First->needsInputFileVisitation() &&
2460b57cec5SDimitry Andric       (!isSystem || First->needsSystemInputFileVisitation()))
2470b57cec5SDimitry Andric     Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
2480b57cec5SDimitry Andric                                       isExplicitModule);
2490b57cec5SDimitry Andric   if (Second->needsInputFileVisitation() &&
2500b57cec5SDimitry Andric       (!isSystem || Second->needsSystemInputFileVisitation()))
2510b57cec5SDimitry Andric     Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
2520b57cec5SDimitry Andric                                        isExplicitModule);
2530b57cec5SDimitry Andric   return Continue;
2540b57cec5SDimitry Andric }
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric void ChainedASTReaderListener::readModuleFileExtension(
2570b57cec5SDimitry Andric        const ModuleFileExtensionMetadata &Metadata) {
2580b57cec5SDimitry Andric   First->readModuleFileExtension(Metadata);
2590b57cec5SDimitry Andric   Second->readModuleFileExtension(Metadata);
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric 
2620b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2630b57cec5SDimitry Andric // PCH validator implementation
2640b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric ASTReaderListener::~ASTReaderListener() = default;
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric /// Compare the given set of language options against an existing set of
2690b57cec5SDimitry Andric /// language options.
2700b57cec5SDimitry Andric ///
2710b57cec5SDimitry Andric /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
2720b57cec5SDimitry Andric /// \param AllowCompatibleDifferences If true, differences between compatible
2730b57cec5SDimitry Andric ///        language options will be permitted.
2740b57cec5SDimitry Andric ///
2750b57cec5SDimitry Andric /// \returns true if the languagae options mis-match, false otherwise.
2760b57cec5SDimitry Andric static bool checkLanguageOptions(const LangOptions &LangOpts,
2770b57cec5SDimitry Andric                                  const LangOptions &ExistingLangOpts,
2780b57cec5SDimitry Andric                                  DiagnosticsEngine *Diags,
2790b57cec5SDimitry Andric                                  bool AllowCompatibleDifferences = true) {
2800b57cec5SDimitry Andric #define LANGOPT(Name, Bits, Default, Description)                 \
2810b57cec5SDimitry Andric   if (ExistingLangOpts.Name != LangOpts.Name) {                   \
2820b57cec5SDimitry Andric     if (Diags)                                                    \
2830b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_mismatch)               \
2840b57cec5SDimitry Andric         << Description << LangOpts.Name << ExistingLangOpts.Name; \
2850b57cec5SDimitry Andric     return true;                                                  \
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric #define VALUE_LANGOPT(Name, Bits, Default, Description)   \
2890b57cec5SDimitry Andric   if (ExistingLangOpts.Name != LangOpts.Name) {           \
2900b57cec5SDimitry Andric     if (Diags)                                            \
2910b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch) \
2920b57cec5SDimitry Andric         << Description;                                   \
2930b57cec5SDimitry Andric     return true;                                          \
2940b57cec5SDimitry Andric   }
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric #define ENUM_LANGOPT(Name, Type, Bits, Default, Description)   \
2970b57cec5SDimitry Andric   if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) {  \
2980b57cec5SDimitry Andric     if (Diags)                                                 \
2990b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch)      \
3000b57cec5SDimitry Andric         << Description;                                        \
3010b57cec5SDimitry Andric     return true;                                               \
3020b57cec5SDimitry Andric   }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description)  \
3050b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)                            \
3060b57cec5SDimitry Andric     LANGOPT(Name, Bits, Default, Description)
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description)  \
3090b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)                                 \
3100b57cec5SDimitry Andric     ENUM_LANGOPT(Name, Bits, Default, Description)
3110b57cec5SDimitry Andric 
3120b57cec5SDimitry Andric #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
3130b57cec5SDimitry Andric   if (!AllowCompatibleDifferences)                                 \
3140b57cec5SDimitry Andric     VALUE_LANGOPT(Name, Bits, Default, Description)
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric #define BENIGN_LANGOPT(Name, Bits, Default, Description)
3170b57cec5SDimitry Andric #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
31881ad6265SDimitry Andric #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
3190b57cec5SDimitry Andric #include "clang/Basic/LangOptions.def"
3200b57cec5SDimitry Andric 
3210b57cec5SDimitry Andric   if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
3220b57cec5SDimitry Andric     if (Diags)
3230b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
3240b57cec5SDimitry Andric     return true;
3250b57cec5SDimitry Andric   }
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
3280b57cec5SDimitry Andric     if (Diags)
3290b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch)
3300b57cec5SDimitry Andric       << "target Objective-C runtime";
3310b57cec5SDimitry Andric     return true;
3320b57cec5SDimitry Andric   }
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric   if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
3350b57cec5SDimitry Andric       LangOpts.CommentOpts.BlockCommandNames) {
3360b57cec5SDimitry Andric     if (Diags)
3370b57cec5SDimitry Andric       Diags->Report(diag::err_pch_langopt_value_mismatch)
3380b57cec5SDimitry Andric         << "block command names";
3390b57cec5SDimitry Andric     return true;
3400b57cec5SDimitry Andric   }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   // Sanitizer feature mismatches are treated as compatible differences. If
3430b57cec5SDimitry Andric   // compatible differences aren't allowed, we still only want to check for
3440b57cec5SDimitry Andric   // mismatches of non-modular sanitizers (the only ones which can affect AST
3450b57cec5SDimitry Andric   // generation).
3460b57cec5SDimitry Andric   if (!AllowCompatibleDifferences) {
3470b57cec5SDimitry Andric     SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
3480b57cec5SDimitry Andric     SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
3490b57cec5SDimitry Andric     SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
3500b57cec5SDimitry Andric     ExistingSanitizers.clear(ModularSanitizers);
3510b57cec5SDimitry Andric     ImportedSanitizers.clear(ModularSanitizers);
3520b57cec5SDimitry Andric     if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
3530b57cec5SDimitry Andric       const std::string Flag = "-fsanitize=";
3540b57cec5SDimitry Andric       if (Diags) {
3550b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
3560b57cec5SDimitry Andric   {                                                                            \
3570b57cec5SDimitry Andric     bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID);         \
3580b57cec5SDimitry Andric     bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID);         \
3590b57cec5SDimitry Andric     if (InExistingModule != InImportedModule)                                  \
3600b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_feature_mismatch)                  \
3610b57cec5SDimitry Andric           << InExistingModule << (Flag + NAME);                                \
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
3640b57cec5SDimitry Andric       }
3650b57cec5SDimitry Andric       return true;
3660b57cec5SDimitry Andric     }
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   return false;
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric /// Compare the given set of target options against an existing set of
3730b57cec5SDimitry Andric /// target options.
3740b57cec5SDimitry Andric ///
3750b57cec5SDimitry Andric /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
3760b57cec5SDimitry Andric ///
3770b57cec5SDimitry Andric /// \returns true if the target options mis-match, false otherwise.
3780b57cec5SDimitry Andric static bool checkTargetOptions(const TargetOptions &TargetOpts,
3790b57cec5SDimitry Andric                                const TargetOptions &ExistingTargetOpts,
3800b57cec5SDimitry Andric                                DiagnosticsEngine *Diags,
3810b57cec5SDimitry Andric                                bool AllowCompatibleDifferences = true) {
3820b57cec5SDimitry Andric #define CHECK_TARGET_OPT(Field, Name)                             \
3830b57cec5SDimitry Andric   if (TargetOpts.Field != ExistingTargetOpts.Field) {             \
3840b57cec5SDimitry Andric     if (Diags)                                                    \
3850b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_mismatch)             \
3860b57cec5SDimitry Andric         << Name << TargetOpts.Field << ExistingTargetOpts.Field;  \
3870b57cec5SDimitry Andric     return true;                                                  \
3880b57cec5SDimitry Andric   }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric   // The triple and ABI must match exactly.
3910b57cec5SDimitry Andric   CHECK_TARGET_OPT(Triple, "target");
3920b57cec5SDimitry Andric   CHECK_TARGET_OPT(ABI, "target ABI");
3930b57cec5SDimitry Andric 
3940b57cec5SDimitry Andric   // We can tolerate different CPUs in many cases, notably when one CPU
3950b57cec5SDimitry Andric   // supports a strict superset of another. When allowing compatible
3960b57cec5SDimitry Andric   // differences skip this check.
397e8d8bef9SDimitry Andric   if (!AllowCompatibleDifferences) {
3980b57cec5SDimitry Andric     CHECK_TARGET_OPT(CPU, "target CPU");
399e8d8bef9SDimitry Andric     CHECK_TARGET_OPT(TuneCPU, "tune CPU");
400e8d8bef9SDimitry Andric   }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric #undef CHECK_TARGET_OPT
4030b57cec5SDimitry Andric 
4040b57cec5SDimitry Andric   // Compare feature sets.
4050b57cec5SDimitry Andric   SmallVector<StringRef, 4> ExistingFeatures(
4060b57cec5SDimitry Andric                                              ExistingTargetOpts.FeaturesAsWritten.begin(),
4070b57cec5SDimitry Andric                                              ExistingTargetOpts.FeaturesAsWritten.end());
4080b57cec5SDimitry Andric   SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
4090b57cec5SDimitry Andric                                          TargetOpts.FeaturesAsWritten.end());
4100b57cec5SDimitry Andric   llvm::sort(ExistingFeatures);
4110b57cec5SDimitry Andric   llvm::sort(ReadFeatures);
4120b57cec5SDimitry Andric 
4130b57cec5SDimitry Andric   // We compute the set difference in both directions explicitly so that we can
4140b57cec5SDimitry Andric   // diagnose the differences differently.
4150b57cec5SDimitry Andric   SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
4160b57cec5SDimitry Andric   std::set_difference(
4170b57cec5SDimitry Andric       ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
4180b57cec5SDimitry Andric       ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
4190b57cec5SDimitry Andric   std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
4200b57cec5SDimitry Andric                       ExistingFeatures.begin(), ExistingFeatures.end(),
4210b57cec5SDimitry Andric                       std::back_inserter(UnmatchedReadFeatures));
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // If we are allowing compatible differences and the read feature set is
4240b57cec5SDimitry Andric   // a strict subset of the existing feature set, there is nothing to diagnose.
4250b57cec5SDimitry Andric   if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
4260b57cec5SDimitry Andric     return false;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   if (Diags) {
4290b57cec5SDimitry Andric     for (StringRef Feature : UnmatchedReadFeatures)
4300b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
4310b57cec5SDimitry Andric           << /* is-existing-feature */ false << Feature;
4320b57cec5SDimitry Andric     for (StringRef Feature : UnmatchedExistingFeatures)
4330b57cec5SDimitry Andric       Diags->Report(diag::err_pch_targetopt_feature_mismatch)
4340b57cec5SDimitry Andric           << /* is-existing-feature */ true << Feature;
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
4380b57cec5SDimitry Andric }
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric bool
4410b57cec5SDimitry Andric PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
4420b57cec5SDimitry Andric                                   bool Complain,
4430b57cec5SDimitry Andric                                   bool AllowCompatibleDifferences) {
4440b57cec5SDimitry Andric   const LangOptions &ExistingLangOpts = PP.getLangOpts();
4450b57cec5SDimitry Andric   return checkLanguageOptions(LangOpts, ExistingLangOpts,
4460b57cec5SDimitry Andric                               Complain ? &Reader.Diags : nullptr,
4470b57cec5SDimitry Andric                               AllowCompatibleDifferences);
4480b57cec5SDimitry Andric }
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
4510b57cec5SDimitry Andric                                      bool Complain,
4520b57cec5SDimitry Andric                                      bool AllowCompatibleDifferences) {
4530b57cec5SDimitry Andric   const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
4540b57cec5SDimitry Andric   return checkTargetOptions(TargetOpts, ExistingTargetOpts,
4550b57cec5SDimitry Andric                             Complain ? &Reader.Diags : nullptr,
4560b57cec5SDimitry Andric                             AllowCompatibleDifferences);
4570b57cec5SDimitry Andric }
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric namespace {
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric using MacroDefinitionsMap =
4620b57cec5SDimitry Andric     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
4630b57cec5SDimitry Andric using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
4640b57cec5SDimitry Andric 
4650b57cec5SDimitry Andric } // namespace
4660b57cec5SDimitry Andric 
4670b57cec5SDimitry Andric static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
4680b57cec5SDimitry Andric                                          DiagnosticsEngine &Diags,
4690b57cec5SDimitry Andric                                          bool Complain) {
4700b57cec5SDimitry Andric   using Level = DiagnosticsEngine::Level;
4710b57cec5SDimitry Andric 
4720b57cec5SDimitry Andric   // Check current mappings for new -Werror mappings, and the stored mappings
4730b57cec5SDimitry Andric   // for cases that were explicitly mapped to *not* be errors that are now
4740b57cec5SDimitry Andric   // errors because of options like -Werror.
4750b57cec5SDimitry Andric   DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
4760b57cec5SDimitry Andric 
4770b57cec5SDimitry Andric   for (DiagnosticsEngine *MappingSource : MappingSources) {
4780b57cec5SDimitry Andric     for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
4790b57cec5SDimitry Andric       diag::kind DiagID = DiagIDMappingPair.first;
4800b57cec5SDimitry Andric       Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
4810b57cec5SDimitry Andric       if (CurLevel < DiagnosticsEngine::Error)
4820b57cec5SDimitry Andric         continue; // not significant
4830b57cec5SDimitry Andric       Level StoredLevel =
4840b57cec5SDimitry Andric           StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
4850b57cec5SDimitry Andric       if (StoredLevel < DiagnosticsEngine::Error) {
4860b57cec5SDimitry Andric         if (Complain)
4870b57cec5SDimitry Andric           Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
4880b57cec5SDimitry Andric               Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
4890b57cec5SDimitry Andric         return true;
4900b57cec5SDimitry Andric       }
4910b57cec5SDimitry Andric     }
4920b57cec5SDimitry Andric   }
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric   return false;
4950b57cec5SDimitry Andric }
4960b57cec5SDimitry Andric 
4970b57cec5SDimitry Andric static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
4980b57cec5SDimitry Andric   diag::Severity Ext = Diags.getExtensionHandlingBehavior();
4990b57cec5SDimitry Andric   if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
5000b57cec5SDimitry Andric     return true;
5010b57cec5SDimitry Andric   return Ext >= diag::Severity::Error;
5020b57cec5SDimitry Andric }
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
5050b57cec5SDimitry Andric                                     DiagnosticsEngine &Diags,
5060b57cec5SDimitry Andric                                     bool IsSystem, bool Complain) {
5070b57cec5SDimitry Andric   // Top-level options
5080b57cec5SDimitry Andric   if (IsSystem) {
5090b57cec5SDimitry Andric     if (Diags.getSuppressSystemWarnings())
5100b57cec5SDimitry Andric       return false;
5110b57cec5SDimitry Andric     // If -Wsystem-headers was not enabled before, be conservative
5120b57cec5SDimitry Andric     if (StoredDiags.getSuppressSystemWarnings()) {
5130b57cec5SDimitry Andric       if (Complain)
5140b57cec5SDimitry Andric         Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
5150b57cec5SDimitry Andric       return true;
5160b57cec5SDimitry Andric     }
5170b57cec5SDimitry Andric   }
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
5200b57cec5SDimitry Andric     if (Complain)
5210b57cec5SDimitry Andric       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
5220b57cec5SDimitry Andric     return true;
5230b57cec5SDimitry Andric   }
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
5260b57cec5SDimitry Andric       !StoredDiags.getEnableAllWarnings()) {
5270b57cec5SDimitry Andric     if (Complain)
5280b57cec5SDimitry Andric       Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
5290b57cec5SDimitry Andric     return true;
5300b57cec5SDimitry Andric   }
5310b57cec5SDimitry Andric 
5320b57cec5SDimitry Andric   if (isExtHandlingFromDiagsError(Diags) &&
5330b57cec5SDimitry Andric       !isExtHandlingFromDiagsError(StoredDiags)) {
5340b57cec5SDimitry Andric     if (Complain)
5350b57cec5SDimitry Andric       Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
5360b57cec5SDimitry Andric     return true;
5370b57cec5SDimitry Andric   }
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
5400b57cec5SDimitry Andric }
5410b57cec5SDimitry Andric 
5420b57cec5SDimitry Andric /// Return the top import module if it is implicit, nullptr otherwise.
5430b57cec5SDimitry Andric static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
5440b57cec5SDimitry Andric                                           Preprocessor &PP) {
5450b57cec5SDimitry Andric   // If the original import came from a file explicitly generated by the user,
5460b57cec5SDimitry Andric   // don't check the diagnostic mappings.
5470b57cec5SDimitry Andric   // FIXME: currently this is approximated by checking whether this is not a
5480b57cec5SDimitry Andric   // module import of an implicitly-loaded module file.
5490b57cec5SDimitry Andric   // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
5500b57cec5SDimitry Andric   // the transitive closure of its imports, since unrelated modules cannot be
5510b57cec5SDimitry Andric   // imported until after this module finishes validation.
5520b57cec5SDimitry Andric   ModuleFile *TopImport = &*ModuleMgr.rbegin();
5530b57cec5SDimitry Andric   while (!TopImport->ImportedBy.empty())
5540b57cec5SDimitry Andric     TopImport = TopImport->ImportedBy[0];
5550b57cec5SDimitry Andric   if (TopImport->Kind != MK_ImplicitModule)
5560b57cec5SDimitry Andric     return nullptr;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   StringRef ModuleName = TopImport->ModuleName;
5590b57cec5SDimitry Andric   assert(!ModuleName.empty() && "diagnostic options read before module name");
5600b57cec5SDimitry Andric 
561349cc55cSDimitry Andric   Module *M =
562349cc55cSDimitry Andric       PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
5630b57cec5SDimitry Andric   assert(M && "missing module");
5640b57cec5SDimitry Andric   return M;
5650b57cec5SDimitry Andric }
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric bool PCHValidator::ReadDiagnosticOptions(
5680b57cec5SDimitry Andric     IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
5690b57cec5SDimitry Andric   DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
5700b57cec5SDimitry Andric   IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
5710b57cec5SDimitry Andric   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
5720b57cec5SDimitry Andric       new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
5730b57cec5SDimitry Andric   // This should never fail, because we would have processed these options
5740b57cec5SDimitry Andric   // before writing them to an ASTFile.
5750b57cec5SDimitry Andric   ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric   ModuleManager &ModuleMgr = Reader.getModuleManager();
5780b57cec5SDimitry Andric   assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
5810b57cec5SDimitry Andric   if (!TopM)
5820b57cec5SDimitry Andric     return false;
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
5850b57cec5SDimitry Andric   // contains the union of their flags.
5860b57cec5SDimitry Andric   return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
5870b57cec5SDimitry Andric                                  Complain);
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric /// Collect the macro definitions provided by the given preprocessor
5910b57cec5SDimitry Andric /// options.
5920b57cec5SDimitry Andric static void
5930b57cec5SDimitry Andric collectMacroDefinitions(const PreprocessorOptions &PPOpts,
5940b57cec5SDimitry Andric                         MacroDefinitionsMap &Macros,
5950b57cec5SDimitry Andric                         SmallVectorImpl<StringRef> *MacroNames = nullptr) {
5960b57cec5SDimitry Andric   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
5970b57cec5SDimitry Andric     StringRef Macro = PPOpts.Macros[I].first;
5980b57cec5SDimitry Andric     bool IsUndef = PPOpts.Macros[I].second;
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
6010b57cec5SDimitry Andric     StringRef MacroName = MacroPair.first;
6020b57cec5SDimitry Andric     StringRef MacroBody = MacroPair.second;
6030b57cec5SDimitry Andric 
6040b57cec5SDimitry Andric     // For an #undef'd macro, we only care about the name.
6050b57cec5SDimitry Andric     if (IsUndef) {
6060b57cec5SDimitry Andric       if (MacroNames && !Macros.count(MacroName))
6070b57cec5SDimitry Andric         MacroNames->push_back(MacroName);
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric       Macros[MacroName] = std::make_pair("", true);
6100b57cec5SDimitry Andric       continue;
6110b57cec5SDimitry Andric     }
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     // For a #define'd macro, figure out the actual definition.
6140b57cec5SDimitry Andric     if (MacroName.size() == Macro.size())
6150b57cec5SDimitry Andric       MacroBody = "1";
6160b57cec5SDimitry Andric     else {
6170b57cec5SDimitry Andric       // Note: GCC drops anything following an end-of-line character.
6180b57cec5SDimitry Andric       StringRef::size_type End = MacroBody.find_first_of("\n\r");
6190b57cec5SDimitry Andric       MacroBody = MacroBody.substr(0, End);
6200b57cec5SDimitry Andric     }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric     if (MacroNames && !Macros.count(MacroName))
6230b57cec5SDimitry Andric       MacroNames->push_back(MacroName);
6240b57cec5SDimitry Andric     Macros[MacroName] = std::make_pair(MacroBody, false);
6250b57cec5SDimitry Andric   }
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric 
62861cfbce3SDimitry Andric enum OptionValidation {
62961cfbce3SDimitry Andric   OptionValidateNone,
63061cfbce3SDimitry Andric   OptionValidateContradictions,
63161cfbce3SDimitry Andric   OptionValidateStrictMatches,
63261cfbce3SDimitry Andric };
63361cfbce3SDimitry Andric 
6340b57cec5SDimitry Andric /// Check the preprocessor options deserialized from the control block
6350b57cec5SDimitry Andric /// against the preprocessor options in an existing preprocessor.
6360b57cec5SDimitry Andric ///
6370b57cec5SDimitry Andric /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
63861cfbce3SDimitry Andric /// \param Validation If set to OptionValidateNone, ignore differences in
63961cfbce3SDimitry Andric ///        preprocessor options. If set to OptionValidateContradictions,
64061cfbce3SDimitry Andric ///        require that options passed both in the AST file and on the command
64161cfbce3SDimitry Andric ///        line (-D or -U) match, but tolerate options missing in one or the
64261cfbce3SDimitry Andric ///        other. If set to OptionValidateContradictions, require that there
64361cfbce3SDimitry Andric ///        are no differences in the options between the two.
64461cfbce3SDimitry Andric static bool checkPreprocessorOptions(
64561cfbce3SDimitry Andric     const PreprocessorOptions &PPOpts,
64661cfbce3SDimitry Andric     const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags,
64761cfbce3SDimitry Andric     FileManager &FileMgr, std::string &SuggestedPredefines,
6480b57cec5SDimitry Andric     const LangOptions &LangOpts,
64961cfbce3SDimitry Andric     OptionValidation Validation = OptionValidateContradictions) {
6500b57cec5SDimitry Andric   // Check macro definitions.
6510b57cec5SDimitry Andric   MacroDefinitionsMap ASTFileMacros;
6520b57cec5SDimitry Andric   collectMacroDefinitions(PPOpts, ASTFileMacros);
6530b57cec5SDimitry Andric   MacroDefinitionsMap ExistingMacros;
6540b57cec5SDimitry Andric   SmallVector<StringRef, 4> ExistingMacroNames;
6550b57cec5SDimitry Andric   collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric   for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
6580b57cec5SDimitry Andric     // Dig out the macro definition in the existing preprocessor options.
6590b57cec5SDimitry Andric     StringRef MacroName = ExistingMacroNames[I];
6600b57cec5SDimitry Andric     std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric     // Check whether we know anything about this macro name or not.
6630b57cec5SDimitry Andric     llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
6640b57cec5SDimitry Andric         ASTFileMacros.find(MacroName);
66561cfbce3SDimitry Andric     if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
66661cfbce3SDimitry Andric       if (Validation == OptionValidateStrictMatches) {
66761cfbce3SDimitry Andric         // If strict matches are requested, don't tolerate any extra defines on
66861cfbce3SDimitry Andric         // the command line that are missing in the AST file.
66961cfbce3SDimitry Andric         if (Diags) {
67061cfbce3SDimitry Andric           Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
67161cfbce3SDimitry Andric         }
67261cfbce3SDimitry Andric         return true;
67361cfbce3SDimitry Andric       }
6740b57cec5SDimitry Andric       // FIXME: Check whether this identifier was referenced anywhere in the
6750b57cec5SDimitry Andric       // AST file. If so, we should reject the AST file. Unfortunately, this
6760b57cec5SDimitry Andric       // information isn't in the control block. What shall we do about it?
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric       if (Existing.second) {
6790b57cec5SDimitry Andric         SuggestedPredefines += "#undef ";
6800b57cec5SDimitry Andric         SuggestedPredefines += MacroName.str();
6810b57cec5SDimitry Andric         SuggestedPredefines += '\n';
6820b57cec5SDimitry Andric       } else {
6830b57cec5SDimitry Andric         SuggestedPredefines += "#define ";
6840b57cec5SDimitry Andric         SuggestedPredefines += MacroName.str();
6850b57cec5SDimitry Andric         SuggestedPredefines += ' ';
6860b57cec5SDimitry Andric         SuggestedPredefines += Existing.first.str();
6870b57cec5SDimitry Andric         SuggestedPredefines += '\n';
6880b57cec5SDimitry Andric       }
6890b57cec5SDimitry Andric       continue;
6900b57cec5SDimitry Andric     }
6910b57cec5SDimitry Andric 
6920b57cec5SDimitry Andric     // If the macro was defined in one but undef'd in the other, we have a
6930b57cec5SDimitry Andric     // conflict.
6940b57cec5SDimitry Andric     if (Existing.second != Known->second.second) {
6950b57cec5SDimitry Andric       if (Diags) {
6960b57cec5SDimitry Andric         Diags->Report(diag::err_pch_macro_def_undef)
6970b57cec5SDimitry Andric           << MacroName << Known->second.second;
6980b57cec5SDimitry Andric       }
6990b57cec5SDimitry Andric       return true;
7000b57cec5SDimitry Andric     }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     // If the macro was #undef'd in both, or if the macro bodies are identical,
7030b57cec5SDimitry Andric     // it's fine.
70461cfbce3SDimitry Andric     if (Existing.second || Existing.first == Known->second.first) {
70561cfbce3SDimitry Andric       ASTFileMacros.erase(Known);
7060b57cec5SDimitry Andric       continue;
70761cfbce3SDimitry Andric     }
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric     // The macro bodies differ; complain.
7100b57cec5SDimitry Andric     if (Diags) {
7110b57cec5SDimitry Andric       Diags->Report(diag::err_pch_macro_def_conflict)
7120b57cec5SDimitry Andric         << MacroName << Known->second.first << Existing.first;
7130b57cec5SDimitry Andric     }
7140b57cec5SDimitry Andric     return true;
7150b57cec5SDimitry Andric   }
71661cfbce3SDimitry Andric   if (Validation == OptionValidateStrictMatches) {
71761cfbce3SDimitry Andric     // If strict matches are requested, don't tolerate any extra defines in
71861cfbce3SDimitry Andric     // the AST file that are missing on the command line.
71961cfbce3SDimitry Andric     for (const auto &MacroName : ASTFileMacros.keys()) {
72061cfbce3SDimitry Andric       if (Diags) {
72161cfbce3SDimitry Andric         Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
72261cfbce3SDimitry Andric       }
72361cfbce3SDimitry Andric       return true;
72461cfbce3SDimitry Andric     }
72561cfbce3SDimitry Andric   }
7260b57cec5SDimitry Andric 
7270b57cec5SDimitry Andric   // Check whether we're using predefines.
72861cfbce3SDimitry Andric   if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
72961cfbce3SDimitry Andric       Validation != OptionValidateNone) {
7300b57cec5SDimitry Andric     if (Diags) {
7310b57cec5SDimitry Andric       Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
7320b57cec5SDimitry Andric     }
7330b57cec5SDimitry Andric     return true;
7340b57cec5SDimitry Andric   }
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   // Detailed record is important since it is used for the module cache hash.
7370b57cec5SDimitry Andric   if (LangOpts.Modules &&
73861cfbce3SDimitry Andric       PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
73961cfbce3SDimitry Andric       Validation != OptionValidateNone) {
7400b57cec5SDimitry Andric     if (Diags) {
7410b57cec5SDimitry Andric       Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
7420b57cec5SDimitry Andric     }
7430b57cec5SDimitry Andric     return true;
7440b57cec5SDimitry Andric   }
7450b57cec5SDimitry Andric 
7460b57cec5SDimitry Andric   // Compute the #include and #include_macros lines we need.
7470b57cec5SDimitry Andric   for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
7480b57cec5SDimitry Andric     StringRef File = ExistingPPOpts.Includes[I];
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric     if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
7510b57cec5SDimitry Andric         !ExistingPPOpts.PCHThroughHeader.empty()) {
7520b57cec5SDimitry Andric       // In case the through header is an include, we must add all the includes
7530b57cec5SDimitry Andric       // to the predefines so the start point can be determined.
7540b57cec5SDimitry Andric       SuggestedPredefines += "#include \"";
7550b57cec5SDimitry Andric       SuggestedPredefines += File;
7560b57cec5SDimitry Andric       SuggestedPredefines += "\"\n";
7570b57cec5SDimitry Andric       continue;
7580b57cec5SDimitry Andric     }
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric     if (File == ExistingPPOpts.ImplicitPCHInclude)
7610b57cec5SDimitry Andric       continue;
7620b57cec5SDimitry Andric 
763349cc55cSDimitry Andric     if (llvm::is_contained(PPOpts.Includes, File))
7640b57cec5SDimitry Andric       continue;
7650b57cec5SDimitry Andric 
7660b57cec5SDimitry Andric     SuggestedPredefines += "#include \"";
7670b57cec5SDimitry Andric     SuggestedPredefines += File;
7680b57cec5SDimitry Andric     SuggestedPredefines += "\"\n";
7690b57cec5SDimitry Andric   }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric   for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
7720b57cec5SDimitry Andric     StringRef File = ExistingPPOpts.MacroIncludes[I];
773349cc55cSDimitry Andric     if (llvm::is_contained(PPOpts.MacroIncludes, File))
7740b57cec5SDimitry Andric       continue;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric     SuggestedPredefines += "#__include_macros \"";
7770b57cec5SDimitry Andric     SuggestedPredefines += File;
7780b57cec5SDimitry Andric     SuggestedPredefines += "\"\n##\n";
7790b57cec5SDimitry Andric   }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   return false;
7820b57cec5SDimitry Andric }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
7850b57cec5SDimitry Andric                                            bool Complain,
7860b57cec5SDimitry Andric                                            std::string &SuggestedPredefines) {
7870b57cec5SDimitry Andric   const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
7900b57cec5SDimitry Andric                                   Complain? &Reader.Diags : nullptr,
7910b57cec5SDimitry Andric                                   PP.getFileManager(),
7920b57cec5SDimitry Andric                                   SuggestedPredefines,
7930b57cec5SDimitry Andric                                   PP.getLangOpts());
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric bool SimpleASTReaderListener::ReadPreprocessorOptions(
7970b57cec5SDimitry Andric                                   const PreprocessorOptions &PPOpts,
7980b57cec5SDimitry Andric                                   bool Complain,
7990b57cec5SDimitry Andric                                   std::string &SuggestedPredefines) {
80061cfbce3SDimitry Andric   return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), nullptr,
80161cfbce3SDimitry Andric                                   PP.getFileManager(), SuggestedPredefines,
80261cfbce3SDimitry Andric                                   PP.getLangOpts(), OptionValidateNone);
8030b57cec5SDimitry Andric }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric /// Check the header search options deserialized from the control block
8060b57cec5SDimitry Andric /// against the header search options in an existing preprocessor.
8070b57cec5SDimitry Andric ///
8080b57cec5SDimitry Andric /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
8090b57cec5SDimitry Andric static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
8100b57cec5SDimitry Andric                                      StringRef SpecificModuleCachePath,
8110b57cec5SDimitry Andric                                      StringRef ExistingModuleCachePath,
8120b57cec5SDimitry Andric                                      DiagnosticsEngine *Diags,
813fe6060f1SDimitry Andric                                      const LangOptions &LangOpts,
814fe6060f1SDimitry Andric                                      const PreprocessorOptions &PPOpts) {
8150b57cec5SDimitry Andric   if (LangOpts.Modules) {
816fe6060f1SDimitry Andric     if (SpecificModuleCachePath != ExistingModuleCachePath &&
817fe6060f1SDimitry Andric         !PPOpts.AllowPCHWithDifferentModulesCachePath) {
8180b57cec5SDimitry Andric       if (Diags)
8190b57cec5SDimitry Andric         Diags->Report(diag::err_pch_modulecache_mismatch)
8200b57cec5SDimitry Andric           << SpecificModuleCachePath << ExistingModuleCachePath;
8210b57cec5SDimitry Andric       return true;
8220b57cec5SDimitry Andric     }
8230b57cec5SDimitry Andric   }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric   return false;
8260b57cec5SDimitry Andric }
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
8290b57cec5SDimitry Andric                                            StringRef SpecificModuleCachePath,
8300b57cec5SDimitry Andric                                            bool Complain) {
8310b57cec5SDimitry Andric   return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
8320b57cec5SDimitry Andric                                   PP.getHeaderSearchInfo().getModuleCachePath(),
8330b57cec5SDimitry Andric                                   Complain ? &Reader.Diags : nullptr,
834fe6060f1SDimitry Andric                                   PP.getLangOpts(), PP.getPreprocessorOpts());
8350b57cec5SDimitry Andric }
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
8380b57cec5SDimitry Andric   PP.setCounterValue(Value);
8390b57cec5SDimitry Andric }
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8420b57cec5SDimitry Andric // AST reader implementation
8430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8440b57cec5SDimitry Andric 
845fe6060f1SDimitry Andric static uint64_t readULEB(const unsigned char *&P) {
846fe6060f1SDimitry Andric   unsigned Length = 0;
847fe6060f1SDimitry Andric   const char *Error = nullptr;
848fe6060f1SDimitry Andric 
849fe6060f1SDimitry Andric   uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
850fe6060f1SDimitry Andric   if (Error)
851fe6060f1SDimitry Andric     llvm::report_fatal_error(Error);
852fe6060f1SDimitry Andric   P += Length;
853fe6060f1SDimitry Andric   return Val;
854fe6060f1SDimitry Andric }
855fe6060f1SDimitry Andric 
856fe6060f1SDimitry Andric /// Read ULEB-encoded key length and data length.
857fe6060f1SDimitry Andric static std::pair<unsigned, unsigned>
858fe6060f1SDimitry Andric readULEBKeyDataLength(const unsigned char *&P) {
859fe6060f1SDimitry Andric   unsigned KeyLen = readULEB(P);
860fe6060f1SDimitry Andric   if ((unsigned)KeyLen != KeyLen)
861fe6060f1SDimitry Andric     llvm::report_fatal_error("key too large");
862fe6060f1SDimitry Andric 
863fe6060f1SDimitry Andric   unsigned DataLen = readULEB(P);
864fe6060f1SDimitry Andric   if ((unsigned)DataLen != DataLen)
865fe6060f1SDimitry Andric     llvm::report_fatal_error("data too large");
866fe6060f1SDimitry Andric 
867fe6060f1SDimitry Andric   return std::make_pair(KeyLen, DataLen);
868fe6060f1SDimitry Andric }
869fe6060f1SDimitry Andric 
8700b57cec5SDimitry Andric void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
8710b57cec5SDimitry Andric                                            bool TakeOwnership) {
8720b57cec5SDimitry Andric   DeserializationListener = Listener;
8730b57cec5SDimitry Andric   OwnsDeserializationListener = TakeOwnership;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
8770b57cec5SDimitry Andric   return serialization::ComputeHash(Sel);
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric std::pair<unsigned, unsigned>
8810b57cec5SDimitry Andric ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
882fe6060f1SDimitry Andric   return readULEBKeyDataLength(d);
8830b57cec5SDimitry Andric }
8840b57cec5SDimitry Andric 
8850b57cec5SDimitry Andric ASTSelectorLookupTrait::internal_key_type
8860b57cec5SDimitry Andric ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
8870b57cec5SDimitry Andric   using namespace llvm::support;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric   SelectorTable &SelTable = Reader.getContext().Selectors;
8900b57cec5SDimitry Andric   unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
8910b57cec5SDimitry Andric   IdentifierInfo *FirstII = Reader.getLocalIdentifier(
8920b57cec5SDimitry Andric       F, endian::readNext<uint32_t, little, unaligned>(d));
8930b57cec5SDimitry Andric   if (N == 0)
8940b57cec5SDimitry Andric     return SelTable.getNullarySelector(FirstII);
8950b57cec5SDimitry Andric   else if (N == 1)
8960b57cec5SDimitry Andric     return SelTable.getUnarySelector(FirstII);
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric   SmallVector<IdentifierInfo *, 16> Args;
8990b57cec5SDimitry Andric   Args.push_back(FirstII);
9000b57cec5SDimitry Andric   for (unsigned I = 1; I != N; ++I)
9010b57cec5SDimitry Andric     Args.push_back(Reader.getLocalIdentifier(
9020b57cec5SDimitry Andric         F, endian::readNext<uint32_t, little, unaligned>(d)));
9030b57cec5SDimitry Andric 
9040b57cec5SDimitry Andric   return SelTable.getSelector(N, Args.data());
9050b57cec5SDimitry Andric }
9060b57cec5SDimitry Andric 
9070b57cec5SDimitry Andric ASTSelectorLookupTrait::data_type
9080b57cec5SDimitry Andric ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
9090b57cec5SDimitry Andric                                  unsigned DataLen) {
9100b57cec5SDimitry Andric   using namespace llvm::support;
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric   data_type Result;
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric   Result.ID = Reader.getGlobalSelectorID(
9150b57cec5SDimitry Andric       F, endian::readNext<uint32_t, little, unaligned>(d));
9160b57cec5SDimitry Andric   unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
9170b57cec5SDimitry Andric   unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
9180b57cec5SDimitry Andric   Result.InstanceBits = FullInstanceBits & 0x3;
9190b57cec5SDimitry Andric   Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
9200b57cec5SDimitry Andric   Result.FactoryBits = FullFactoryBits & 0x3;
9210b57cec5SDimitry Andric   Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
9220b57cec5SDimitry Andric   unsigned NumInstanceMethods = FullInstanceBits >> 3;
9230b57cec5SDimitry Andric   unsigned NumFactoryMethods = FullFactoryBits >> 3;
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   // Load instance methods
9260b57cec5SDimitry Andric   for (unsigned I = 0; I != NumInstanceMethods; ++I) {
9270b57cec5SDimitry Andric     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
9280b57cec5SDimitry Andric             F, endian::readNext<uint32_t, little, unaligned>(d)))
9290b57cec5SDimitry Andric       Result.Instance.push_back(Method);
9300b57cec5SDimitry Andric   }
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   // Load factory methods
9330b57cec5SDimitry Andric   for (unsigned I = 0; I != NumFactoryMethods; ++I) {
9340b57cec5SDimitry Andric     if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
9350b57cec5SDimitry Andric             F, endian::readNext<uint32_t, little, unaligned>(d)))
9360b57cec5SDimitry Andric       Result.Factory.push_back(Method);
9370b57cec5SDimitry Andric   }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric   return Result;
9400b57cec5SDimitry Andric }
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
9430b57cec5SDimitry Andric   return llvm::djbHash(a);
9440b57cec5SDimitry Andric }
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric std::pair<unsigned, unsigned>
9470b57cec5SDimitry Andric ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
948fe6060f1SDimitry Andric   return readULEBKeyDataLength(d);
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric 
9510b57cec5SDimitry Andric ASTIdentifierLookupTraitBase::internal_key_type
9520b57cec5SDimitry Andric ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
9530b57cec5SDimitry Andric   assert(n >= 2 && d[n-1] == '\0');
9540b57cec5SDimitry Andric   return StringRef((const char*) d, n-1);
9550b57cec5SDimitry Andric }
9560b57cec5SDimitry Andric 
9570b57cec5SDimitry Andric /// Whether the given identifier is "interesting".
9580b57cec5SDimitry Andric static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
9590b57cec5SDimitry Andric                                     bool IsModule) {
960927c847dSDimitry Andric   return II.hadMacroDefinition() || II.isPoisoned() ||
961927c847dSDimitry Andric          (!IsModule && II.getObjCOrBuiltinID()) ||
9620b57cec5SDimitry Andric          II.hasRevertedTokenIDToIdentifier() ||
9630b57cec5SDimitry Andric          (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
9640b57cec5SDimitry Andric           II.getFETokenInfo());
9650b57cec5SDimitry Andric }
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric static bool readBit(unsigned &Bits) {
9680b57cec5SDimitry Andric   bool Value = Bits & 0x1;
9690b57cec5SDimitry Andric   Bits >>= 1;
9700b57cec5SDimitry Andric   return Value;
9710b57cec5SDimitry Andric }
9720b57cec5SDimitry Andric 
9730b57cec5SDimitry Andric IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
9740b57cec5SDimitry Andric   using namespace llvm::support;
9750b57cec5SDimitry Andric 
9760b57cec5SDimitry Andric   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
9770b57cec5SDimitry Andric   return Reader.getGlobalIdentifierID(F, RawID >> 1);
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
9810b57cec5SDimitry Andric   if (!II.isFromAST()) {
9820b57cec5SDimitry Andric     II.setIsFromAST();
9830b57cec5SDimitry Andric     bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
9840b57cec5SDimitry Andric     if (isInterestingIdentifier(Reader, II, IsModule))
9850b57cec5SDimitry Andric       II.setChangedSinceDeserialization();
9860b57cec5SDimitry Andric   }
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
9890b57cec5SDimitry Andric IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
9900b57cec5SDimitry Andric                                                    const unsigned char* d,
9910b57cec5SDimitry Andric                                                    unsigned DataLen) {
9920b57cec5SDimitry Andric   using namespace llvm::support;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
9950b57cec5SDimitry Andric   bool IsInteresting = RawID & 0x01;
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   // Wipe out the "is interesting" bit.
9980b57cec5SDimitry Andric   RawID = RawID >> 1;
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   // Build the IdentifierInfo and link the identifier ID with it.
10010b57cec5SDimitry Andric   IdentifierInfo *II = KnownII;
10020b57cec5SDimitry Andric   if (!II) {
10030b57cec5SDimitry Andric     II = &Reader.getIdentifierTable().getOwn(k);
10040b57cec5SDimitry Andric     KnownII = II;
10050b57cec5SDimitry Andric   }
10060b57cec5SDimitry Andric   markIdentifierFromAST(Reader, *II);
10070b57cec5SDimitry Andric   Reader.markIdentifierUpToDate(II);
10080b57cec5SDimitry Andric 
10090b57cec5SDimitry Andric   IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
10100b57cec5SDimitry Andric   if (!IsInteresting) {
10110b57cec5SDimitry Andric     // For uninteresting identifiers, there's nothing else to do. Just notify
10120b57cec5SDimitry Andric     // the reader that we've finished loading this identifier.
10130b57cec5SDimitry Andric     Reader.SetIdentifierInfo(ID, II);
10140b57cec5SDimitry Andric     return II;
10150b57cec5SDimitry Andric   }
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
10180b57cec5SDimitry Andric   unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
10190b57cec5SDimitry Andric   bool CPlusPlusOperatorKeyword = readBit(Bits);
10200b57cec5SDimitry Andric   bool HasRevertedTokenIDToIdentifier = readBit(Bits);
10210b57cec5SDimitry Andric   bool Poisoned = readBit(Bits);
10220b57cec5SDimitry Andric   bool ExtensionToken = readBit(Bits);
10230b57cec5SDimitry Andric   bool HadMacroDefinition = readBit(Bits);
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric   assert(Bits == 0 && "Extra bits in the identifier?");
10260b57cec5SDimitry Andric   DataLen -= 8;
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric   // Set or check the various bits in the IdentifierInfo structure.
10290b57cec5SDimitry Andric   // Token IDs are read-only.
10300b57cec5SDimitry Andric   if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
10310b57cec5SDimitry Andric     II->revertTokenIDToIdentifier();
10320b57cec5SDimitry Andric   if (!F.isModule())
10330b57cec5SDimitry Andric     II->setObjCOrBuiltinID(ObjCOrBuiltinID);
10340b57cec5SDimitry Andric   assert(II->isExtensionToken() == ExtensionToken &&
10350b57cec5SDimitry Andric          "Incorrect extension token flag");
10360b57cec5SDimitry Andric   (void)ExtensionToken;
10370b57cec5SDimitry Andric   if (Poisoned)
10380b57cec5SDimitry Andric     II->setIsPoisoned(true);
10390b57cec5SDimitry Andric   assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
10400b57cec5SDimitry Andric          "Incorrect C++ operator keyword flag");
10410b57cec5SDimitry Andric   (void)CPlusPlusOperatorKeyword;
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   // If this identifier is a macro, deserialize the macro
10440b57cec5SDimitry Andric   // definition.
10450b57cec5SDimitry Andric   if (HadMacroDefinition) {
10460b57cec5SDimitry Andric     uint32_t MacroDirectivesOffset =
10470b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(d);
10480b57cec5SDimitry Andric     DataLen -= 4;
10490b57cec5SDimitry Andric 
10500b57cec5SDimitry Andric     Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
10510b57cec5SDimitry Andric   }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric   Reader.SetIdentifierInfo(ID, II);
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   // Read all of the declarations visible at global scope with this
10560b57cec5SDimitry Andric   // name.
10570b57cec5SDimitry Andric   if (DataLen > 0) {
10580b57cec5SDimitry Andric     SmallVector<uint32_t, 4> DeclIDs;
10590b57cec5SDimitry Andric     for (; DataLen > 0; DataLen -= 4)
10600b57cec5SDimitry Andric       DeclIDs.push_back(Reader.getGlobalDeclID(
10610b57cec5SDimitry Andric           F, endian::readNext<uint32_t, little, unaligned>(d)));
10620b57cec5SDimitry Andric     Reader.SetGloballyVisibleDecls(II, DeclIDs);
10630b57cec5SDimitry Andric   }
10640b57cec5SDimitry Andric 
10650b57cec5SDimitry Andric   return II;
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
10690b57cec5SDimitry Andric     : Kind(Name.getNameKind()) {
10700b57cec5SDimitry Andric   switch (Kind) {
10710b57cec5SDimitry Andric   case DeclarationName::Identifier:
10720b57cec5SDimitry Andric     Data = (uint64_t)Name.getAsIdentifierInfo();
10730b57cec5SDimitry Andric     break;
10740b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
10750b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
10760b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
10770b57cec5SDimitry Andric     Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
10780b57cec5SDimitry Andric     break;
10790b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
10800b57cec5SDimitry Andric     Data = Name.getCXXOverloadedOperator();
10810b57cec5SDimitry Andric     break;
10820b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
10830b57cec5SDimitry Andric     Data = (uint64_t)Name.getCXXLiteralIdentifier();
10840b57cec5SDimitry Andric     break;
10850b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
10860b57cec5SDimitry Andric     Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
10870b57cec5SDimitry Andric                ->getDeclName().getAsIdentifierInfo();
10880b57cec5SDimitry Andric     break;
10890b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
10900b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
10910b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
10920b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
10930b57cec5SDimitry Andric     Data = 0;
10940b57cec5SDimitry Andric     break;
10950b57cec5SDimitry Andric   }
10960b57cec5SDimitry Andric }
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric unsigned DeclarationNameKey::getHash() const {
10990b57cec5SDimitry Andric   llvm::FoldingSetNodeID ID;
11000b57cec5SDimitry Andric   ID.AddInteger(Kind);
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric   switch (Kind) {
11030b57cec5SDimitry Andric   case DeclarationName::Identifier:
11040b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
11050b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
11060b57cec5SDimitry Andric     ID.AddString(((IdentifierInfo*)Data)->getName());
11070b57cec5SDimitry Andric     break;
11080b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
11090b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
11100b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
11110b57cec5SDimitry Andric     ID.AddInteger(serialization::ComputeHash(Selector(Data)));
11120b57cec5SDimitry Andric     break;
11130b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
11140b57cec5SDimitry Andric     ID.AddInteger((OverloadedOperatorKind)Data);
11150b57cec5SDimitry Andric     break;
11160b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
11170b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
11180b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
11190b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
11200b57cec5SDimitry Andric     break;
11210b57cec5SDimitry Andric   }
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   return ID.ComputeHash();
11240b57cec5SDimitry Andric }
11250b57cec5SDimitry Andric 
11260b57cec5SDimitry Andric ModuleFile *
11270b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
11280b57cec5SDimitry Andric   using namespace llvm::support;
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
11310b57cec5SDimitry Andric   return Reader.getLocalModuleFile(F, ModuleFileID);
11320b57cec5SDimitry Andric }
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric std::pair<unsigned, unsigned>
11350b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
1136fe6060f1SDimitry Andric   return readULEBKeyDataLength(d);
11370b57cec5SDimitry Andric }
11380b57cec5SDimitry Andric 
11390b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::internal_key_type
11400b57cec5SDimitry Andric ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
11410b57cec5SDimitry Andric   using namespace llvm::support;
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric   auto Kind = (DeclarationName::NameKind)*d++;
11440b57cec5SDimitry Andric   uint64_t Data;
11450b57cec5SDimitry Andric   switch (Kind) {
11460b57cec5SDimitry Andric   case DeclarationName::Identifier:
11470b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
11480b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
11490b57cec5SDimitry Andric     Data = (uint64_t)Reader.getLocalIdentifier(
11500b57cec5SDimitry Andric         F, endian::readNext<uint32_t, little, unaligned>(d));
11510b57cec5SDimitry Andric     break;
11520b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
11530b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
11540b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
11550b57cec5SDimitry Andric     Data =
11560b57cec5SDimitry Andric         (uint64_t)Reader.getLocalSelector(
11570b57cec5SDimitry Andric                              F, endian::readNext<uint32_t, little, unaligned>(
11580b57cec5SDimitry Andric                                     d)).getAsOpaquePtr();
11590b57cec5SDimitry Andric     break;
11600b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
11610b57cec5SDimitry Andric     Data = *d++; // OverloadedOperatorKind
11620b57cec5SDimitry Andric     break;
11630b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
11640b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
11650b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
11660b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
11670b57cec5SDimitry Andric     Data = 0;
11680b57cec5SDimitry Andric     break;
11690b57cec5SDimitry Andric   }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric   return DeclarationNameKey(Kind, Data);
11720b57cec5SDimitry Andric }
11730b57cec5SDimitry Andric 
11740b57cec5SDimitry Andric void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
11750b57cec5SDimitry Andric                                                  const unsigned char *d,
11760b57cec5SDimitry Andric                                                  unsigned DataLen,
11770b57cec5SDimitry Andric                                                  data_type_builder &Val) {
11780b57cec5SDimitry Andric   using namespace llvm::support;
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
11810b57cec5SDimitry Andric     uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
11820b57cec5SDimitry Andric     Val.insert(Reader.getGlobalDeclID(F, LocalID));
11830b57cec5SDimitry Andric   }
11840b57cec5SDimitry Andric }
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
11870b57cec5SDimitry Andric                                               BitstreamCursor &Cursor,
11880b57cec5SDimitry Andric                                               uint64_t Offset,
11890b57cec5SDimitry Andric                                               DeclContext *DC) {
11900b57cec5SDimitry Andric   assert(Offset != 0);
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
11930b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
11940b57cec5SDimitry Andric     Error(std::move(Err));
11950b57cec5SDimitry Andric     return true;
11960b57cec5SDimitry Andric   }
11970b57cec5SDimitry Andric 
11980b57cec5SDimitry Andric   RecordData Record;
11990b57cec5SDimitry Andric   StringRef Blob;
12000b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
12010b57cec5SDimitry Andric   if (!MaybeCode) {
12020b57cec5SDimitry Andric     Error(MaybeCode.takeError());
12030b57cec5SDimitry Andric     return true;
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
12080b57cec5SDimitry Andric   if (!MaybeRecCode) {
12090b57cec5SDimitry Andric     Error(MaybeRecCode.takeError());
12100b57cec5SDimitry Andric     return true;
12110b57cec5SDimitry Andric   }
12120b57cec5SDimitry Andric   unsigned RecCode = MaybeRecCode.get();
12130b57cec5SDimitry Andric   if (RecCode != DECL_CONTEXT_LEXICAL) {
12140b57cec5SDimitry Andric     Error("Expected lexical block");
12150b57cec5SDimitry Andric     return true;
12160b57cec5SDimitry Andric   }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   assert(!isa<TranslationUnitDecl>(DC) &&
12190b57cec5SDimitry Andric          "expected a TU_UPDATE_LEXICAL record for TU");
12200b57cec5SDimitry Andric   // If we are handling a C++ class template instantiation, we can see multiple
12210b57cec5SDimitry Andric   // lexical updates for the same record. It's important that we select only one
12220b57cec5SDimitry Andric   // of them, so that field numbering works properly. Just pick the first one we
12230b57cec5SDimitry Andric   // see.
12240b57cec5SDimitry Andric   auto &Lex = LexicalDecls[DC];
12250b57cec5SDimitry Andric   if (!Lex.first) {
12260b57cec5SDimitry Andric     Lex = std::make_pair(
1227*bdd1243dSDimitry Andric         &M, llvm::ArrayRef(
12280b57cec5SDimitry Andric                 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
12290b57cec5SDimitry Andric                     Blob.data()),
12300b57cec5SDimitry Andric                 Blob.size() / 4));
12310b57cec5SDimitry Andric   }
12320b57cec5SDimitry Andric   DC->setHasExternalLexicalStorage(true);
12330b57cec5SDimitry Andric   return false;
12340b57cec5SDimitry Andric }
12350b57cec5SDimitry Andric 
12360b57cec5SDimitry Andric bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
12370b57cec5SDimitry Andric                                               BitstreamCursor &Cursor,
12380b57cec5SDimitry Andric                                               uint64_t Offset,
12390b57cec5SDimitry Andric                                               DeclID ID) {
12400b57cec5SDimitry Andric   assert(Offset != 0);
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
12430b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
12440b57cec5SDimitry Andric     Error(std::move(Err));
12450b57cec5SDimitry Andric     return true;
12460b57cec5SDimitry Andric   }
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric   RecordData Record;
12490b57cec5SDimitry Andric   StringRef Blob;
12500b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
12510b57cec5SDimitry Andric   if (!MaybeCode) {
12520b57cec5SDimitry Andric     Error(MaybeCode.takeError());
12530b57cec5SDimitry Andric     return true;
12540b57cec5SDimitry Andric   }
12550b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric   Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
12580b57cec5SDimitry Andric   if (!MaybeRecCode) {
12590b57cec5SDimitry Andric     Error(MaybeRecCode.takeError());
12600b57cec5SDimitry Andric     return true;
12610b57cec5SDimitry Andric   }
12620b57cec5SDimitry Andric   unsigned RecCode = MaybeRecCode.get();
12630b57cec5SDimitry Andric   if (RecCode != DECL_CONTEXT_VISIBLE) {
12640b57cec5SDimitry Andric     Error("Expected visible lookup table block");
12650b57cec5SDimitry Andric     return true;
12660b57cec5SDimitry Andric   }
12670b57cec5SDimitry Andric 
12680b57cec5SDimitry Andric   // We can't safely determine the primary context yet, so delay attaching the
12690b57cec5SDimitry Andric   // lookup table until we're done with recursive deserialization.
12700b57cec5SDimitry Andric   auto *Data = (const unsigned char*)Blob.data();
12710b57cec5SDimitry Andric   PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
12720b57cec5SDimitry Andric   return false;
12730b57cec5SDimitry Andric }
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric void ASTReader::Error(StringRef Msg) const {
12760b57cec5SDimitry Andric   Error(diag::err_fe_pch_malformed, Msg);
12770b57cec5SDimitry Andric   if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
12780b57cec5SDimitry Andric       !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
12790b57cec5SDimitry Andric     Diag(diag::note_module_cache_path)
12800b57cec5SDimitry Andric       << PP.getHeaderSearchInfo().getModuleCachePath();
12810b57cec5SDimitry Andric   }
12820b57cec5SDimitry Andric }
12830b57cec5SDimitry Andric 
1284480093f4SDimitry Andric void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1285480093f4SDimitry Andric                       StringRef Arg3) const {
12860b57cec5SDimitry Andric   if (Diags.isDiagnosticInFlight())
1287480093f4SDimitry Andric     Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
12880b57cec5SDimitry Andric   else
1289480093f4SDimitry Andric     Diag(DiagID) << Arg1 << Arg2 << Arg3;
12900b57cec5SDimitry Andric }
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric void ASTReader::Error(llvm::Error &&Err) const {
1293349cc55cSDimitry Andric   llvm::Error RemainingErr =
1294349cc55cSDimitry Andric       handleErrors(std::move(Err), [this](const DiagnosticError &E) {
1295349cc55cSDimitry Andric         auto Diag = E.getDiagnostic().second;
1296349cc55cSDimitry Andric 
1297349cc55cSDimitry Andric         // Ideally we'd just emit it, but have to handle a possible in-flight
1298349cc55cSDimitry Andric         // diagnostic. Note that the location is currently ignored as well.
1299349cc55cSDimitry Andric         auto NumArgs = Diag.getStorage()->NumDiagArgs;
1300349cc55cSDimitry Andric         assert(NumArgs <= 3 && "Can only have up to 3 arguments");
1301349cc55cSDimitry Andric         StringRef Arg1, Arg2, Arg3;
1302349cc55cSDimitry Andric         switch (NumArgs) {
1303349cc55cSDimitry Andric         case 3:
1304349cc55cSDimitry Andric           Arg3 = Diag.getStringArg(2);
1305*bdd1243dSDimitry Andric           [[fallthrough]];
1306349cc55cSDimitry Andric         case 2:
1307349cc55cSDimitry Andric           Arg2 = Diag.getStringArg(1);
1308*bdd1243dSDimitry Andric           [[fallthrough]];
1309349cc55cSDimitry Andric         case 1:
1310349cc55cSDimitry Andric           Arg1 = Diag.getStringArg(0);
1311349cc55cSDimitry Andric         }
1312349cc55cSDimitry Andric         Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
1313349cc55cSDimitry Andric       });
1314349cc55cSDimitry Andric   if (RemainingErr)
1315349cc55cSDimitry Andric     Error(toString(std::move(RemainingErr)));
13160b57cec5SDimitry Andric }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13190b57cec5SDimitry Andric // Source Manager Deserialization
13200b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13210b57cec5SDimitry Andric 
13220b57cec5SDimitry Andric /// Read the line table in the source manager block.
1323349cc55cSDimitry Andric void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
13240b57cec5SDimitry Andric   unsigned Idx = 0;
13250b57cec5SDimitry Andric   LineTableInfo &LineTable = SourceMgr.getLineTable();
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric   // Parse the file names
13280b57cec5SDimitry Andric   std::map<int, int> FileIDs;
13290b57cec5SDimitry Andric   FileIDs[-1] = -1; // For unspecified filenames.
13300b57cec5SDimitry Andric   for (unsigned I = 0; Record[Idx]; ++I) {
13310b57cec5SDimitry Andric     // Extract the file name
13320b57cec5SDimitry Andric     auto Filename = ReadPath(F, Record, Idx);
13330b57cec5SDimitry Andric     FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
13340b57cec5SDimitry Andric   }
13350b57cec5SDimitry Andric   ++Idx;
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric   // Parse the line entries
13380b57cec5SDimitry Andric   std::vector<LineEntry> Entries;
13390b57cec5SDimitry Andric   while (Idx < Record.size()) {
1340*bdd1243dSDimitry Andric     FileID FID = ReadFileID(F, Record, Idx);
13410b57cec5SDimitry Andric 
13420b57cec5SDimitry Andric     // Extract the line entries
13430b57cec5SDimitry Andric     unsigned NumEntries = Record[Idx++];
13440b57cec5SDimitry Andric     assert(NumEntries && "no line entries for file ID");
13450b57cec5SDimitry Andric     Entries.clear();
13460b57cec5SDimitry Andric     Entries.reserve(NumEntries);
13470b57cec5SDimitry Andric     for (unsigned I = 0; I != NumEntries; ++I) {
13480b57cec5SDimitry Andric       unsigned FileOffset = Record[Idx++];
13490b57cec5SDimitry Andric       unsigned LineNo = Record[Idx++];
13500b57cec5SDimitry Andric       int FilenameID = FileIDs[Record[Idx++]];
13510b57cec5SDimitry Andric       SrcMgr::CharacteristicKind FileKind
13520b57cec5SDimitry Andric         = (SrcMgr::CharacteristicKind)Record[Idx++];
13530b57cec5SDimitry Andric       unsigned IncludeOffset = Record[Idx++];
13540b57cec5SDimitry Andric       Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
13550b57cec5SDimitry Andric                                        FileKind, IncludeOffset));
13560b57cec5SDimitry Andric     }
1357*bdd1243dSDimitry Andric     LineTable.AddEntry(FID, Entries);
13580b57cec5SDimitry Andric   }
13590b57cec5SDimitry Andric }
13600b57cec5SDimitry Andric 
13610b57cec5SDimitry Andric /// Read a source manager block
1362349cc55cSDimitry Andric llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
13630b57cec5SDimitry Andric   using namespace SrcMgr;
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric   BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   // Set the source-location entry cursor to the current position in
13680b57cec5SDimitry Andric   // the stream. This cursor will be used to read the contents of the
13690b57cec5SDimitry Andric   // source manager block initially, and then lazily read
13700b57cec5SDimitry Andric   // source-location entries as needed.
13710b57cec5SDimitry Andric   SLocEntryCursor = F.Stream;
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric   // The stream itself is going to skip over the source manager block.
1374349cc55cSDimitry Andric   if (llvm::Error Err = F.Stream.SkipBlock())
1375349cc55cSDimitry Andric     return Err;
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   // Enter the source manager block.
1378349cc55cSDimitry Andric   if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
1379349cc55cSDimitry Andric     return Err;
13805ffd83dbSDimitry Andric   F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
13810b57cec5SDimitry Andric 
13820b57cec5SDimitry Andric   RecordData Record;
13830b57cec5SDimitry Andric   while (true) {
13840b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeE =
13850b57cec5SDimitry Andric         SLocEntryCursor.advanceSkippingSubblocks();
1386349cc55cSDimitry Andric     if (!MaybeE)
1387349cc55cSDimitry Andric       return MaybeE.takeError();
13880b57cec5SDimitry Andric     llvm::BitstreamEntry E = MaybeE.get();
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric     switch (E.Kind) {
13910b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
13920b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
1393349cc55cSDimitry Andric       return llvm::createStringError(std::errc::illegal_byte_sequence,
1394349cc55cSDimitry Andric                                      "malformed block record in AST file");
13950b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
1396349cc55cSDimitry Andric       return llvm::Error::success();
13970b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
13980b57cec5SDimitry Andric       // The interesting case.
13990b57cec5SDimitry Andric       break;
14000b57cec5SDimitry Andric     }
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric     // Read a record.
14030b57cec5SDimitry Andric     Record.clear();
14040b57cec5SDimitry Andric     StringRef Blob;
14050b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord =
14060b57cec5SDimitry Andric         SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1407349cc55cSDimitry Andric     if (!MaybeRecord)
1408349cc55cSDimitry Andric       return MaybeRecord.takeError();
14090b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
14100b57cec5SDimitry Andric     default:  // Default behavior: ignore.
14110b57cec5SDimitry Andric       break;
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric     case SM_SLOC_FILE_ENTRY:
14140b57cec5SDimitry Andric     case SM_SLOC_BUFFER_ENTRY:
14150b57cec5SDimitry Andric     case SM_SLOC_EXPANSION_ENTRY:
14160b57cec5SDimitry Andric       // Once we hit one of the source location entries, we're done.
1417349cc55cSDimitry Andric       return llvm::Error::success();
14180b57cec5SDimitry Andric     }
14190b57cec5SDimitry Andric   }
14200b57cec5SDimitry Andric }
14210b57cec5SDimitry Andric 
14220b57cec5SDimitry Andric bool ASTReader::ReadSLocEntry(int ID) {
14230b57cec5SDimitry Andric   if (ID == 0)
14240b57cec5SDimitry Andric     return false;
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
14270b57cec5SDimitry Andric     Error("source location entry ID out-of-range for AST file");
14280b57cec5SDimitry Andric     return true;
14290b57cec5SDimitry Andric   }
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric   // Local helper to read the (possibly-compressed) buffer data following the
14320b57cec5SDimitry Andric   // entry record.
14330b57cec5SDimitry Andric   auto ReadBuffer = [this](
14340b57cec5SDimitry Andric       BitstreamCursor &SLocEntryCursor,
14350b57cec5SDimitry Andric       StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
14360b57cec5SDimitry Andric     RecordData Record;
14370b57cec5SDimitry Andric     StringRef Blob;
14380b57cec5SDimitry Andric     Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
14390b57cec5SDimitry Andric     if (!MaybeCode) {
14400b57cec5SDimitry Andric       Error(MaybeCode.takeError());
14410b57cec5SDimitry Andric       return nullptr;
14420b57cec5SDimitry Andric     }
14430b57cec5SDimitry Andric     unsigned Code = MaybeCode.get();
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric     Expected<unsigned> MaybeRecCode =
14460b57cec5SDimitry Andric         SLocEntryCursor.readRecord(Code, Record, &Blob);
14470b57cec5SDimitry Andric     if (!MaybeRecCode) {
14480b57cec5SDimitry Andric       Error(MaybeRecCode.takeError());
14490b57cec5SDimitry Andric       return nullptr;
14500b57cec5SDimitry Andric     }
14510b57cec5SDimitry Andric     unsigned RecCode = MaybeRecCode.get();
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric     if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
1454*bdd1243dSDimitry Andric       // Inspect the first byte to differentiate zlib (\x78) and zstd
1455*bdd1243dSDimitry Andric       // (little-endian 0xFD2FB528).
1456*bdd1243dSDimitry Andric       const llvm::compression::Format F =
1457*bdd1243dSDimitry Andric           Blob.size() > 0 && Blob.data()[0] == 0x78
1458*bdd1243dSDimitry Andric               ? llvm::compression::Format::Zlib
1459*bdd1243dSDimitry Andric               : llvm::compression::Format::Zstd;
1460*bdd1243dSDimitry Andric       if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
1461*bdd1243dSDimitry Andric         Error(Reason);
14620b57cec5SDimitry Andric         return nullptr;
14630b57cec5SDimitry Andric       }
1464*bdd1243dSDimitry Andric       SmallVector<uint8_t, 0> Decompressed;
1465*bdd1243dSDimitry Andric       if (llvm::Error E = llvm::compression::decompress(
1466*bdd1243dSDimitry Andric               F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
14670b57cec5SDimitry Andric         Error("could not decompress embedded file contents: " +
14680b57cec5SDimitry Andric               llvm::toString(std::move(E)));
14690b57cec5SDimitry Andric         return nullptr;
14700b57cec5SDimitry Andric       }
1471753f127fSDimitry Andric       return llvm::MemoryBuffer::getMemBufferCopy(
1472*bdd1243dSDimitry Andric           llvm::toStringRef(Decompressed), Name);
14730b57cec5SDimitry Andric     } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
14740b57cec5SDimitry Andric       return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
14750b57cec5SDimitry Andric     } else {
14760b57cec5SDimitry Andric       Error("AST record has invalid code");
14770b57cec5SDimitry Andric       return nullptr;
14780b57cec5SDimitry Andric     }
14790b57cec5SDimitry Andric   };
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric   ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
14820b57cec5SDimitry Andric   if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
14835ffd83dbSDimitry Andric           F->SLocEntryOffsetsBase +
14840b57cec5SDimitry Andric           F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
14850b57cec5SDimitry Andric     Error(std::move(Err));
14860b57cec5SDimitry Andric     return true;
14870b57cec5SDimitry Andric   }
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
1490fe6060f1SDimitry Andric   SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
14910b57cec5SDimitry Andric 
14920b57cec5SDimitry Andric   ++NumSLocEntriesRead;
14930b57cec5SDimitry Andric   Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
14940b57cec5SDimitry Andric   if (!MaybeEntry) {
14950b57cec5SDimitry Andric     Error(MaybeEntry.takeError());
14960b57cec5SDimitry Andric     return true;
14970b57cec5SDimitry Andric   }
14980b57cec5SDimitry Andric   llvm::BitstreamEntry Entry = MaybeEntry.get();
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric   if (Entry.Kind != llvm::BitstreamEntry::Record) {
15010b57cec5SDimitry Andric     Error("incorrectly-formatted source location entry in AST file");
15020b57cec5SDimitry Andric     return true;
15030b57cec5SDimitry Andric   }
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   RecordData Record;
15060b57cec5SDimitry Andric   StringRef Blob;
15070b57cec5SDimitry Andric   Expected<unsigned> MaybeSLOC =
15080b57cec5SDimitry Andric       SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
15090b57cec5SDimitry Andric   if (!MaybeSLOC) {
15100b57cec5SDimitry Andric     Error(MaybeSLOC.takeError());
15110b57cec5SDimitry Andric     return true;
15120b57cec5SDimitry Andric   }
15130b57cec5SDimitry Andric   switch (MaybeSLOC.get()) {
15140b57cec5SDimitry Andric   default:
15150b57cec5SDimitry Andric     Error("incorrectly-formatted source location entry in AST file");
15160b57cec5SDimitry Andric     return true;
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric   case SM_SLOC_FILE_ENTRY: {
15190b57cec5SDimitry Andric     // We will detect whether a file changed and return 'Failure' for it, but
15200b57cec5SDimitry Andric     // we will also try to fail gracefully by setting up the SLocEntry.
15210b57cec5SDimitry Andric     unsigned InputID = Record[4];
15220b57cec5SDimitry Andric     InputFile IF = getInputFile(*F, InputID);
1523*bdd1243dSDimitry Andric     OptionalFileEntryRef File = IF.getFile();
15240b57cec5SDimitry Andric     bool OverriddenBuffer = IF.isOverridden();
15250b57cec5SDimitry Andric 
15260b57cec5SDimitry Andric     // Note that we only check if a File was returned. If it was out-of-date
15270b57cec5SDimitry Andric     // we have complained but we will continue creating a FileID to recover
15280b57cec5SDimitry Andric     // gracefully.
15290b57cec5SDimitry Andric     if (!File)
15300b57cec5SDimitry Andric       return true;
15310b57cec5SDimitry Andric 
15320b57cec5SDimitry Andric     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
15330b57cec5SDimitry Andric     if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
15340b57cec5SDimitry Andric       // This is the module's main file.
15350b57cec5SDimitry Andric       IncludeLoc = getImportLocation(F);
15360b57cec5SDimitry Andric     }
15370b57cec5SDimitry Andric     SrcMgr::CharacteristicKind
15380b57cec5SDimitry Andric       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1539e8d8bef9SDimitry Andric     FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
1540e8d8bef9SDimitry Andric                                         BaseOffset + Record[0]);
15410b57cec5SDimitry Andric     SrcMgr::FileInfo &FileInfo =
15420b57cec5SDimitry Andric           const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
15430b57cec5SDimitry Andric     FileInfo.NumCreatedFIDs = Record[5];
15440b57cec5SDimitry Andric     if (Record[3])
15450b57cec5SDimitry Andric       FileInfo.setHasLineDirectives();
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric     unsigned NumFileDecls = Record[7];
15480b57cec5SDimitry Andric     if (NumFileDecls && ContextObj) {
1549a7dea167SDimitry Andric       const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
15500b57cec5SDimitry Andric       assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1551*bdd1243dSDimitry Andric       FileDeclIDs[FID] =
1552*bdd1243dSDimitry Andric           FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
15530b57cec5SDimitry Andric     }
15540b57cec5SDimitry Andric 
1555e8d8bef9SDimitry Andric     const SrcMgr::ContentCache &ContentCache =
1556e8d8bef9SDimitry Andric         SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
1557e8d8bef9SDimitry Andric     if (OverriddenBuffer && !ContentCache.BufferOverridden &&
1558e8d8bef9SDimitry Andric         ContentCache.ContentsEntry == ContentCache.OrigEntry &&
1559e8d8bef9SDimitry Andric         !ContentCache.getBufferIfLoaded()) {
15600b57cec5SDimitry Andric       auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
15610b57cec5SDimitry Andric       if (!Buffer)
15620b57cec5SDimitry Andric         return true;
1563e8d8bef9SDimitry Andric       SourceMgr.overrideFileContents(*File, std::move(Buffer));
15640b57cec5SDimitry Andric     }
15650b57cec5SDimitry Andric 
15660b57cec5SDimitry Andric     break;
15670b57cec5SDimitry Andric   }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric   case SM_SLOC_BUFFER_ENTRY: {
15700b57cec5SDimitry Andric     const char *Name = Blob.data();
15710b57cec5SDimitry Andric     unsigned Offset = Record[0];
15720b57cec5SDimitry Andric     SrcMgr::CharacteristicKind
15730b57cec5SDimitry Andric       FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
15740b57cec5SDimitry Andric     SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
15750b57cec5SDimitry Andric     if (IncludeLoc.isInvalid() && F->isModule()) {
15760b57cec5SDimitry Andric       IncludeLoc = getImportLocation(F);
15770b57cec5SDimitry Andric     }
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric     auto Buffer = ReadBuffer(SLocEntryCursor, Name);
15800b57cec5SDimitry Andric     if (!Buffer)
15810b57cec5SDimitry Andric       return true;
15820b57cec5SDimitry Andric     SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
15830b57cec5SDimitry Andric                            BaseOffset + Offset, IncludeLoc);
15840b57cec5SDimitry Andric     break;
15850b57cec5SDimitry Andric   }
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   case SM_SLOC_EXPANSION_ENTRY: {
158881ad6265SDimitry Andric     LocSeq::State Seq;
158981ad6265SDimitry Andric     SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
159081ad6265SDimitry Andric     SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
159181ad6265SDimitry Andric     SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
159281ad6265SDimitry Andric     SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
159381ad6265SDimitry Andric                                  Record[5], Record[4], ID,
15940b57cec5SDimitry Andric                                  BaseOffset + Record[0]);
15950b57cec5SDimitry Andric     break;
15960b57cec5SDimitry Andric   }
15970b57cec5SDimitry Andric   }
15980b57cec5SDimitry Andric 
15990b57cec5SDimitry Andric   return false;
16000b57cec5SDimitry Andric }
16010b57cec5SDimitry Andric 
16020b57cec5SDimitry Andric std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
16030b57cec5SDimitry Andric   if (ID == 0)
16040b57cec5SDimitry Andric     return std::make_pair(SourceLocation(), "");
16050b57cec5SDimitry Andric 
16060b57cec5SDimitry Andric   if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
16070b57cec5SDimitry Andric     Error("source location entry ID out-of-range for AST file");
16080b57cec5SDimitry Andric     return std::make_pair(SourceLocation(), "");
16090b57cec5SDimitry Andric   }
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   // Find which module file this entry lands in.
16120b57cec5SDimitry Andric   ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
16130b57cec5SDimitry Andric   if (!M->isModule())
16140b57cec5SDimitry Andric     return std::make_pair(SourceLocation(), "");
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   // FIXME: Can we map this down to a particular submodule? That would be
16170b57cec5SDimitry Andric   // ideal.
16180b57cec5SDimitry Andric   return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
16190b57cec5SDimitry Andric }
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric /// Find the location where the module F is imported.
16220b57cec5SDimitry Andric SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
16230b57cec5SDimitry Andric   if (F->ImportLoc.isValid())
16240b57cec5SDimitry Andric     return F->ImportLoc;
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   // Otherwise we have a PCH. It's considered to be "imported" at the first
16270b57cec5SDimitry Andric   // location of its includer.
16280b57cec5SDimitry Andric   if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
16290b57cec5SDimitry Andric     // Main file is the importer.
16300b57cec5SDimitry Andric     assert(SourceMgr.getMainFileID().isValid() && "missing main file");
16310b57cec5SDimitry Andric     return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
16320b57cec5SDimitry Andric   }
16330b57cec5SDimitry Andric   return F->ImportedBy[0]->FirstLoc;
16340b57cec5SDimitry Andric }
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric /// Enter a subblock of the specified BlockID with the specified cursor. Read
16370b57cec5SDimitry Andric /// the abbreviations that are at the top of the block and then leave the cursor
16380b57cec5SDimitry Andric /// pointing into the block.
1639349cc55cSDimitry Andric llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
1640349cc55cSDimitry Andric                                         unsigned BlockID,
16415ffd83dbSDimitry Andric                                         uint64_t *StartOfBlockOffset) {
1642349cc55cSDimitry Andric   if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
1643349cc55cSDimitry Andric     return Err;
16440b57cec5SDimitry Andric 
16455ffd83dbSDimitry Andric   if (StartOfBlockOffset)
16465ffd83dbSDimitry Andric     *StartOfBlockOffset = Cursor.GetCurrentBitNo();
16475ffd83dbSDimitry Andric 
16480b57cec5SDimitry Andric   while (true) {
16490b57cec5SDimitry Andric     uint64_t Offset = Cursor.GetCurrentBitNo();
16500b57cec5SDimitry Andric     Expected<unsigned> MaybeCode = Cursor.ReadCode();
1651349cc55cSDimitry Andric     if (!MaybeCode)
1652349cc55cSDimitry Andric       return MaybeCode.takeError();
16530b57cec5SDimitry Andric     unsigned Code = MaybeCode.get();
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric     // We expect all abbrevs to be at the start of the block.
16560b57cec5SDimitry Andric     if (Code != llvm::bitc::DEFINE_ABBREV) {
1657349cc55cSDimitry Andric       if (llvm::Error Err = Cursor.JumpToBit(Offset))
1658349cc55cSDimitry Andric         return Err;
1659349cc55cSDimitry Andric       return llvm::Error::success();
16600b57cec5SDimitry Andric     }
1661349cc55cSDimitry Andric     if (llvm::Error Err = Cursor.ReadAbbrevRecord())
1662349cc55cSDimitry Andric       return Err;
16630b57cec5SDimitry Andric   }
16640b57cec5SDimitry Andric }
16650b57cec5SDimitry Andric 
16660b57cec5SDimitry Andric Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
16670b57cec5SDimitry Andric                            unsigned &Idx) {
16680b57cec5SDimitry Andric   Token Tok;
16690b57cec5SDimitry Andric   Tok.startToken();
16700b57cec5SDimitry Andric   Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1671*bdd1243dSDimitry Andric   Tok.setKind((tok::TokenKind)Record[Idx++]);
1672*bdd1243dSDimitry Andric   Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1673*bdd1243dSDimitry Andric 
1674*bdd1243dSDimitry Andric   if (Tok.isAnnotation()) {
1675*bdd1243dSDimitry Andric     Tok.setAnnotationEndLoc(ReadSourceLocation(F, Record, Idx));
1676*bdd1243dSDimitry Andric     switch (Tok.getKind()) {
1677*bdd1243dSDimitry Andric     case tok::annot_pragma_loop_hint: {
1678*bdd1243dSDimitry Andric       auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
1679*bdd1243dSDimitry Andric       Info->PragmaName = ReadToken(F, Record, Idx);
1680*bdd1243dSDimitry Andric       Info->Option = ReadToken(F, Record, Idx);
1681*bdd1243dSDimitry Andric       unsigned NumTokens = Record[Idx++];
1682*bdd1243dSDimitry Andric       SmallVector<Token, 4> Toks;
1683*bdd1243dSDimitry Andric       Toks.reserve(NumTokens);
1684*bdd1243dSDimitry Andric       for (unsigned I = 0; I < NumTokens; ++I)
1685*bdd1243dSDimitry Andric         Toks.push_back(ReadToken(F, Record, Idx));
1686*bdd1243dSDimitry Andric       Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
1687*bdd1243dSDimitry Andric       Tok.setAnnotationValue(static_cast<void *>(Info));
1688*bdd1243dSDimitry Andric       break;
1689*bdd1243dSDimitry Andric     }
1690*bdd1243dSDimitry Andric     // Some annotation tokens do not use the PtrData field.
1691*bdd1243dSDimitry Andric     case tok::annot_pragma_openmp:
1692*bdd1243dSDimitry Andric     case tok::annot_pragma_openmp_end:
1693*bdd1243dSDimitry Andric     case tok::annot_pragma_unused:
1694*bdd1243dSDimitry Andric       break;
1695*bdd1243dSDimitry Andric     default:
1696*bdd1243dSDimitry Andric       llvm_unreachable("missing deserialization code for annotation token");
1697*bdd1243dSDimitry Andric     }
1698*bdd1243dSDimitry Andric   } else {
16990b57cec5SDimitry Andric     Tok.setLength(Record[Idx++]);
17000b57cec5SDimitry Andric     if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
17010b57cec5SDimitry Andric       Tok.setIdentifierInfo(II);
1702*bdd1243dSDimitry Andric   }
17030b57cec5SDimitry Andric   return Tok;
17040b57cec5SDimitry Andric }
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
17070b57cec5SDimitry Andric   BitstreamCursor &Stream = F.MacroCursor;
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   // Keep track of where we are in the stream, then jump back there
17100b57cec5SDimitry Andric   // after reading this macro.
17110b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Stream);
17120b57cec5SDimitry Andric 
17130b57cec5SDimitry Andric   if (llvm::Error Err = Stream.JumpToBit(Offset)) {
17140b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
17150b57cec5SDimitry Andric     consumeError(std::move(Err));
17160b57cec5SDimitry Andric     return nullptr;
17170b57cec5SDimitry Andric   }
17180b57cec5SDimitry Andric   RecordData Record;
17190b57cec5SDimitry Andric   SmallVector<IdentifierInfo*, 16> MacroParams;
17200b57cec5SDimitry Andric   MacroInfo *Macro = nullptr;
172181ad6265SDimitry Andric   llvm::MutableArrayRef<Token> MacroTokens;
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   while (true) {
17240b57cec5SDimitry Andric     // Advance to the next record, but if we get to the end of the block, don't
17250b57cec5SDimitry Andric     // pop it (removing all the abbreviations from the cursor) since we want to
17260b57cec5SDimitry Andric     // be able to reseek within the block and read entries.
17270b57cec5SDimitry Andric     unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
17280b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
17290b57cec5SDimitry Andric         Stream.advanceSkippingSubblocks(Flags);
17300b57cec5SDimitry Andric     if (!MaybeEntry) {
17310b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
17320b57cec5SDimitry Andric       return Macro;
17330b57cec5SDimitry Andric     }
17340b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric     switch (Entry.Kind) {
17370b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
17380b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
17390b57cec5SDimitry Andric       Error("malformed block record in AST file");
17400b57cec5SDimitry Andric       return Macro;
17410b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
17420b57cec5SDimitry Andric       return Macro;
17430b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
17440b57cec5SDimitry Andric       // The interesting case.
17450b57cec5SDimitry Andric       break;
17460b57cec5SDimitry Andric     }
17470b57cec5SDimitry Andric 
17480b57cec5SDimitry Andric     // Read a record.
17490b57cec5SDimitry Andric     Record.clear();
17500b57cec5SDimitry Andric     PreprocessorRecordTypes RecType;
17510b57cec5SDimitry Andric     if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
17520b57cec5SDimitry Andric       RecType = (PreprocessorRecordTypes)MaybeRecType.get();
17530b57cec5SDimitry Andric     else {
17540b57cec5SDimitry Andric       Error(MaybeRecType.takeError());
17550b57cec5SDimitry Andric       return Macro;
17560b57cec5SDimitry Andric     }
17570b57cec5SDimitry Andric     switch (RecType) {
17580b57cec5SDimitry Andric     case PP_MODULE_MACRO:
17590b57cec5SDimitry Andric     case PP_MACRO_DIRECTIVE_HISTORY:
17600b57cec5SDimitry Andric       return Macro;
17610b57cec5SDimitry Andric 
17620b57cec5SDimitry Andric     case PP_MACRO_OBJECT_LIKE:
17630b57cec5SDimitry Andric     case PP_MACRO_FUNCTION_LIKE: {
17640b57cec5SDimitry Andric       // If we already have a macro, that means that we've hit the end
17650b57cec5SDimitry Andric       // of the definition of the macro we were looking for. We're
17660b57cec5SDimitry Andric       // done.
17670b57cec5SDimitry Andric       if (Macro)
17680b57cec5SDimitry Andric         return Macro;
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric       unsigned NextIndex = 1; // Skip identifier ID.
17710b57cec5SDimitry Andric       SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
17720b57cec5SDimitry Andric       MacroInfo *MI = PP.AllocateMacroInfo(Loc);
17730b57cec5SDimitry Andric       MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
17740b57cec5SDimitry Andric       MI->setIsUsed(Record[NextIndex++]);
17750b57cec5SDimitry Andric       MI->setUsedForHeaderGuard(Record[NextIndex++]);
177681ad6265SDimitry Andric       MacroTokens = MI->allocateTokens(Record[NextIndex++],
177781ad6265SDimitry Andric                                        PP.getPreprocessorAllocator());
17780b57cec5SDimitry Andric       if (RecType == PP_MACRO_FUNCTION_LIKE) {
17790b57cec5SDimitry Andric         // Decode function-like macro info.
17800b57cec5SDimitry Andric         bool isC99VarArgs = Record[NextIndex++];
17810b57cec5SDimitry Andric         bool isGNUVarArgs = Record[NextIndex++];
17820b57cec5SDimitry Andric         bool hasCommaPasting = Record[NextIndex++];
17830b57cec5SDimitry Andric         MacroParams.clear();
17840b57cec5SDimitry Andric         unsigned NumArgs = Record[NextIndex++];
17850b57cec5SDimitry Andric         for (unsigned i = 0; i != NumArgs; ++i)
17860b57cec5SDimitry Andric           MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric         // Install function-like macro info.
17890b57cec5SDimitry Andric         MI->setIsFunctionLike();
17900b57cec5SDimitry Andric         if (isC99VarArgs) MI->setIsC99Varargs();
17910b57cec5SDimitry Andric         if (isGNUVarArgs) MI->setIsGNUVarargs();
17920b57cec5SDimitry Andric         if (hasCommaPasting) MI->setHasCommaPasting();
17930b57cec5SDimitry Andric         MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
17940b57cec5SDimitry Andric       }
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric       // Remember that we saw this macro last so that we add the tokens that
17970b57cec5SDimitry Andric       // form its body to it.
17980b57cec5SDimitry Andric       Macro = MI;
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric       if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
18010b57cec5SDimitry Andric           Record[NextIndex]) {
18020b57cec5SDimitry Andric         // We have a macro definition. Register the association
18030b57cec5SDimitry Andric         PreprocessedEntityID
18040b57cec5SDimitry Andric             GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
18050b57cec5SDimitry Andric         PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
18060b57cec5SDimitry Andric         PreprocessingRecord::PPEntityID PPID =
18070b57cec5SDimitry Andric             PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
18080b57cec5SDimitry Andric         MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
18090b57cec5SDimitry Andric             PPRec.getPreprocessedEntity(PPID));
18100b57cec5SDimitry Andric         if (PPDef)
18110b57cec5SDimitry Andric           PPRec.RegisterMacroDefinition(Macro, PPDef);
18120b57cec5SDimitry Andric       }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric       ++NumMacrosRead;
18150b57cec5SDimitry Andric       break;
18160b57cec5SDimitry Andric     }
18170b57cec5SDimitry Andric 
18180b57cec5SDimitry Andric     case PP_TOKEN: {
18190b57cec5SDimitry Andric       // If we see a TOKEN before a PP_MACRO_*, then the file is
18200b57cec5SDimitry Andric       // erroneous, just pretend we didn't see this.
18210b57cec5SDimitry Andric       if (!Macro) break;
182281ad6265SDimitry Andric       if (MacroTokens.empty()) {
182381ad6265SDimitry Andric         Error("unexpected number of macro tokens for a macro in AST file");
182481ad6265SDimitry Andric         return Macro;
182581ad6265SDimitry Andric       }
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric       unsigned Idx = 0;
182881ad6265SDimitry Andric       MacroTokens[0] = ReadToken(F, Record, Idx);
182981ad6265SDimitry Andric       MacroTokens = MacroTokens.drop_front();
18300b57cec5SDimitry Andric       break;
18310b57cec5SDimitry Andric     }
18320b57cec5SDimitry Andric     }
18330b57cec5SDimitry Andric   }
18340b57cec5SDimitry Andric }
18350b57cec5SDimitry Andric 
18360b57cec5SDimitry Andric PreprocessedEntityID
18370b57cec5SDimitry Andric ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
18380b57cec5SDimitry Andric                                          unsigned LocalID) const {
18390b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
18400b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::const_iterator
18430b57cec5SDimitry Andric     I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
18440b57cec5SDimitry Andric   assert(I != M.PreprocessedEntityRemap.end()
18450b57cec5SDimitry Andric          && "Invalid index into preprocessed entity index remap");
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric   return LocalID + I->second;
18480b57cec5SDimitry Andric }
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
18510b57cec5SDimitry Andric   return llvm::hash_combine(ikey.Size, ikey.ModTime);
18520b57cec5SDimitry Andric }
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric HeaderFileInfoTrait::internal_key_type
18550b57cec5SDimitry Andric HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
18560b57cec5SDimitry Andric   internal_key_type ikey = {FE->getSize(),
18570b57cec5SDimitry Andric                             M.HasTimestamps ? FE->getModificationTime() : 0,
18580b57cec5SDimitry Andric                             FE->getName(), /*Imported*/ false};
18590b57cec5SDimitry Andric   return ikey;
18600b57cec5SDimitry Andric }
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
18630b57cec5SDimitry Andric   if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
18640b57cec5SDimitry Andric     return false;
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric   if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
18670b57cec5SDimitry Andric     return true;
18680b57cec5SDimitry Andric 
18690b57cec5SDimitry Andric   // Determine whether the actual files are equivalent.
18700b57cec5SDimitry Andric   FileManager &FileMgr = Reader.getFileManager();
18710b57cec5SDimitry Andric   auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1872a7dea167SDimitry Andric     if (!Key.Imported) {
1873a7dea167SDimitry Andric       if (auto File = FileMgr.getFile(Key.Filename))
1874a7dea167SDimitry Andric         return *File;
1875a7dea167SDimitry Andric       return nullptr;
1876a7dea167SDimitry Andric     }
18770b57cec5SDimitry Andric 
18785ffd83dbSDimitry Andric     std::string Resolved = std::string(Key.Filename);
18790b57cec5SDimitry Andric     Reader.ResolveImportedPath(M, Resolved);
1880a7dea167SDimitry Andric     if (auto File = FileMgr.getFile(Resolved))
1881a7dea167SDimitry Andric       return *File;
1882a7dea167SDimitry Andric     return nullptr;
18830b57cec5SDimitry Andric   };
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric   const FileEntry *FEA = GetFile(a);
18860b57cec5SDimitry Andric   const FileEntry *FEB = GetFile(b);
18870b57cec5SDimitry Andric   return FEA && FEA == FEB;
18880b57cec5SDimitry Andric }
18890b57cec5SDimitry Andric 
18900b57cec5SDimitry Andric std::pair<unsigned, unsigned>
18910b57cec5SDimitry Andric HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
1892fe6060f1SDimitry Andric   return readULEBKeyDataLength(d);
18930b57cec5SDimitry Andric }
18940b57cec5SDimitry Andric 
18950b57cec5SDimitry Andric HeaderFileInfoTrait::internal_key_type
18960b57cec5SDimitry Andric HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
18970b57cec5SDimitry Andric   using namespace llvm::support;
18980b57cec5SDimitry Andric 
18990b57cec5SDimitry Andric   internal_key_type ikey;
19000b57cec5SDimitry Andric   ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
19010b57cec5SDimitry Andric   ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
19020b57cec5SDimitry Andric   ikey.Filename = (const char *)d;
19030b57cec5SDimitry Andric   ikey.Imported = true;
19040b57cec5SDimitry Andric   return ikey;
19050b57cec5SDimitry Andric }
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric HeaderFileInfoTrait::data_type
19080b57cec5SDimitry Andric HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
19090b57cec5SDimitry Andric                               unsigned DataLen) {
19100b57cec5SDimitry Andric   using namespace llvm::support;
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric   const unsigned char *End = d + DataLen;
19130b57cec5SDimitry Andric   HeaderFileInfo HFI;
19140b57cec5SDimitry Andric   unsigned Flags = *d++;
19150b57cec5SDimitry Andric   // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
19160b57cec5SDimitry Andric   HFI.isImport |= (Flags >> 5) & 0x01;
19170b57cec5SDimitry Andric   HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
19180b57cec5SDimitry Andric   HFI.DirInfo = (Flags >> 1) & 0x07;
19190b57cec5SDimitry Andric   HFI.IndexHeaderMapHeader = Flags & 0x01;
19200b57cec5SDimitry Andric   HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
19210b57cec5SDimitry Andric       M, endian::readNext<uint32_t, little, unaligned>(d));
19220b57cec5SDimitry Andric   if (unsigned FrameworkOffset =
19230b57cec5SDimitry Andric           endian::readNext<uint32_t, little, unaligned>(d)) {
19240b57cec5SDimitry Andric     // The framework offset is 1 greater than the actual offset,
19250b57cec5SDimitry Andric     // since 0 is used as an indicator for "no framework name".
19260b57cec5SDimitry Andric     StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
19270b57cec5SDimitry Andric     HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
19280b57cec5SDimitry Andric   }
19290b57cec5SDimitry Andric 
19300b57cec5SDimitry Andric   assert((End - d) % 4 == 0 &&
19310b57cec5SDimitry Andric          "Wrong data length in HeaderFileInfo deserialization");
19320b57cec5SDimitry Andric   while (d != End) {
19330b57cec5SDimitry Andric     uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
1934*bdd1243dSDimitry Andric     auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
1935*bdd1243dSDimitry Andric     LocalSMID >>= 3;
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric     // This header is part of a module. Associate it with the module to enable
19380b57cec5SDimitry Andric     // implicit module import.
19390b57cec5SDimitry Andric     SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
19400b57cec5SDimitry Andric     Module *Mod = Reader.getSubmodule(GlobalSMID);
19410b57cec5SDimitry Andric     FileManager &FileMgr = Reader.getFileManager();
19420b57cec5SDimitry Andric     ModuleMap &ModMap =
19430b57cec5SDimitry Andric         Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
19440b57cec5SDimitry Andric 
19455ffd83dbSDimitry Andric     std::string Filename = std::string(key.Filename);
19460b57cec5SDimitry Andric     if (key.Imported)
19470b57cec5SDimitry Andric       Reader.ResolveImportedPath(M, Filename);
1948fe6060f1SDimitry Andric     // FIXME: NameAsWritten
1949fe6060f1SDimitry Andric     Module::Header H = {std::string(key.Filename), "",
1950*bdd1243dSDimitry Andric                         FileMgr.getOptionalFileRef(Filename)};
19510b57cec5SDimitry Andric     ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1952*bdd1243dSDimitry Andric     HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
19530b57cec5SDimitry Andric   }
19540b57cec5SDimitry Andric 
19550b57cec5SDimitry Andric   // This HeaderFileInfo was externally loaded.
19560b57cec5SDimitry Andric   HFI.External = true;
19570b57cec5SDimitry Andric   HFI.IsValid = true;
19580b57cec5SDimitry Andric   return HFI;
19590b57cec5SDimitry Andric }
19600b57cec5SDimitry Andric 
19615ffd83dbSDimitry Andric void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
19625ffd83dbSDimitry Andric                                 uint32_t MacroDirectivesOffset) {
19630b57cec5SDimitry Andric   assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
19640b57cec5SDimitry Andric   PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
19650b57cec5SDimitry Andric }
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric void ASTReader::ReadDefinedMacros() {
19680b57cec5SDimitry Andric   // Note that we are loading defined macros.
19690b57cec5SDimitry Andric   Deserializing Macros(this);
19700b57cec5SDimitry Andric 
19710b57cec5SDimitry Andric   for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
19720b57cec5SDimitry Andric     BitstreamCursor &MacroCursor = I.MacroCursor;
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric     // If there was no preprocessor block, skip this file.
19750b57cec5SDimitry Andric     if (MacroCursor.getBitcodeBytes().empty())
19760b57cec5SDimitry Andric       continue;
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric     BitstreamCursor Cursor = MacroCursor;
19790b57cec5SDimitry Andric     if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
19800b57cec5SDimitry Andric       Error(std::move(Err));
19810b57cec5SDimitry Andric       return;
19820b57cec5SDimitry Andric     }
19830b57cec5SDimitry Andric 
19840b57cec5SDimitry Andric     RecordData Record;
19850b57cec5SDimitry Andric     while (true) {
19860b57cec5SDimitry Andric       Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
19870b57cec5SDimitry Andric       if (!MaybeE) {
19880b57cec5SDimitry Andric         Error(MaybeE.takeError());
19890b57cec5SDimitry Andric         return;
19900b57cec5SDimitry Andric       }
19910b57cec5SDimitry Andric       llvm::BitstreamEntry E = MaybeE.get();
19920b57cec5SDimitry Andric 
19930b57cec5SDimitry Andric       switch (E.Kind) {
19940b57cec5SDimitry Andric       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
19950b57cec5SDimitry Andric       case llvm::BitstreamEntry::Error:
19960b57cec5SDimitry Andric         Error("malformed block record in AST file");
19970b57cec5SDimitry Andric         return;
19980b57cec5SDimitry Andric       case llvm::BitstreamEntry::EndBlock:
19990b57cec5SDimitry Andric         goto NextCursor;
20000b57cec5SDimitry Andric 
20010b57cec5SDimitry Andric       case llvm::BitstreamEntry::Record: {
20020b57cec5SDimitry Andric         Record.clear();
20030b57cec5SDimitry Andric         Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
20040b57cec5SDimitry Andric         if (!MaybeRecord) {
20050b57cec5SDimitry Andric           Error(MaybeRecord.takeError());
20060b57cec5SDimitry Andric           return;
20070b57cec5SDimitry Andric         }
20080b57cec5SDimitry Andric         switch (MaybeRecord.get()) {
20090b57cec5SDimitry Andric         default:  // Default behavior: ignore.
20100b57cec5SDimitry Andric           break;
20110b57cec5SDimitry Andric 
20120b57cec5SDimitry Andric         case PP_MACRO_OBJECT_LIKE:
20130b57cec5SDimitry Andric         case PP_MACRO_FUNCTION_LIKE: {
20140b57cec5SDimitry Andric           IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
20150b57cec5SDimitry Andric           if (II->isOutOfDate())
20160b57cec5SDimitry Andric             updateOutOfDateIdentifier(*II);
20170b57cec5SDimitry Andric           break;
20180b57cec5SDimitry Andric         }
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric         case PP_TOKEN:
20210b57cec5SDimitry Andric           // Ignore tokens.
20220b57cec5SDimitry Andric           break;
20230b57cec5SDimitry Andric         }
20240b57cec5SDimitry Andric         break;
20250b57cec5SDimitry Andric       }
20260b57cec5SDimitry Andric       }
20270b57cec5SDimitry Andric     }
20280b57cec5SDimitry Andric     NextCursor:  ;
20290b57cec5SDimitry Andric   }
20300b57cec5SDimitry Andric }
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric namespace {
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   /// Visitor class used to look up identifirs in an AST file.
20350b57cec5SDimitry Andric   class IdentifierLookupVisitor {
20360b57cec5SDimitry Andric     StringRef Name;
20370b57cec5SDimitry Andric     unsigned NameHash;
20380b57cec5SDimitry Andric     unsigned PriorGeneration;
20390b57cec5SDimitry Andric     unsigned &NumIdentifierLookups;
20400b57cec5SDimitry Andric     unsigned &NumIdentifierLookupHits;
20410b57cec5SDimitry Andric     IdentifierInfo *Found = nullptr;
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric   public:
20440b57cec5SDimitry Andric     IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
20450b57cec5SDimitry Andric                             unsigned &NumIdentifierLookups,
20460b57cec5SDimitry Andric                             unsigned &NumIdentifierLookupHits)
20470b57cec5SDimitry Andric       : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
20480b57cec5SDimitry Andric         PriorGeneration(PriorGeneration),
20490b57cec5SDimitry Andric         NumIdentifierLookups(NumIdentifierLookups),
20500b57cec5SDimitry Andric         NumIdentifierLookupHits(NumIdentifierLookupHits) {}
20510b57cec5SDimitry Andric 
20520b57cec5SDimitry Andric     bool operator()(ModuleFile &M) {
20530b57cec5SDimitry Andric       // If we've already searched this module file, skip it now.
20540b57cec5SDimitry Andric       if (M.Generation <= PriorGeneration)
20550b57cec5SDimitry Andric         return true;
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric       ASTIdentifierLookupTable *IdTable
20580b57cec5SDimitry Andric         = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
20590b57cec5SDimitry Andric       if (!IdTable)
20600b57cec5SDimitry Andric         return false;
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric       ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
20630b57cec5SDimitry Andric                                      Found);
20640b57cec5SDimitry Andric       ++NumIdentifierLookups;
20650b57cec5SDimitry Andric       ASTIdentifierLookupTable::iterator Pos =
20660b57cec5SDimitry Andric           IdTable->find_hashed(Name, NameHash, &Trait);
20670b57cec5SDimitry Andric       if (Pos == IdTable->end())
20680b57cec5SDimitry Andric         return false;
20690b57cec5SDimitry Andric 
20700b57cec5SDimitry Andric       // Dereferencing the iterator has the effect of building the
20710b57cec5SDimitry Andric       // IdentifierInfo node and populating it with the various
20720b57cec5SDimitry Andric       // declarations it needs.
20730b57cec5SDimitry Andric       ++NumIdentifierLookupHits;
20740b57cec5SDimitry Andric       Found = *Pos;
20750b57cec5SDimitry Andric       return true;
20760b57cec5SDimitry Andric     }
20770b57cec5SDimitry Andric 
20780b57cec5SDimitry Andric     // Retrieve the identifier info found within the module
20790b57cec5SDimitry Andric     // files.
20800b57cec5SDimitry Andric     IdentifierInfo *getIdentifierInfo() const { return Found; }
20810b57cec5SDimitry Andric   };
20820b57cec5SDimitry Andric 
20830b57cec5SDimitry Andric } // namespace
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
20860b57cec5SDimitry Andric   // Note that we are loading an identifier.
20870b57cec5SDimitry Andric   Deserializing AnIdentifier(this);
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric   unsigned PriorGeneration = 0;
20900b57cec5SDimitry Andric   if (getContext().getLangOpts().Modules)
20910b57cec5SDimitry Andric     PriorGeneration = IdentifierGeneration[&II];
20920b57cec5SDimitry Andric 
20930b57cec5SDimitry Andric   // If there is a global index, look there first to determine which modules
20940b57cec5SDimitry Andric   // provably do not have any results for this identifier.
20950b57cec5SDimitry Andric   GlobalModuleIndex::HitSet Hits;
20960b57cec5SDimitry Andric   GlobalModuleIndex::HitSet *HitsPtr = nullptr;
20970b57cec5SDimitry Andric   if (!loadGlobalIndex()) {
20980b57cec5SDimitry Andric     if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
20990b57cec5SDimitry Andric       HitsPtr = &Hits;
21000b57cec5SDimitry Andric     }
21010b57cec5SDimitry Andric   }
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric   IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
21040b57cec5SDimitry Andric                                   NumIdentifierLookups,
21050b57cec5SDimitry Andric                                   NumIdentifierLookupHits);
21060b57cec5SDimitry Andric   ModuleMgr.visit(Visitor, HitsPtr);
21070b57cec5SDimitry Andric   markIdentifierUpToDate(&II);
21080b57cec5SDimitry Andric }
21090b57cec5SDimitry Andric 
21100b57cec5SDimitry Andric void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
21110b57cec5SDimitry Andric   if (!II)
21120b57cec5SDimitry Andric     return;
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric   II->setOutOfDate(false);
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric   // Update the generation for this identifier.
21170b57cec5SDimitry Andric   if (getContext().getLangOpts().Modules)
21180b57cec5SDimitry Andric     IdentifierGeneration[II] = getGeneration();
21190b57cec5SDimitry Andric }
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric void ASTReader::resolvePendingMacro(IdentifierInfo *II,
21220b57cec5SDimitry Andric                                     const PendingMacroInfo &PMInfo) {
21230b57cec5SDimitry Andric   ModuleFile &M = *PMInfo.M;
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric   BitstreamCursor &Cursor = M.MacroCursor;
21260b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
21275ffd83dbSDimitry Andric   if (llvm::Error Err =
21285ffd83dbSDimitry Andric           Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
21290b57cec5SDimitry Andric     Error(std::move(Err));
21300b57cec5SDimitry Andric     return;
21310b57cec5SDimitry Andric   }
21320b57cec5SDimitry Andric 
21330b57cec5SDimitry Andric   struct ModuleMacroRecord {
21340b57cec5SDimitry Andric     SubmoduleID SubModID;
21350b57cec5SDimitry Andric     MacroInfo *MI;
21360b57cec5SDimitry Andric     SmallVector<SubmoduleID, 8> Overrides;
21370b57cec5SDimitry Andric   };
21380b57cec5SDimitry Andric   llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric   // We expect to see a sequence of PP_MODULE_MACRO records listing exported
21410b57cec5SDimitry Andric   // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
21420b57cec5SDimitry Andric   // macro histroy.
21430b57cec5SDimitry Andric   RecordData Record;
21440b57cec5SDimitry Andric   while (true) {
21450b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
21460b57cec5SDimitry Andric         Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
21470b57cec5SDimitry Andric     if (!MaybeEntry) {
21480b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
21490b57cec5SDimitry Andric       return;
21500b57cec5SDimitry Andric     }
21510b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
21520b57cec5SDimitry Andric 
21530b57cec5SDimitry Andric     if (Entry.Kind != llvm::BitstreamEntry::Record) {
21540b57cec5SDimitry Andric       Error("malformed block record in AST file");
21550b57cec5SDimitry Andric       return;
21560b57cec5SDimitry Andric     }
21570b57cec5SDimitry Andric 
21580b57cec5SDimitry Andric     Record.clear();
21590b57cec5SDimitry Andric     Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
21600b57cec5SDimitry Andric     if (!MaybePP) {
21610b57cec5SDimitry Andric       Error(MaybePP.takeError());
21620b57cec5SDimitry Andric       return;
21630b57cec5SDimitry Andric     }
21640b57cec5SDimitry Andric     switch ((PreprocessorRecordTypes)MaybePP.get()) {
21650b57cec5SDimitry Andric     case PP_MACRO_DIRECTIVE_HISTORY:
21660b57cec5SDimitry Andric       break;
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric     case PP_MODULE_MACRO: {
21690b57cec5SDimitry Andric       ModuleMacros.push_back(ModuleMacroRecord());
21700b57cec5SDimitry Andric       auto &Info = ModuleMacros.back();
21710b57cec5SDimitry Andric       Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
21720b57cec5SDimitry Andric       Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
21730b57cec5SDimitry Andric       for (int I = 2, N = Record.size(); I != N; ++I)
21740b57cec5SDimitry Andric         Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
21750b57cec5SDimitry Andric       continue;
21760b57cec5SDimitry Andric     }
21770b57cec5SDimitry Andric 
21780b57cec5SDimitry Andric     default:
21790b57cec5SDimitry Andric       Error("malformed block record in AST file");
21800b57cec5SDimitry Andric       return;
21810b57cec5SDimitry Andric     }
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric     // We found the macro directive history; that's the last record
21840b57cec5SDimitry Andric     // for this macro.
21850b57cec5SDimitry Andric     break;
21860b57cec5SDimitry Andric   }
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   // Module macros are listed in reverse dependency order.
21890b57cec5SDimitry Andric   {
21900b57cec5SDimitry Andric     std::reverse(ModuleMacros.begin(), ModuleMacros.end());
21910b57cec5SDimitry Andric     llvm::SmallVector<ModuleMacro*, 8> Overrides;
21920b57cec5SDimitry Andric     for (auto &MMR : ModuleMacros) {
21930b57cec5SDimitry Andric       Overrides.clear();
21940b57cec5SDimitry Andric       for (unsigned ModID : MMR.Overrides) {
21950b57cec5SDimitry Andric         Module *Mod = getSubmodule(ModID);
21960b57cec5SDimitry Andric         auto *Macro = PP.getModuleMacro(Mod, II);
21970b57cec5SDimitry Andric         assert(Macro && "missing definition for overridden macro");
21980b57cec5SDimitry Andric         Overrides.push_back(Macro);
21990b57cec5SDimitry Andric       }
22000b57cec5SDimitry Andric 
22010b57cec5SDimitry Andric       bool Inserted = false;
22020b57cec5SDimitry Andric       Module *Owner = getSubmodule(MMR.SubModID);
22030b57cec5SDimitry Andric       PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
22040b57cec5SDimitry Andric     }
22050b57cec5SDimitry Andric   }
22060b57cec5SDimitry Andric 
22070b57cec5SDimitry Andric   // Don't read the directive history for a module; we don't have anywhere
22080b57cec5SDimitry Andric   // to put it.
22090b57cec5SDimitry Andric   if (M.isModule())
22100b57cec5SDimitry Andric     return;
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric   // Deserialize the macro directives history in reverse source-order.
22130b57cec5SDimitry Andric   MacroDirective *Latest = nullptr, *Earliest = nullptr;
22140b57cec5SDimitry Andric   unsigned Idx = 0, N = Record.size();
22150b57cec5SDimitry Andric   while (Idx < N) {
22160b57cec5SDimitry Andric     MacroDirective *MD = nullptr;
22170b57cec5SDimitry Andric     SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
22180b57cec5SDimitry Andric     MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
22190b57cec5SDimitry Andric     switch (K) {
22200b57cec5SDimitry Andric     case MacroDirective::MD_Define: {
22210b57cec5SDimitry Andric       MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
22220b57cec5SDimitry Andric       MD = PP.AllocateDefMacroDirective(MI, Loc);
22230b57cec5SDimitry Andric       break;
22240b57cec5SDimitry Andric     }
22250b57cec5SDimitry Andric     case MacroDirective::MD_Undefine:
22260b57cec5SDimitry Andric       MD = PP.AllocateUndefMacroDirective(Loc);
22270b57cec5SDimitry Andric       break;
22280b57cec5SDimitry Andric     case MacroDirective::MD_Visibility:
22290b57cec5SDimitry Andric       bool isPublic = Record[Idx++];
22300b57cec5SDimitry Andric       MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
22310b57cec5SDimitry Andric       break;
22320b57cec5SDimitry Andric     }
22330b57cec5SDimitry Andric 
22340b57cec5SDimitry Andric     if (!Latest)
22350b57cec5SDimitry Andric       Latest = MD;
22360b57cec5SDimitry Andric     if (Earliest)
22370b57cec5SDimitry Andric       Earliest->setPrevious(MD);
22380b57cec5SDimitry Andric     Earliest = MD;
22390b57cec5SDimitry Andric   }
22400b57cec5SDimitry Andric 
22410b57cec5SDimitry Andric   if (Latest)
22420b57cec5SDimitry Andric     PP.setLoadedMacroDirective(II, Earliest, Latest);
22430b57cec5SDimitry Andric }
22440b57cec5SDimitry Andric 
2245e8d8bef9SDimitry Andric bool ASTReader::shouldDisableValidationForFile(
2246e8d8bef9SDimitry Andric     const serialization::ModuleFile &M) const {
2247e8d8bef9SDimitry Andric   if (DisableValidationKind == DisableValidationForModuleKind::None)
2248e8d8bef9SDimitry Andric     return false;
2249e8d8bef9SDimitry Andric 
2250e8d8bef9SDimitry Andric   // If a PCH is loaded and validation is disabled for PCH then disable
2251e8d8bef9SDimitry Andric   // validation for the PCH and the modules it loads.
225281ad6265SDimitry Andric   ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
2253e8d8bef9SDimitry Andric 
2254e8d8bef9SDimitry Andric   switch (K) {
2255e8d8bef9SDimitry Andric   case MK_MainFile:
2256e8d8bef9SDimitry Andric   case MK_Preamble:
2257e8d8bef9SDimitry Andric   case MK_PCH:
2258e8d8bef9SDimitry Andric     return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
2259e8d8bef9SDimitry Andric   case MK_ImplicitModule:
2260e8d8bef9SDimitry Andric   case MK_ExplicitModule:
2261e8d8bef9SDimitry Andric   case MK_PrebuiltModule:
2262e8d8bef9SDimitry Andric     return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
2263e8d8bef9SDimitry Andric   }
2264e8d8bef9SDimitry Andric 
2265e8d8bef9SDimitry Andric   return false;
2266e8d8bef9SDimitry Andric }
2267e8d8bef9SDimitry Andric 
2268*bdd1243dSDimitry Andric InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
2269*bdd1243dSDimitry Andric   // If this ID is bogus, just return an empty input file.
2270*bdd1243dSDimitry Andric   if (ID == 0 || ID > F.InputFileInfosLoaded.size())
2271*bdd1243dSDimitry Andric     return InputFileInfo();
2272*bdd1243dSDimitry Andric 
2273*bdd1243dSDimitry Andric   // If we've already loaded this input file, return it.
2274*bdd1243dSDimitry Andric   if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
2275*bdd1243dSDimitry Andric     return F.InputFileInfosLoaded[ID - 1];
2276*bdd1243dSDimitry Andric 
22770b57cec5SDimitry Andric   // Go find this input file.
22780b57cec5SDimitry Andric   BitstreamCursor &Cursor = F.InputFilesCursor;
22790b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
22800b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
22810b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22820b57cec5SDimitry Andric     consumeError(std::move(Err));
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
22860b57cec5SDimitry Andric   if (!MaybeCode) {
22870b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22880b57cec5SDimitry Andric     consumeError(MaybeCode.takeError());
22890b57cec5SDimitry Andric   }
22900b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
22910b57cec5SDimitry Andric   RecordData Record;
22920b57cec5SDimitry Andric   StringRef Blob;
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
22950b57cec5SDimitry Andric     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
22960b57cec5SDimitry Andric            "invalid record type for input file");
22970b57cec5SDimitry Andric   else {
22980b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
22990b57cec5SDimitry Andric     consumeError(Maybe.takeError());
23000b57cec5SDimitry Andric   }
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric   assert(Record[0] == ID && "Bogus stored ID or offset");
23030b57cec5SDimitry Andric   InputFileInfo R;
23040b57cec5SDimitry Andric   R.StoredSize = static_cast<off_t>(Record[1]);
23050b57cec5SDimitry Andric   R.StoredTime = static_cast<time_t>(Record[2]);
23060b57cec5SDimitry Andric   R.Overridden = static_cast<bool>(Record[3]);
23070b57cec5SDimitry Andric   R.Transient = static_cast<bool>(Record[4]);
23080b57cec5SDimitry Andric   R.TopLevelModuleMap = static_cast<bool>(Record[5]);
23095ffd83dbSDimitry Andric   R.Filename = std::string(Blob);
23100b57cec5SDimitry Andric   ResolveImportedPath(F, R.Filename);
2311a7dea167SDimitry Andric 
2312a7dea167SDimitry Andric   Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2313a7dea167SDimitry Andric   if (!MaybeEntry) // FIXME this drops errors on the floor.
2314a7dea167SDimitry Andric     consumeError(MaybeEntry.takeError());
2315a7dea167SDimitry Andric   llvm::BitstreamEntry Entry = MaybeEntry.get();
2316a7dea167SDimitry Andric   assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2317a7dea167SDimitry Andric          "expected record type for input file hash");
2318a7dea167SDimitry Andric 
2319a7dea167SDimitry Andric   Record.clear();
2320a7dea167SDimitry Andric   if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2321a7dea167SDimitry Andric     assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2322a7dea167SDimitry Andric            "invalid record type for input file hash");
2323a7dea167SDimitry Andric   else {
2324a7dea167SDimitry Andric     // FIXME this drops errors on the floor.
2325a7dea167SDimitry Andric     consumeError(Maybe.takeError());
2326a7dea167SDimitry Andric   }
2327a7dea167SDimitry Andric   R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2328a7dea167SDimitry Andric                   static_cast<uint64_t>(Record[0]);
2329*bdd1243dSDimitry Andric 
2330*bdd1243dSDimitry Andric   // Note that we've loaded this input file info.
2331*bdd1243dSDimitry Andric   F.InputFileInfosLoaded[ID - 1] = R;
23320b57cec5SDimitry Andric   return R;
23330b57cec5SDimitry Andric }
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric static unsigned moduleKindForDiagnostic(ModuleKind Kind);
23360b57cec5SDimitry Andric InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
23370b57cec5SDimitry Andric   // If this ID is bogus, just return an empty input file.
23380b57cec5SDimitry Andric   if (ID == 0 || ID > F.InputFilesLoaded.size())
23390b57cec5SDimitry Andric     return InputFile();
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   // If we've already loaded this input file, return it.
23420b57cec5SDimitry Andric   if (F.InputFilesLoaded[ID-1].getFile())
23430b57cec5SDimitry Andric     return F.InputFilesLoaded[ID-1];
23440b57cec5SDimitry Andric 
23450b57cec5SDimitry Andric   if (F.InputFilesLoaded[ID-1].isNotFound())
23460b57cec5SDimitry Andric     return InputFile();
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric   // Go find this input file.
23490b57cec5SDimitry Andric   BitstreamCursor &Cursor = F.InputFilesCursor;
23500b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
23510b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
23520b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
23530b57cec5SDimitry Andric     consumeError(std::move(Err));
23540b57cec5SDimitry Andric   }
23550b57cec5SDimitry Andric 
2356*bdd1243dSDimitry Andric   InputFileInfo FI = getInputFileInfo(F, ID);
23570b57cec5SDimitry Andric   off_t StoredSize = FI.StoredSize;
23580b57cec5SDimitry Andric   time_t StoredTime = FI.StoredTime;
23590b57cec5SDimitry Andric   bool Overridden = FI.Overridden;
23600b57cec5SDimitry Andric   bool Transient = FI.Transient;
23610b57cec5SDimitry Andric   StringRef Filename = FI.Filename;
2362a7dea167SDimitry Andric   uint64_t StoredContentHash = FI.ContentHash;
23630b57cec5SDimitry Andric 
2364*bdd1243dSDimitry Andric   OptionalFileEntryRefDegradesToFileEntryPtr File = OptionalFileEntryRef(
2365*bdd1243dSDimitry Andric       expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false)));
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric   // For an overridden file, create a virtual file with the stored
23680b57cec5SDimitry Andric   // size/timestamp.
2369e8d8bef9SDimitry Andric   if ((Overridden || Transient) && !File)
2370e8d8bef9SDimitry Andric     File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
23710b57cec5SDimitry Andric 
2372e8d8bef9SDimitry Andric   if (!File) {
23730b57cec5SDimitry Andric     if (Complain) {
23740b57cec5SDimitry Andric       std::string ErrorStr = "could not find file '";
23750b57cec5SDimitry Andric       ErrorStr += Filename;
23760b57cec5SDimitry Andric       ErrorStr += "' referenced by AST file '";
23770b57cec5SDimitry Andric       ErrorStr += F.FileName;
23780b57cec5SDimitry Andric       ErrorStr += "'";
23790b57cec5SDimitry Andric       Error(ErrorStr);
23800b57cec5SDimitry Andric     }
23810b57cec5SDimitry Andric     // Record that we didn't find the file.
23820b57cec5SDimitry Andric     F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
23830b57cec5SDimitry Andric     return InputFile();
23840b57cec5SDimitry Andric   }
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   // Check if there was a request to override the contents of the file
23870b57cec5SDimitry Andric   // that was part of the precompiled header. Overriding such a file
23880b57cec5SDimitry Andric   // can lead to problems when lexing using the source locations from the
23890b57cec5SDimitry Andric   // PCH.
23900b57cec5SDimitry Andric   SourceManager &SM = getSourceManager();
23910b57cec5SDimitry Andric   // FIXME: Reject if the overrides are different.
23920b57cec5SDimitry Andric   if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
23930b57cec5SDimitry Andric     if (Complain)
23940b57cec5SDimitry Andric       Error(diag::err_fe_pch_file_overridden, Filename);
2395a7dea167SDimitry Andric 
2396a7dea167SDimitry Andric     // After emitting the diagnostic, bypass the overriding file to recover
2397a7dea167SDimitry Andric     // (this creates a separate FileEntry).
2398a7dea167SDimitry Andric     File = SM.bypassFileContentsOverride(*File);
2399a7dea167SDimitry Andric     if (!File) {
2400a7dea167SDimitry Andric       F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2401a7dea167SDimitry Andric       return InputFile();
2402a7dea167SDimitry Andric     }
24030b57cec5SDimitry Andric   }
24040b57cec5SDimitry Andric 
2405349cc55cSDimitry Andric   struct Change {
2406349cc55cSDimitry Andric     enum ModificationKind {
2407a7dea167SDimitry Andric       Size,
2408a7dea167SDimitry Andric       ModTime,
2409a7dea167SDimitry Andric       Content,
2410a7dea167SDimitry Andric       None,
2411349cc55cSDimitry Andric     } Kind;
2412*bdd1243dSDimitry Andric     std::optional<int64_t> Old = std::nullopt;
2413*bdd1243dSDimitry Andric     std::optional<int64_t> New = std::nullopt;
2414a7dea167SDimitry Andric   };
2415a7dea167SDimitry Andric   auto HasInputFileChanged = [&]() {
2416a7dea167SDimitry Andric     if (StoredSize != File->getSize())
2417349cc55cSDimitry Andric       return Change{Change::Size, StoredSize, File->getSize()};
2418e8d8bef9SDimitry Andric     if (!shouldDisableValidationForFile(F) && StoredTime &&
2419a7dea167SDimitry Andric         StoredTime != File->getModificationTime()) {
2420349cc55cSDimitry Andric       Change MTimeChange = {Change::ModTime, StoredTime,
2421349cc55cSDimitry Andric                             File->getModificationTime()};
2422349cc55cSDimitry Andric 
2423a7dea167SDimitry Andric       // In case the modification time changes but not the content,
2424a7dea167SDimitry Andric       // accept the cached file as legit.
2425a7dea167SDimitry Andric       if (ValidateASTInputFilesContent &&
2426a7dea167SDimitry Andric           StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2427a7dea167SDimitry Andric         auto MemBuffOrError = FileMgr.getBufferForFile(File);
2428a7dea167SDimitry Andric         if (!MemBuffOrError) {
2429a7dea167SDimitry Andric           if (!Complain)
2430349cc55cSDimitry Andric             return MTimeChange;
2431a7dea167SDimitry Andric           std::string ErrorStr = "could not get buffer for file '";
2432a7dea167SDimitry Andric           ErrorStr += File->getName();
2433a7dea167SDimitry Andric           ErrorStr += "'";
2434a7dea167SDimitry Andric           Error(ErrorStr);
2435349cc55cSDimitry Andric           return MTimeChange;
2436a7dea167SDimitry Andric         }
24370b57cec5SDimitry Andric 
2438349cc55cSDimitry Andric         // FIXME: hash_value is not guaranteed to be stable!
2439a7dea167SDimitry Andric         auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2440a7dea167SDimitry Andric         if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2441349cc55cSDimitry Andric           return Change{Change::None};
2442349cc55cSDimitry Andric 
2443349cc55cSDimitry Andric         return Change{Change::Content};
2444a7dea167SDimitry Andric       }
2445349cc55cSDimitry Andric       return MTimeChange;
2446a7dea167SDimitry Andric     }
2447349cc55cSDimitry Andric     return Change{Change::None};
2448a7dea167SDimitry Andric   };
2449a7dea167SDimitry Andric 
2450a7dea167SDimitry Andric   bool IsOutOfDate = false;
2451a7dea167SDimitry Andric   auto FileChange = HasInputFileChanged();
24520b57cec5SDimitry Andric   // For an overridden file, there is nothing to validate.
2453349cc55cSDimitry Andric   if (!Overridden && FileChange.Kind != Change::None) {
2454e8d8bef9SDimitry Andric     if (Complain && !Diags.isDiagnosticInFlight()) {
24550b57cec5SDimitry Andric       // Build a list of the PCH imports that got us here (in reverse).
24560b57cec5SDimitry Andric       SmallVector<ModuleFile *, 4> ImportStack(1, &F);
24570b57cec5SDimitry Andric       while (!ImportStack.back()->ImportedBy.empty())
24580b57cec5SDimitry Andric         ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
24590b57cec5SDimitry Andric 
24600b57cec5SDimitry Andric       // The top-level PCH is stale.
24610b57cec5SDimitry Andric       StringRef TopLevelPCHName(ImportStack.back()->FileName);
2462e8d8bef9SDimitry Andric       Diag(diag::err_fe_ast_file_modified)
2463e8d8bef9SDimitry Andric           << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
2464349cc55cSDimitry Andric           << TopLevelPCHName << FileChange.Kind
2465349cc55cSDimitry Andric           << (FileChange.Old && FileChange.New)
246681ad6265SDimitry Andric           << llvm::itostr(FileChange.Old.value_or(0))
246781ad6265SDimitry Andric           << llvm::itostr(FileChange.New.value_or(0));
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric       // Print the import stack.
2470e8d8bef9SDimitry Andric       if (ImportStack.size() > 1) {
24710b57cec5SDimitry Andric         Diag(diag::note_pch_required_by)
24720b57cec5SDimitry Andric           << Filename << ImportStack[0]->FileName;
24730b57cec5SDimitry Andric         for (unsigned I = 1; I < ImportStack.size(); ++I)
24740b57cec5SDimitry Andric           Diag(diag::note_pch_required_by)
24750b57cec5SDimitry Andric             << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
24760b57cec5SDimitry Andric       }
24770b57cec5SDimitry Andric 
24780b57cec5SDimitry Andric       Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
24790b57cec5SDimitry Andric     }
24800b57cec5SDimitry Andric 
24810b57cec5SDimitry Andric     IsOutOfDate = true;
24820b57cec5SDimitry Andric   }
24830b57cec5SDimitry Andric   // FIXME: If the file is overridden and we've already opened it,
24840b57cec5SDimitry Andric   // issue an error (or split it into a separate FileEntry).
24850b57cec5SDimitry Andric 
2486e8d8bef9SDimitry Andric   InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
24870b57cec5SDimitry Andric 
24880b57cec5SDimitry Andric   // Note that we've loaded this input file.
24890b57cec5SDimitry Andric   F.InputFilesLoaded[ID-1] = IF;
24900b57cec5SDimitry Andric   return IF;
24910b57cec5SDimitry Andric }
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric /// If we are loading a relocatable PCH or module file, and the filename
24940b57cec5SDimitry Andric /// is not an absolute path, add the system or module root to the beginning of
24950b57cec5SDimitry Andric /// the file name.
24960b57cec5SDimitry Andric void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
24970b57cec5SDimitry Andric   // Resolve relative to the base directory, if we have one.
24980b57cec5SDimitry Andric   if (!M.BaseDirectory.empty())
24990b57cec5SDimitry Andric     return ResolveImportedPath(Filename, M.BaseDirectory);
25000b57cec5SDimitry Andric }
25010b57cec5SDimitry Andric 
25020b57cec5SDimitry Andric void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
25030b57cec5SDimitry Andric   if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
25040b57cec5SDimitry Andric     return;
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric   SmallString<128> Buffer;
25070b57cec5SDimitry Andric   llvm::sys::path::append(Buffer, Prefix, Filename);
25080b57cec5SDimitry Andric   Filename.assign(Buffer.begin(), Buffer.end());
25090b57cec5SDimitry Andric }
25100b57cec5SDimitry Andric 
25110b57cec5SDimitry Andric static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
25120b57cec5SDimitry Andric   switch (ARR) {
25130b57cec5SDimitry Andric   case ASTReader::Failure: return true;
25140b57cec5SDimitry Andric   case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
25150b57cec5SDimitry Andric   case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
25160b57cec5SDimitry Andric   case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
25170b57cec5SDimitry Andric   case ASTReader::ConfigurationMismatch:
25180b57cec5SDimitry Andric     return !(Caps & ASTReader::ARR_ConfigurationMismatch);
25190b57cec5SDimitry Andric   case ASTReader::HadErrors: return true;
25200b57cec5SDimitry Andric   case ASTReader::Success: return false;
25210b57cec5SDimitry Andric   }
25220b57cec5SDimitry Andric 
25230b57cec5SDimitry Andric   llvm_unreachable("unknown ASTReadResult");
25240b57cec5SDimitry Andric }
25250b57cec5SDimitry Andric 
25260b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
25270b57cec5SDimitry Andric     BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
25280b57cec5SDimitry Andric     bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
25290b57cec5SDimitry Andric     std::string &SuggestedPredefines) {
25300b57cec5SDimitry Andric   if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
25310b57cec5SDimitry Andric     // FIXME this drops errors on the floor.
25320b57cec5SDimitry Andric     consumeError(std::move(Err));
25330b57cec5SDimitry Andric     return Failure;
25340b57cec5SDimitry Andric   }
25350b57cec5SDimitry Andric 
25360b57cec5SDimitry Andric   // Read all of the records in the options block.
25370b57cec5SDimitry Andric   RecordData Record;
25380b57cec5SDimitry Andric   ASTReadResult Result = Success;
25390b57cec5SDimitry Andric   while (true) {
25400b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
25410b57cec5SDimitry Andric     if (!MaybeEntry) {
25420b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
25430b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
25440b57cec5SDimitry Andric       return Failure;
25450b57cec5SDimitry Andric     }
25460b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric     switch (Entry.Kind) {
25490b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
25500b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
25510b57cec5SDimitry Andric       return Failure;
25520b57cec5SDimitry Andric 
25530b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
25540b57cec5SDimitry Andric       return Result;
25550b57cec5SDimitry Andric 
25560b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
25570b57cec5SDimitry Andric       // The interesting case.
25580b57cec5SDimitry Andric       break;
25590b57cec5SDimitry Andric     }
25600b57cec5SDimitry Andric 
25610b57cec5SDimitry Andric     // Read and process a record.
25620b57cec5SDimitry Andric     Record.clear();
25630b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
25640b57cec5SDimitry Andric     if (!MaybeRecordType) {
25650b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
25660b57cec5SDimitry Andric       consumeError(MaybeRecordType.takeError());
25670b57cec5SDimitry Andric       return Failure;
25680b57cec5SDimitry Andric     }
25690b57cec5SDimitry Andric     switch ((OptionsRecordTypes)MaybeRecordType.get()) {
25700b57cec5SDimitry Andric     case LANGUAGE_OPTIONS: {
25710b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25720b57cec5SDimitry Andric       if (ParseLanguageOptions(Record, Complain, Listener,
25730b57cec5SDimitry Andric                                AllowCompatibleConfigurationMismatch))
25740b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25750b57cec5SDimitry Andric       break;
25760b57cec5SDimitry Andric     }
25770b57cec5SDimitry Andric 
25780b57cec5SDimitry Andric     case TARGET_OPTIONS: {
25790b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25800b57cec5SDimitry Andric       if (ParseTargetOptions(Record, Complain, Listener,
25810b57cec5SDimitry Andric                              AllowCompatibleConfigurationMismatch))
25820b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25830b57cec5SDimitry Andric       break;
25840b57cec5SDimitry Andric     }
25850b57cec5SDimitry Andric 
25860b57cec5SDimitry Andric     case FILE_SYSTEM_OPTIONS: {
25870b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25880b57cec5SDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
25890b57cec5SDimitry Andric           ParseFileSystemOptions(Record, Complain, Listener))
25900b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25910b57cec5SDimitry Andric       break;
25920b57cec5SDimitry Andric     }
25930b57cec5SDimitry Andric 
25940b57cec5SDimitry Andric     case HEADER_SEARCH_OPTIONS: {
25950b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
25960b57cec5SDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
25970b57cec5SDimitry Andric           ParseHeaderSearchOptions(Record, Complain, Listener))
25980b57cec5SDimitry Andric         Result = ConfigurationMismatch;
25990b57cec5SDimitry Andric       break;
26000b57cec5SDimitry Andric     }
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric     case PREPROCESSOR_OPTIONS:
26030b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
26040b57cec5SDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
26050b57cec5SDimitry Andric           ParsePreprocessorOptions(Record, Complain, Listener,
26060b57cec5SDimitry Andric                                    SuggestedPredefines))
26070b57cec5SDimitry Andric         Result = ConfigurationMismatch;
26080b57cec5SDimitry Andric       break;
26090b57cec5SDimitry Andric     }
26100b57cec5SDimitry Andric   }
26110b57cec5SDimitry Andric }
26120b57cec5SDimitry Andric 
26130b57cec5SDimitry Andric ASTReader::ASTReadResult
26140b57cec5SDimitry Andric ASTReader::ReadControlBlock(ModuleFile &F,
26150b57cec5SDimitry Andric                             SmallVectorImpl<ImportedModule> &Loaded,
26160b57cec5SDimitry Andric                             const ModuleFile *ImportedBy,
26170b57cec5SDimitry Andric                             unsigned ClientLoadCapabilities) {
26180b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric   if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
26210b57cec5SDimitry Andric     Error(std::move(Err));
26220b57cec5SDimitry Andric     return Failure;
26230b57cec5SDimitry Andric   }
26240b57cec5SDimitry Andric 
26250b57cec5SDimitry Andric   // Lambda to read the unhashed control block the first time it's called.
26260b57cec5SDimitry Andric   //
26270b57cec5SDimitry Andric   // For PCM files, the unhashed control block cannot be read until after the
26280b57cec5SDimitry Andric   // MODULE_NAME record.  However, PCH files have no MODULE_NAME, and yet still
26290b57cec5SDimitry Andric   // need to look ahead before reading the IMPORTS record.  For consistency,
26300b57cec5SDimitry Andric   // this block is always read somehow (see BitstreamEntry::EndBlock).
26310b57cec5SDimitry Andric   bool HasReadUnhashedControlBlock = false;
26320b57cec5SDimitry Andric   auto readUnhashedControlBlockOnce = [&]() {
26330b57cec5SDimitry Andric     if (!HasReadUnhashedControlBlock) {
26340b57cec5SDimitry Andric       HasReadUnhashedControlBlock = true;
26350b57cec5SDimitry Andric       if (ASTReadResult Result =
26360b57cec5SDimitry Andric               readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
26370b57cec5SDimitry Andric         return Result;
26380b57cec5SDimitry Andric     }
26390b57cec5SDimitry Andric     return Success;
26400b57cec5SDimitry Andric   };
26410b57cec5SDimitry Andric 
2642e8d8bef9SDimitry Andric   bool DisableValidation = shouldDisableValidationForFile(F);
2643e8d8bef9SDimitry Andric 
26440b57cec5SDimitry Andric   // Read all of the records and blocks in the control block.
26450b57cec5SDimitry Andric   RecordData Record;
26460b57cec5SDimitry Andric   unsigned NumInputs = 0;
26470b57cec5SDimitry Andric   unsigned NumUserInputs = 0;
26480b57cec5SDimitry Andric   StringRef BaseDirectoryAsWritten;
26490b57cec5SDimitry Andric   while (true) {
26500b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
26510b57cec5SDimitry Andric     if (!MaybeEntry) {
26520b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
26530b57cec5SDimitry Andric       return Failure;
26540b57cec5SDimitry Andric     }
26550b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
26560b57cec5SDimitry Andric 
26570b57cec5SDimitry Andric     switch (Entry.Kind) {
26580b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
26590b57cec5SDimitry Andric       Error("malformed block record in AST file");
26600b57cec5SDimitry Andric       return Failure;
26610b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock: {
26620b57cec5SDimitry Andric       // Validate the module before returning.  This call catches an AST with
26630b57cec5SDimitry Andric       // no module name and no imports.
26640b57cec5SDimitry Andric       if (ASTReadResult Result = readUnhashedControlBlockOnce())
26650b57cec5SDimitry Andric         return Result;
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric       // Validate input files.
26680b57cec5SDimitry Andric       const HeaderSearchOptions &HSOpts =
26690b57cec5SDimitry Andric           PP.getHeaderSearchInfo().getHeaderSearchOpts();
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric       // All user input files reside at the index range [0, NumUserInputs), and
26720b57cec5SDimitry Andric       // system input files reside at [NumUserInputs, NumInputs). For explicitly
26730b57cec5SDimitry Andric       // loaded module files, ignore missing inputs.
26740b57cec5SDimitry Andric       if (!DisableValidation && F.Kind != MK_ExplicitModule &&
26750b57cec5SDimitry Andric           F.Kind != MK_PrebuiltModule) {
26760b57cec5SDimitry Andric         bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric         // If we are reading a module, we will create a verification timestamp,
26790b57cec5SDimitry Andric         // so we verify all input files.  Otherwise, verify only user input
26800b57cec5SDimitry Andric         // files.
26810b57cec5SDimitry Andric 
2682*bdd1243dSDimitry Andric         unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
2683*bdd1243dSDimitry Andric         if (HSOpts.ModulesValidateOncePerBuildSession &&
2684*bdd1243dSDimitry Andric             F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&
2685*bdd1243dSDimitry Andric             F.Kind == MK_ImplicitModule)
2686*bdd1243dSDimitry Andric           N = NumUserInputs;
26870b57cec5SDimitry Andric 
26880b57cec5SDimitry Andric         for (unsigned I = 0; I < N; ++I) {
26890b57cec5SDimitry Andric           InputFile IF = getInputFile(F, I+1, Complain);
26900b57cec5SDimitry Andric           if (!IF.getFile() || IF.isOutOfDate())
26910b57cec5SDimitry Andric             return OutOfDate;
26920b57cec5SDimitry Andric         }
26930b57cec5SDimitry Andric       }
26940b57cec5SDimitry Andric 
26950b57cec5SDimitry Andric       if (Listener)
26960b57cec5SDimitry Andric         Listener->visitModuleFile(F.FileName, F.Kind);
26970b57cec5SDimitry Andric 
26980b57cec5SDimitry Andric       if (Listener && Listener->needsInputFileVisitation()) {
26990b57cec5SDimitry Andric         unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
27000b57cec5SDimitry Andric                                                                 : NumUserInputs;
27010b57cec5SDimitry Andric         for (unsigned I = 0; I < N; ++I) {
27020b57cec5SDimitry Andric           bool IsSystem = I >= NumUserInputs;
2703*bdd1243dSDimitry Andric           InputFileInfo FI = getInputFileInfo(F, I + 1);
27040b57cec5SDimitry Andric           Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
27050b57cec5SDimitry Andric                                    F.Kind == MK_ExplicitModule ||
27060b57cec5SDimitry Andric                                    F.Kind == MK_PrebuiltModule);
27070b57cec5SDimitry Andric         }
27080b57cec5SDimitry Andric       }
27090b57cec5SDimitry Andric 
2710480093f4SDimitry Andric       return Success;
27110b57cec5SDimitry Andric     }
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
27140b57cec5SDimitry Andric       switch (Entry.ID) {
27150b57cec5SDimitry Andric       case INPUT_FILES_BLOCK_ID:
27160b57cec5SDimitry Andric         F.InputFilesCursor = Stream;
27170b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
27180b57cec5SDimitry Andric           Error(std::move(Err));
27190b57cec5SDimitry Andric           return Failure;
27200b57cec5SDimitry Andric         }
27210b57cec5SDimitry Andric         if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
27220b57cec5SDimitry Andric           Error("malformed block record in AST file");
27230b57cec5SDimitry Andric           return Failure;
27240b57cec5SDimitry Andric         }
27250b57cec5SDimitry Andric         continue;
27260b57cec5SDimitry Andric 
27270b57cec5SDimitry Andric       case OPTIONS_BLOCK_ID:
27280b57cec5SDimitry Andric         // If we're reading the first module for this group, check its options
27290b57cec5SDimitry Andric         // are compatible with ours. For modules it imports, no further checking
27300b57cec5SDimitry Andric         // is required, because we checked them when we built it.
27310b57cec5SDimitry Andric         if (Listener && !ImportedBy) {
27320b57cec5SDimitry Andric           // Should we allow the configuration of the module file to differ from
27330b57cec5SDimitry Andric           // the configuration of the current translation unit in a compatible
27340b57cec5SDimitry Andric           // way?
27350b57cec5SDimitry Andric           //
27360b57cec5SDimitry Andric           // FIXME: Allow this for files explicitly specified with -include-pch.
27370b57cec5SDimitry Andric           bool AllowCompatibleConfigurationMismatch =
27380b57cec5SDimitry Andric               F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
27390b57cec5SDimitry Andric 
2740480093f4SDimitry Andric           ASTReadResult Result =
2741480093f4SDimitry Andric               ReadOptionsBlock(Stream, ClientLoadCapabilities,
2742480093f4SDimitry Andric                                AllowCompatibleConfigurationMismatch, *Listener,
2743480093f4SDimitry Andric                                SuggestedPredefines);
27440b57cec5SDimitry Andric           if (Result == Failure) {
27450b57cec5SDimitry Andric             Error("malformed block record in AST file");
27460b57cec5SDimitry Andric             return Result;
27470b57cec5SDimitry Andric           }
27480b57cec5SDimitry Andric 
27490b57cec5SDimitry Andric           if (DisableValidation ||
27500b57cec5SDimitry Andric               (AllowConfigurationMismatch && Result == ConfigurationMismatch))
27510b57cec5SDimitry Andric             Result = Success;
27520b57cec5SDimitry Andric 
27530b57cec5SDimitry Andric           // If we can't load the module, exit early since we likely
27540b57cec5SDimitry Andric           // will rebuild the module anyway. The stream may be in the
27550b57cec5SDimitry Andric           // middle of a block.
27560b57cec5SDimitry Andric           if (Result != Success)
27570b57cec5SDimitry Andric             return Result;
27580b57cec5SDimitry Andric         } else if (llvm::Error Err = Stream.SkipBlock()) {
27590b57cec5SDimitry Andric           Error(std::move(Err));
27600b57cec5SDimitry Andric           return Failure;
27610b57cec5SDimitry Andric         }
27620b57cec5SDimitry Andric         continue;
27630b57cec5SDimitry Andric 
27640b57cec5SDimitry Andric       default:
27650b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
27660b57cec5SDimitry Andric           Error(std::move(Err));
27670b57cec5SDimitry Andric           return Failure;
27680b57cec5SDimitry Andric         }
27690b57cec5SDimitry Andric         continue;
27700b57cec5SDimitry Andric       }
27710b57cec5SDimitry Andric 
27720b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
27730b57cec5SDimitry Andric       // The interesting case.
27740b57cec5SDimitry Andric       break;
27750b57cec5SDimitry Andric     }
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric     // Read and process a record.
27780b57cec5SDimitry Andric     Record.clear();
27790b57cec5SDimitry Andric     StringRef Blob;
27800b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType =
27810b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
27820b57cec5SDimitry Andric     if (!MaybeRecordType) {
27830b57cec5SDimitry Andric       Error(MaybeRecordType.takeError());
27840b57cec5SDimitry Andric       return Failure;
27850b57cec5SDimitry Andric     }
27860b57cec5SDimitry Andric     switch ((ControlRecordTypes)MaybeRecordType.get()) {
27870b57cec5SDimitry Andric     case METADATA: {
27880b57cec5SDimitry Andric       if (Record[0] != VERSION_MAJOR && !DisableValidation) {
27890b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
27900b57cec5SDimitry Andric           Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
27910b57cec5SDimitry Andric                                         : diag::err_pch_version_too_new);
27920b57cec5SDimitry Andric         return VersionMismatch;
27930b57cec5SDimitry Andric       }
27940b57cec5SDimitry Andric 
2795e8d8bef9SDimitry Andric       bool hasErrors = Record[6];
2796fe6060f1SDimitry Andric       if (hasErrors && !DisableValidation) {
2797fe6060f1SDimitry Andric         // If requested by the caller and the module hasn't already been read
2798fe6060f1SDimitry Andric         // or compiled, mark modules on error as out-of-date.
2799fe6060f1SDimitry Andric         if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
2800fe6060f1SDimitry Andric             canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
2801fe6060f1SDimitry Andric           return OutOfDate;
2802fe6060f1SDimitry Andric 
2803fe6060f1SDimitry Andric         if (!AllowASTWithCompilerErrors) {
28040b57cec5SDimitry Andric           Diag(diag::err_pch_with_compiler_errors);
28050b57cec5SDimitry Andric           return HadErrors;
28060b57cec5SDimitry Andric         }
2807fe6060f1SDimitry Andric       }
28080b57cec5SDimitry Andric       if (hasErrors) {
28090b57cec5SDimitry Andric         Diags.ErrorOccurred = true;
28100b57cec5SDimitry Andric         Diags.UncompilableErrorOccurred = true;
28110b57cec5SDimitry Andric         Diags.UnrecoverableErrorOccurred = true;
28120b57cec5SDimitry Andric       }
28130b57cec5SDimitry Andric 
28140b57cec5SDimitry Andric       F.RelocatablePCH = Record[4];
28150b57cec5SDimitry Andric       // Relative paths in a relocatable PCH are relative to our sysroot.
28160b57cec5SDimitry Andric       if (F.RelocatablePCH)
28170b57cec5SDimitry Andric         F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
28180b57cec5SDimitry Andric 
28190b57cec5SDimitry Andric       F.HasTimestamps = Record[5];
28200b57cec5SDimitry Andric 
28210b57cec5SDimitry Andric       const std::string &CurBranch = getClangFullRepositoryVersion();
28220b57cec5SDimitry Andric       StringRef ASTBranch = Blob;
28230b57cec5SDimitry Andric       if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
28240b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
28250b57cec5SDimitry Andric           Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
28260b57cec5SDimitry Andric         return VersionMismatch;
28270b57cec5SDimitry Andric       }
28280b57cec5SDimitry Andric       break;
28290b57cec5SDimitry Andric     }
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric     case IMPORTS: {
28320b57cec5SDimitry Andric       // Validate the AST before processing any imports (otherwise, untangling
28330b57cec5SDimitry Andric       // them can be error-prone and expensive).  A module will have a name and
28340b57cec5SDimitry Andric       // will already have been validated, but this catches the PCH case.
28350b57cec5SDimitry Andric       if (ASTReadResult Result = readUnhashedControlBlockOnce())
28360b57cec5SDimitry Andric         return Result;
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric       // Load each of the imported PCH files.
28390b57cec5SDimitry Andric       unsigned Idx = 0, N = Record.size();
28400b57cec5SDimitry Andric       while (Idx < N) {
28410b57cec5SDimitry Andric         // Read information about the AST file.
28420b57cec5SDimitry Andric         ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
28430b57cec5SDimitry Andric         // The import location will be the local one for now; we will adjust
28440b57cec5SDimitry Andric         // all import locations of module imports after the global source
28450b57cec5SDimitry Andric         // location info are setup, in ReadAST.
28460b57cec5SDimitry Andric         SourceLocation ImportLoc =
28470b57cec5SDimitry Andric             ReadUntranslatedSourceLocation(Record[Idx++]);
28480b57cec5SDimitry Andric         off_t StoredSize = (off_t)Record[Idx++];
28490b57cec5SDimitry Andric         time_t StoredModTime = (time_t)Record[Idx++];
28505ffd83dbSDimitry Andric         auto FirstSignatureByte = Record.begin() + Idx;
28515ffd83dbSDimitry Andric         ASTFileSignature StoredSignature = ASTFileSignature::create(
28525ffd83dbSDimitry Andric             FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
28535ffd83dbSDimitry Andric         Idx += ASTFileSignature::size;
28540b57cec5SDimitry Andric 
28550b57cec5SDimitry Andric         std::string ImportedName = ReadString(Record, Idx);
28560b57cec5SDimitry Andric         std::string ImportedFile;
28570b57cec5SDimitry Andric 
28580b57cec5SDimitry Andric         // For prebuilt and explicit modules first consult the file map for
28590b57cec5SDimitry Andric         // an override. Note that here we don't search prebuilt module
28600b57cec5SDimitry Andric         // directories, only the explicit name to file mappings. Also, we will
28610b57cec5SDimitry Andric         // still verify the size/signature making sure it is essentially the
28620b57cec5SDimitry Andric         // same file but perhaps in a different location.
28630b57cec5SDimitry Andric         if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
28640b57cec5SDimitry Andric           ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
28650b57cec5SDimitry Andric             ImportedName, /*FileMapOnly*/ true);
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric         if (ImportedFile.empty())
28680b57cec5SDimitry Andric           // Use BaseDirectoryAsWritten to ensure we use the same path in the
28690b57cec5SDimitry Andric           // ModuleCache as when writing.
28700b57cec5SDimitry Andric           ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
28710b57cec5SDimitry Andric         else
28720b57cec5SDimitry Andric           SkipPath(Record, Idx);
28730b57cec5SDimitry Andric 
28740b57cec5SDimitry Andric         // If our client can't cope with us being out of date, we can't cope with
28750b57cec5SDimitry Andric         // our dependency being missing.
28760b57cec5SDimitry Andric         unsigned Capabilities = ClientLoadCapabilities;
28770b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
28780b57cec5SDimitry Andric           Capabilities &= ~ARR_Missing;
28790b57cec5SDimitry Andric 
28800b57cec5SDimitry Andric         // Load the AST file.
28810b57cec5SDimitry Andric         auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
28820b57cec5SDimitry Andric                                   Loaded, StoredSize, StoredModTime,
28830b57cec5SDimitry Andric                                   StoredSignature, Capabilities);
28840b57cec5SDimitry Andric 
28850b57cec5SDimitry Andric         // If we diagnosed a problem, produce a backtrace.
2886fe6060f1SDimitry Andric         bool recompilingFinalized =
2887fe6060f1SDimitry Andric             Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
2888fe6060f1SDimitry Andric             getModuleManager().getModuleCache().isPCMFinal(F.FileName);
2889fe6060f1SDimitry Andric         if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
28900b57cec5SDimitry Andric           Diag(diag::note_module_file_imported_by)
28910b57cec5SDimitry Andric               << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2892fe6060f1SDimitry Andric         if (recompilingFinalized)
2893fe6060f1SDimitry Andric           Diag(diag::note_module_file_conflict);
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric         switch (Result) {
28960b57cec5SDimitry Andric         case Failure: return Failure;
28970b57cec5SDimitry Andric           // If we have to ignore the dependency, we'll have to ignore this too.
28980b57cec5SDimitry Andric         case Missing:
28990b57cec5SDimitry Andric         case OutOfDate: return OutOfDate;
29000b57cec5SDimitry Andric         case VersionMismatch: return VersionMismatch;
29010b57cec5SDimitry Andric         case ConfigurationMismatch: return ConfigurationMismatch;
29020b57cec5SDimitry Andric         case HadErrors: return HadErrors;
29030b57cec5SDimitry Andric         case Success: break;
29040b57cec5SDimitry Andric         }
29050b57cec5SDimitry Andric       }
29060b57cec5SDimitry Andric       break;
29070b57cec5SDimitry Andric     }
29080b57cec5SDimitry Andric 
29090b57cec5SDimitry Andric     case ORIGINAL_FILE:
29100b57cec5SDimitry Andric       F.OriginalSourceFileID = FileID::get(Record[0]);
29115ffd83dbSDimitry Andric       F.ActualOriginalSourceFileName = std::string(Blob);
29120b57cec5SDimitry Andric       F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
29130b57cec5SDimitry Andric       ResolveImportedPath(F, F.OriginalSourceFileName);
29140b57cec5SDimitry Andric       break;
29150b57cec5SDimitry Andric 
29160b57cec5SDimitry Andric     case ORIGINAL_FILE_ID:
29170b57cec5SDimitry Andric       F.OriginalSourceFileID = FileID::get(Record[0]);
29180b57cec5SDimitry Andric       break;
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric     case MODULE_NAME:
29215ffd83dbSDimitry Andric       F.ModuleName = std::string(Blob);
29220b57cec5SDimitry Andric       Diag(diag::remark_module_import)
29230b57cec5SDimitry Andric           << F.ModuleName << F.FileName << (ImportedBy ? true : false)
29240b57cec5SDimitry Andric           << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
29250b57cec5SDimitry Andric       if (Listener)
29260b57cec5SDimitry Andric         Listener->ReadModuleName(F.ModuleName);
29270b57cec5SDimitry Andric 
29280b57cec5SDimitry Andric       // Validate the AST as soon as we have a name so we can exit early on
29290b57cec5SDimitry Andric       // failure.
29300b57cec5SDimitry Andric       if (ASTReadResult Result = readUnhashedControlBlockOnce())
29310b57cec5SDimitry Andric         return Result;
29320b57cec5SDimitry Andric 
29330b57cec5SDimitry Andric       break;
29340b57cec5SDimitry Andric 
29350b57cec5SDimitry Andric     case MODULE_DIRECTORY: {
29360b57cec5SDimitry Andric       // Save the BaseDirectory as written in the PCM for computing the module
29370b57cec5SDimitry Andric       // filename for the ModuleCache.
29380b57cec5SDimitry Andric       BaseDirectoryAsWritten = Blob;
29390b57cec5SDimitry Andric       assert(!F.ModuleName.empty() &&
29400b57cec5SDimitry Andric              "MODULE_DIRECTORY found before MODULE_NAME");
29410b57cec5SDimitry Andric       // If we've already loaded a module map file covering this module, we may
29420b57cec5SDimitry Andric       // have a better path for it (relative to the current build).
29430b57cec5SDimitry Andric       Module *M = PP.getHeaderSearchInfo().lookupModule(
2944349cc55cSDimitry Andric           F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
29450b57cec5SDimitry Andric           /*AllowExtraModuleMapSearch*/ true);
29460b57cec5SDimitry Andric       if (M && M->Directory) {
29470b57cec5SDimitry Andric         // If we're implicitly loading a module, the base directory can't
29480b57cec5SDimitry Andric         // change between the build and use.
29490b57cec5SDimitry Andric         // Don't emit module relocation error if we have -fno-validate-pch
2950e8d8bef9SDimitry Andric         if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
2951e8d8bef9SDimitry Andric                   DisableValidationForModuleKind::Module) &&
29520b57cec5SDimitry Andric             F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
2953a7dea167SDimitry Andric           auto BuildDir = PP.getFileManager().getDirectory(Blob);
2954a7dea167SDimitry Andric           if (!BuildDir || *BuildDir != M->Directory) {
2955fe6060f1SDimitry Andric             if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
29560b57cec5SDimitry Andric               Diag(diag::err_imported_module_relocated)
29570b57cec5SDimitry Andric                   << F.ModuleName << Blob << M->Directory->getName();
29580b57cec5SDimitry Andric             return OutOfDate;
29590b57cec5SDimitry Andric           }
29600b57cec5SDimitry Andric         }
29615ffd83dbSDimitry Andric         F.BaseDirectory = std::string(M->Directory->getName());
29620b57cec5SDimitry Andric       } else {
29635ffd83dbSDimitry Andric         F.BaseDirectory = std::string(Blob);
29640b57cec5SDimitry Andric       }
29650b57cec5SDimitry Andric       break;
29660b57cec5SDimitry Andric     }
29670b57cec5SDimitry Andric 
29680b57cec5SDimitry Andric     case MODULE_MAP_FILE:
29690b57cec5SDimitry Andric       if (ASTReadResult Result =
29700b57cec5SDimitry Andric               ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
29710b57cec5SDimitry Andric         return Result;
29720b57cec5SDimitry Andric       break;
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric     case INPUT_FILE_OFFSETS:
29750b57cec5SDimitry Andric       NumInputs = Record[0];
29760b57cec5SDimitry Andric       NumUserInputs = Record[1];
29770b57cec5SDimitry Andric       F.InputFileOffsets =
29780b57cec5SDimitry Andric           (const llvm::support::unaligned_uint64_t *)Blob.data();
29790b57cec5SDimitry Andric       F.InputFilesLoaded.resize(NumInputs);
2980*bdd1243dSDimitry Andric       F.InputFileInfosLoaded.resize(NumInputs);
29810b57cec5SDimitry Andric       F.NumUserInputFiles = NumUserInputs;
29820b57cec5SDimitry Andric       break;
29830b57cec5SDimitry Andric     }
29840b57cec5SDimitry Andric   }
29850b57cec5SDimitry Andric }
29860b57cec5SDimitry Andric 
298704eeddc0SDimitry Andric void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
298804eeddc0SDimitry Andric                                   Preprocessor &PP) {
298904eeddc0SDimitry Andric   using namespace llvm::support;
299004eeddc0SDimitry Andric 
299104eeddc0SDimitry Andric   const unsigned char *D = (const unsigned char *)Blob.data();
299204eeddc0SDimitry Andric   unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
299304eeddc0SDimitry Andric 
299404eeddc0SDimitry Andric   for (unsigned I = 0; I < FileCount; ++I) {
299504eeddc0SDimitry Andric     size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
2996*bdd1243dSDimitry Andric     InputFileInfo IFI = getInputFileInfo(F, ID);
299704eeddc0SDimitry Andric     if (llvm::ErrorOr<const FileEntry *> File =
299804eeddc0SDimitry Andric             PP.getFileManager().getFile(IFI.Filename))
299904eeddc0SDimitry Andric       PP.getIncludedFiles().insert(*File);
300004eeddc0SDimitry Andric   }
300104eeddc0SDimitry Andric }
300204eeddc0SDimitry Andric 
3003349cc55cSDimitry Andric llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
3004349cc55cSDimitry Andric                                     unsigned ClientLoadCapabilities) {
30050b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
30060b57cec5SDimitry Andric 
3007349cc55cSDimitry Andric   if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
3008349cc55cSDimitry Andric     return Err;
30095ffd83dbSDimitry Andric   F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric   // Read all of the records and blocks for the AST file.
30120b57cec5SDimitry Andric   RecordData Record;
30130b57cec5SDimitry Andric   while (true) {
30140b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3015349cc55cSDimitry Andric     if (!MaybeEntry)
3016349cc55cSDimitry Andric       return MaybeEntry.takeError();
30170b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric     switch (Entry.Kind) {
30200b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
3021349cc55cSDimitry Andric       return llvm::createStringError(
3022349cc55cSDimitry Andric           std::errc::illegal_byte_sequence,
3023349cc55cSDimitry Andric           "error at end of module block in AST file");
30240b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
30250b57cec5SDimitry Andric       // Outside of C++, we do not store a lookup map for the translation unit.
30260b57cec5SDimitry Andric       // Instead, mark it as needing a lookup map to be built if this module
30270b57cec5SDimitry Andric       // contains any declarations lexically within it (which it always does!).
30280b57cec5SDimitry Andric       // This usually has no cost, since we very rarely need the lookup map for
30290b57cec5SDimitry Andric       // the translation unit outside C++.
30300b57cec5SDimitry Andric       if (ASTContext *Ctx = ContextObj) {
30310b57cec5SDimitry Andric         DeclContext *DC = Ctx->getTranslationUnitDecl();
30320b57cec5SDimitry Andric         if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
30330b57cec5SDimitry Andric           DC->setMustBuildLookupTable();
30340b57cec5SDimitry Andric       }
30350b57cec5SDimitry Andric 
3036349cc55cSDimitry Andric       return llvm::Error::success();
30370b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
30380b57cec5SDimitry Andric       switch (Entry.ID) {
30390b57cec5SDimitry Andric       case DECLTYPES_BLOCK_ID:
30400b57cec5SDimitry Andric         // We lazily load the decls block, but we want to set up the
30410b57cec5SDimitry Andric         // DeclsCursor cursor to point into it.  Clone our current bitcode
30420b57cec5SDimitry Andric         // cursor to it, enter the block and read the abbrevs in that block.
30430b57cec5SDimitry Andric         // With the main cursor, we just skip over it.
30440b57cec5SDimitry Andric         F.DeclsCursor = Stream;
3045349cc55cSDimitry Andric         if (llvm::Error Err = Stream.SkipBlock())
3046349cc55cSDimitry Andric           return Err;
3047349cc55cSDimitry Andric         if (llvm::Error Err = ReadBlockAbbrevs(
3048349cc55cSDimitry Andric                 F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
3049349cc55cSDimitry Andric           return Err;
30500b57cec5SDimitry Andric         break;
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric       case PREPROCESSOR_BLOCK_ID:
30530b57cec5SDimitry Andric         F.MacroCursor = Stream;
30540b57cec5SDimitry Andric         if (!PP.getExternalSource())
30550b57cec5SDimitry Andric           PP.setExternalSource(this);
30560b57cec5SDimitry Andric 
3057349cc55cSDimitry Andric         if (llvm::Error Err = Stream.SkipBlock())
3058349cc55cSDimitry Andric           return Err;
3059349cc55cSDimitry Andric         if (llvm::Error Err =
3060349cc55cSDimitry Andric                 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
3061349cc55cSDimitry Andric           return Err;
30620b57cec5SDimitry Andric         F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
30630b57cec5SDimitry Andric         break;
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric       case PREPROCESSOR_DETAIL_BLOCK_ID:
30660b57cec5SDimitry Andric         F.PreprocessorDetailCursor = Stream;
30670b57cec5SDimitry Andric 
30680b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
3069349cc55cSDimitry Andric           return Err;
30700b57cec5SDimitry Andric         }
3071349cc55cSDimitry Andric         if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
3072349cc55cSDimitry Andric                                                PREPROCESSOR_DETAIL_BLOCK_ID))
3073349cc55cSDimitry Andric           return Err;
30740b57cec5SDimitry Andric         F.PreprocessorDetailStartOffset
30750b57cec5SDimitry Andric         = F.PreprocessorDetailCursor.GetCurrentBitNo();
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric         if (!PP.getPreprocessingRecord())
30780b57cec5SDimitry Andric           PP.createPreprocessingRecord();
30790b57cec5SDimitry Andric         if (!PP.getPreprocessingRecord()->getExternalSource())
30800b57cec5SDimitry Andric           PP.getPreprocessingRecord()->SetExternalSource(*this);
30810b57cec5SDimitry Andric         break;
30820b57cec5SDimitry Andric 
30830b57cec5SDimitry Andric       case SOURCE_MANAGER_BLOCK_ID:
3084349cc55cSDimitry Andric         if (llvm::Error Err = ReadSourceManagerBlock(F))
3085349cc55cSDimitry Andric           return Err;
30860b57cec5SDimitry Andric         break;
30870b57cec5SDimitry Andric 
30880b57cec5SDimitry Andric       case SUBMODULE_BLOCK_ID:
3089349cc55cSDimitry Andric         if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
3090349cc55cSDimitry Andric           return Err;
30910b57cec5SDimitry Andric         break;
30920b57cec5SDimitry Andric 
30930b57cec5SDimitry Andric       case COMMENTS_BLOCK_ID: {
30940b57cec5SDimitry Andric         BitstreamCursor C = Stream;
30950b57cec5SDimitry Andric 
3096349cc55cSDimitry Andric         if (llvm::Error Err = Stream.SkipBlock())
3097349cc55cSDimitry Andric           return Err;
3098349cc55cSDimitry Andric         if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
3099349cc55cSDimitry Andric           return Err;
31000b57cec5SDimitry Andric         CommentsCursors.push_back(std::make_pair(C, &F));
31010b57cec5SDimitry Andric         break;
31020b57cec5SDimitry Andric       }
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric       default:
3105349cc55cSDimitry Andric         if (llvm::Error Err = Stream.SkipBlock())
3106349cc55cSDimitry Andric           return Err;
31070b57cec5SDimitry Andric         break;
31080b57cec5SDimitry Andric       }
31090b57cec5SDimitry Andric       continue;
31100b57cec5SDimitry Andric 
31110b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
31120b57cec5SDimitry Andric       // The interesting case.
31130b57cec5SDimitry Andric       break;
31140b57cec5SDimitry Andric     }
31150b57cec5SDimitry Andric 
31160b57cec5SDimitry Andric     // Read and process a record.
31170b57cec5SDimitry Andric     Record.clear();
31180b57cec5SDimitry Andric     StringRef Blob;
31190b57cec5SDimitry Andric     Expected<unsigned> MaybeRecordType =
31200b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
3121349cc55cSDimitry Andric     if (!MaybeRecordType)
3122349cc55cSDimitry Andric       return MaybeRecordType.takeError();
31230b57cec5SDimitry Andric     ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric     // If we're not loading an AST context, we don't care about most records.
31260b57cec5SDimitry Andric     if (!ContextObj) {
31270b57cec5SDimitry Andric       switch (RecordType) {
31280b57cec5SDimitry Andric       case IDENTIFIER_TABLE:
31290b57cec5SDimitry Andric       case IDENTIFIER_OFFSET:
31300b57cec5SDimitry Andric       case INTERESTING_IDENTIFIERS:
31310b57cec5SDimitry Andric       case STATISTICS:
313281ad6265SDimitry Andric       case PP_ASSUME_NONNULL_LOC:
31330b57cec5SDimitry Andric       case PP_CONDITIONAL_STACK:
31340b57cec5SDimitry Andric       case PP_COUNTER_VALUE:
31350b57cec5SDimitry Andric       case SOURCE_LOCATION_OFFSETS:
31360b57cec5SDimitry Andric       case MODULE_OFFSET_MAP:
31370b57cec5SDimitry Andric       case SOURCE_MANAGER_LINE_TABLE:
31380b57cec5SDimitry Andric       case SOURCE_LOCATION_PRELOADS:
31390b57cec5SDimitry Andric       case PPD_ENTITIES_OFFSETS:
31400b57cec5SDimitry Andric       case HEADER_SEARCH_TABLE:
31410b57cec5SDimitry Andric       case IMPORTED_MODULES:
31420b57cec5SDimitry Andric       case MACRO_OFFSET:
31430b57cec5SDimitry Andric         break;
31440b57cec5SDimitry Andric       default:
31450b57cec5SDimitry Andric         continue;
31460b57cec5SDimitry Andric       }
31470b57cec5SDimitry Andric     }
31480b57cec5SDimitry Andric 
31490b57cec5SDimitry Andric     switch (RecordType) {
31500b57cec5SDimitry Andric     default:  // Default behavior: ignore.
31510b57cec5SDimitry Andric       break;
31520b57cec5SDimitry Andric 
31530b57cec5SDimitry Andric     case TYPE_OFFSET: {
3154349cc55cSDimitry Andric       if (F.LocalNumTypes != 0)
3155349cc55cSDimitry Andric         return llvm::createStringError(
3156349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3157349cc55cSDimitry Andric             "duplicate TYPE_OFFSET record in AST file");
31585ffd83dbSDimitry Andric       F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
31590b57cec5SDimitry Andric       F.LocalNumTypes = Record[0];
31600b57cec5SDimitry Andric       unsigned LocalBaseTypeIndex = Record[1];
31610b57cec5SDimitry Andric       F.BaseTypeIndex = getTotalNumTypes();
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric       if (F.LocalNumTypes > 0) {
31640b57cec5SDimitry Andric         // Introduce the global -> local mapping for types within this module.
31650b57cec5SDimitry Andric         GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
31660b57cec5SDimitry Andric 
31670b57cec5SDimitry Andric         // Introduce the local -> global mapping for types within this module.
31680b57cec5SDimitry Andric         F.TypeRemap.insertOrReplace(
31690b57cec5SDimitry Andric           std::make_pair(LocalBaseTypeIndex,
31700b57cec5SDimitry Andric                          F.BaseTypeIndex - LocalBaseTypeIndex));
31710b57cec5SDimitry Andric 
31720b57cec5SDimitry Andric         TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
31730b57cec5SDimitry Andric       }
31740b57cec5SDimitry Andric       break;
31750b57cec5SDimitry Andric     }
31760b57cec5SDimitry Andric 
31770b57cec5SDimitry Andric     case DECL_OFFSET: {
3178349cc55cSDimitry Andric       if (F.LocalNumDecls != 0)
3179349cc55cSDimitry Andric         return llvm::createStringError(
3180349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3181349cc55cSDimitry Andric             "duplicate DECL_OFFSET record in AST file");
31820b57cec5SDimitry Andric       F.DeclOffsets = (const DeclOffset *)Blob.data();
31830b57cec5SDimitry Andric       F.LocalNumDecls = Record[0];
31840b57cec5SDimitry Andric       unsigned LocalBaseDeclID = Record[1];
31850b57cec5SDimitry Andric       F.BaseDeclID = getTotalNumDecls();
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric       if (F.LocalNumDecls > 0) {
31880b57cec5SDimitry Andric         // Introduce the global -> local mapping for declarations within this
31890b57cec5SDimitry Andric         // module.
31900b57cec5SDimitry Andric         GlobalDeclMap.insert(
31910b57cec5SDimitry Andric           std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
31920b57cec5SDimitry Andric 
31930b57cec5SDimitry Andric         // Introduce the local -> global mapping for declarations within this
31940b57cec5SDimitry Andric         // module.
31950b57cec5SDimitry Andric         F.DeclRemap.insertOrReplace(
31960b57cec5SDimitry Andric           std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric         // Introduce the global -> local mapping for declarations within this
31990b57cec5SDimitry Andric         // module.
32000b57cec5SDimitry Andric         F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
32010b57cec5SDimitry Andric 
32020b57cec5SDimitry Andric         DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
32030b57cec5SDimitry Andric       }
32040b57cec5SDimitry Andric       break;
32050b57cec5SDimitry Andric     }
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric     case TU_UPDATE_LEXICAL: {
32080b57cec5SDimitry Andric       DeclContext *TU = ContextObj->getTranslationUnitDecl();
32090b57cec5SDimitry Andric       LexicalContents Contents(
32100b57cec5SDimitry Andric           reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
32110b57cec5SDimitry Andric               Blob.data()),
32120b57cec5SDimitry Andric           static_cast<unsigned int>(Blob.size() / 4));
32130b57cec5SDimitry Andric       TULexicalDecls.push_back(std::make_pair(&F, Contents));
32140b57cec5SDimitry Andric       TU->setHasExternalLexicalStorage(true);
32150b57cec5SDimitry Andric       break;
32160b57cec5SDimitry Andric     }
32170b57cec5SDimitry Andric 
32180b57cec5SDimitry Andric     case UPDATE_VISIBLE: {
32190b57cec5SDimitry Andric       unsigned Idx = 0;
32200b57cec5SDimitry Andric       serialization::DeclID ID = ReadDeclID(F, Record, Idx);
32210b57cec5SDimitry Andric       auto *Data = (const unsigned char*)Blob.data();
32220b57cec5SDimitry Andric       PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
32230b57cec5SDimitry Andric       // If we've already loaded the decl, perform the updates when we finish
32240b57cec5SDimitry Andric       // loading this block.
32250b57cec5SDimitry Andric       if (Decl *D = GetExistingDecl(ID))
32260b57cec5SDimitry Andric         PendingUpdateRecords.push_back(
32270b57cec5SDimitry Andric             PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
32280b57cec5SDimitry Andric       break;
32290b57cec5SDimitry Andric     }
32300b57cec5SDimitry Andric 
32310b57cec5SDimitry Andric     case IDENTIFIER_TABLE:
3232fe6060f1SDimitry Andric       F.IdentifierTableData =
3233fe6060f1SDimitry Andric           reinterpret_cast<const unsigned char *>(Blob.data());
32340b57cec5SDimitry Andric       if (Record[0]) {
32350b57cec5SDimitry Andric         F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3236fe6060f1SDimitry Andric             F.IdentifierTableData + Record[0],
3237fe6060f1SDimitry Andric             F.IdentifierTableData + sizeof(uint32_t),
3238fe6060f1SDimitry Andric             F.IdentifierTableData,
32390b57cec5SDimitry Andric             ASTIdentifierLookupTrait(*this, F));
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric         PP.getIdentifierTable().setExternalIdentifierLookup(this);
32420b57cec5SDimitry Andric       }
32430b57cec5SDimitry Andric       break;
32440b57cec5SDimitry Andric 
32450b57cec5SDimitry Andric     case IDENTIFIER_OFFSET: {
3246349cc55cSDimitry Andric       if (F.LocalNumIdentifiers != 0)
3247349cc55cSDimitry Andric         return llvm::createStringError(
3248349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3249349cc55cSDimitry Andric             "duplicate IDENTIFIER_OFFSET record in AST file");
32500b57cec5SDimitry Andric       F.IdentifierOffsets = (const uint32_t *)Blob.data();
32510b57cec5SDimitry Andric       F.LocalNumIdentifiers = Record[0];
32520b57cec5SDimitry Andric       unsigned LocalBaseIdentifierID = Record[1];
32530b57cec5SDimitry Andric       F.BaseIdentifierID = getTotalNumIdentifiers();
32540b57cec5SDimitry Andric 
32550b57cec5SDimitry Andric       if (F.LocalNumIdentifiers > 0) {
32560b57cec5SDimitry Andric         // Introduce the global -> local mapping for identifiers within this
32570b57cec5SDimitry Andric         // module.
32580b57cec5SDimitry Andric         GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
32590b57cec5SDimitry Andric                                                   &F));
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric         // Introduce the local -> global mapping for identifiers within this
32620b57cec5SDimitry Andric         // module.
32630b57cec5SDimitry Andric         F.IdentifierRemap.insertOrReplace(
32640b57cec5SDimitry Andric           std::make_pair(LocalBaseIdentifierID,
32650b57cec5SDimitry Andric                          F.BaseIdentifierID - LocalBaseIdentifierID));
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric         IdentifiersLoaded.resize(IdentifiersLoaded.size()
32680b57cec5SDimitry Andric                                  + F.LocalNumIdentifiers);
32690b57cec5SDimitry Andric       }
32700b57cec5SDimitry Andric       break;
32710b57cec5SDimitry Andric     }
32720b57cec5SDimitry Andric 
32730b57cec5SDimitry Andric     case INTERESTING_IDENTIFIERS:
32740b57cec5SDimitry Andric       F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
32750b57cec5SDimitry Andric       break;
32760b57cec5SDimitry Andric 
32770b57cec5SDimitry Andric     case EAGERLY_DESERIALIZED_DECLS:
32780b57cec5SDimitry Andric       // FIXME: Skip reading this record if our ASTConsumer doesn't care
32790b57cec5SDimitry Andric       // about "interesting" decls (for instance, if we're building a module).
32800b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
32810b57cec5SDimitry Andric         EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
32820b57cec5SDimitry Andric       break;
32830b57cec5SDimitry Andric 
32840b57cec5SDimitry Andric     case MODULAR_CODEGEN_DECLS:
32850b57cec5SDimitry Andric       // FIXME: Skip reading this record if our ASTConsumer doesn't care about
32860b57cec5SDimitry Andric       // them (ie: if we're not codegenerating this module).
32875ffd83dbSDimitry Andric       if (F.Kind == MK_MainFile ||
32885ffd83dbSDimitry Andric           getContext().getLangOpts().BuildingPCHWithObjectFile)
32890b57cec5SDimitry Andric         for (unsigned I = 0, N = Record.size(); I != N; ++I)
32900b57cec5SDimitry Andric           EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
32910b57cec5SDimitry Andric       break;
32920b57cec5SDimitry Andric 
32930b57cec5SDimitry Andric     case SPECIAL_TYPES:
32940b57cec5SDimitry Andric       if (SpecialTypes.empty()) {
32950b57cec5SDimitry Andric         for (unsigned I = 0, N = Record.size(); I != N; ++I)
32960b57cec5SDimitry Andric           SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
32970b57cec5SDimitry Andric         break;
32980b57cec5SDimitry Andric       }
32990b57cec5SDimitry Andric 
3300349cc55cSDimitry Andric       if (SpecialTypes.size() != Record.size())
3301349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3302349cc55cSDimitry Andric                                        "invalid special-types record");
33030b57cec5SDimitry Andric 
33040b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I) {
33050b57cec5SDimitry Andric         serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
33060b57cec5SDimitry Andric         if (!SpecialTypes[I])
33070b57cec5SDimitry Andric           SpecialTypes[I] = ID;
33080b57cec5SDimitry Andric         // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
33090b57cec5SDimitry Andric         // merge step?
33100b57cec5SDimitry Andric       }
33110b57cec5SDimitry Andric       break;
33120b57cec5SDimitry Andric 
33130b57cec5SDimitry Andric     case STATISTICS:
33140b57cec5SDimitry Andric       TotalNumStatements += Record[0];
33150b57cec5SDimitry Andric       TotalNumMacros += Record[1];
33160b57cec5SDimitry Andric       TotalLexicalDeclContexts += Record[2];
33170b57cec5SDimitry Andric       TotalVisibleDeclContexts += Record[3];
33180b57cec5SDimitry Andric       break;
33190b57cec5SDimitry Andric 
33200b57cec5SDimitry Andric     case UNUSED_FILESCOPED_DECLS:
33210b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
33220b57cec5SDimitry Andric         UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
33230b57cec5SDimitry Andric       break;
33240b57cec5SDimitry Andric 
33250b57cec5SDimitry Andric     case DELEGATING_CTORS:
33260b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
33270b57cec5SDimitry Andric         DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
33280b57cec5SDimitry Andric       break;
33290b57cec5SDimitry Andric 
33300b57cec5SDimitry Andric     case WEAK_UNDECLARED_IDENTIFIERS:
333181ad6265SDimitry Andric       if (Record.size() % 3 != 0)
3332349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3333349cc55cSDimitry Andric                                        "invalid weak identifiers record");
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric       // FIXME: Ignore weak undeclared identifiers from non-original PCH
33360b57cec5SDimitry Andric       // files. This isn't the way to do it :)
33370b57cec5SDimitry Andric       WeakUndeclaredIdentifiers.clear();
33380b57cec5SDimitry Andric 
33390b57cec5SDimitry Andric       // Translate the weak, undeclared identifiers into global IDs.
33400b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
33410b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(
33420b57cec5SDimitry Andric           getGlobalIdentifierID(F, Record[I++]));
33430b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(
33440b57cec5SDimitry Andric           getGlobalIdentifierID(F, Record[I++]));
33450b57cec5SDimitry Andric         WeakUndeclaredIdentifiers.push_back(
33460b57cec5SDimitry Andric             ReadSourceLocation(F, Record, I).getRawEncoding());
33470b57cec5SDimitry Andric       }
33480b57cec5SDimitry Andric       break;
33490b57cec5SDimitry Andric 
33500b57cec5SDimitry Andric     case SELECTOR_OFFSETS: {
33510b57cec5SDimitry Andric       F.SelectorOffsets = (const uint32_t *)Blob.data();
33520b57cec5SDimitry Andric       F.LocalNumSelectors = Record[0];
33530b57cec5SDimitry Andric       unsigned LocalBaseSelectorID = Record[1];
33540b57cec5SDimitry Andric       F.BaseSelectorID = getTotalNumSelectors();
33550b57cec5SDimitry Andric 
33560b57cec5SDimitry Andric       if (F.LocalNumSelectors > 0) {
33570b57cec5SDimitry Andric         // Introduce the global -> local mapping for selectors within this
33580b57cec5SDimitry Andric         // module.
33590b57cec5SDimitry Andric         GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
33600b57cec5SDimitry Andric 
33610b57cec5SDimitry Andric         // Introduce the local -> global mapping for selectors within this
33620b57cec5SDimitry Andric         // module.
33630b57cec5SDimitry Andric         F.SelectorRemap.insertOrReplace(
33640b57cec5SDimitry Andric           std::make_pair(LocalBaseSelectorID,
33650b57cec5SDimitry Andric                          F.BaseSelectorID - LocalBaseSelectorID));
33660b57cec5SDimitry Andric 
33670b57cec5SDimitry Andric         SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
33680b57cec5SDimitry Andric       }
33690b57cec5SDimitry Andric       break;
33700b57cec5SDimitry Andric     }
33710b57cec5SDimitry Andric 
33720b57cec5SDimitry Andric     case METHOD_POOL:
33730b57cec5SDimitry Andric       F.SelectorLookupTableData = (const unsigned char *)Blob.data();
33740b57cec5SDimitry Andric       if (Record[0])
33750b57cec5SDimitry Andric         F.SelectorLookupTable
33760b57cec5SDimitry Andric           = ASTSelectorLookupTable::Create(
33770b57cec5SDimitry Andric                         F.SelectorLookupTableData + Record[0],
33780b57cec5SDimitry Andric                         F.SelectorLookupTableData,
33790b57cec5SDimitry Andric                         ASTSelectorLookupTrait(*this, F));
33800b57cec5SDimitry Andric       TotalNumMethodPoolEntries += Record[1];
33810b57cec5SDimitry Andric       break;
33820b57cec5SDimitry Andric 
33830b57cec5SDimitry Andric     case REFERENCED_SELECTOR_POOL:
33840b57cec5SDimitry Andric       if (!Record.empty()) {
33850b57cec5SDimitry Andric         for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
33860b57cec5SDimitry Andric           ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
33870b57cec5SDimitry Andric                                                                 Record[Idx++]));
33880b57cec5SDimitry Andric           ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
33890b57cec5SDimitry Andric                                               getRawEncoding());
33900b57cec5SDimitry Andric         }
33910b57cec5SDimitry Andric       }
33920b57cec5SDimitry Andric       break;
33930b57cec5SDimitry Andric 
339481ad6265SDimitry Andric     case PP_ASSUME_NONNULL_LOC: {
339581ad6265SDimitry Andric       unsigned Idx = 0;
339681ad6265SDimitry Andric       if (!Record.empty())
339781ad6265SDimitry Andric         PP.setPreambleRecordedPragmaAssumeNonNullLoc(
339881ad6265SDimitry Andric             ReadSourceLocation(F, Record, Idx));
339981ad6265SDimitry Andric       break;
340081ad6265SDimitry Andric     }
340181ad6265SDimitry Andric 
34020b57cec5SDimitry Andric     case PP_CONDITIONAL_STACK:
34030b57cec5SDimitry Andric       if (!Record.empty()) {
34040b57cec5SDimitry Andric         unsigned Idx = 0, End = Record.size() - 1;
34050b57cec5SDimitry Andric         bool ReachedEOFWhileSkipping = Record[Idx++];
3406*bdd1243dSDimitry Andric         std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
34070b57cec5SDimitry Andric         if (ReachedEOFWhileSkipping) {
34080b57cec5SDimitry Andric           SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
34090b57cec5SDimitry Andric           SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
34100b57cec5SDimitry Andric           bool FoundNonSkipPortion = Record[Idx++];
34110b57cec5SDimitry Andric           bool FoundElse = Record[Idx++];
34120b57cec5SDimitry Andric           SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
34130b57cec5SDimitry Andric           SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
34140b57cec5SDimitry Andric                            FoundElse, ElseLoc);
34150b57cec5SDimitry Andric         }
34160b57cec5SDimitry Andric         SmallVector<PPConditionalInfo, 4> ConditionalStack;
34170b57cec5SDimitry Andric         while (Idx < End) {
34180b57cec5SDimitry Andric           auto Loc = ReadSourceLocation(F, Record, Idx);
34190b57cec5SDimitry Andric           bool WasSkipping = Record[Idx++];
34200b57cec5SDimitry Andric           bool FoundNonSkip = Record[Idx++];
34210b57cec5SDimitry Andric           bool FoundElse = Record[Idx++];
34220b57cec5SDimitry Andric           ConditionalStack.push_back(
34230b57cec5SDimitry Andric               {Loc, WasSkipping, FoundNonSkip, FoundElse});
34240b57cec5SDimitry Andric         }
34250b57cec5SDimitry Andric         PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
34260b57cec5SDimitry Andric       }
34270b57cec5SDimitry Andric       break;
34280b57cec5SDimitry Andric 
34290b57cec5SDimitry Andric     case PP_COUNTER_VALUE:
34300b57cec5SDimitry Andric       if (!Record.empty() && Listener)
34310b57cec5SDimitry Andric         Listener->ReadCounter(F, Record[0]);
34320b57cec5SDimitry Andric       break;
34330b57cec5SDimitry Andric 
34340b57cec5SDimitry Andric     case FILE_SORTED_DECLS:
34350b57cec5SDimitry Andric       F.FileSortedDecls = (const DeclID *)Blob.data();
34360b57cec5SDimitry Andric       F.NumFileSortedDecls = Record[0];
34370b57cec5SDimitry Andric       break;
34380b57cec5SDimitry Andric 
34390b57cec5SDimitry Andric     case SOURCE_LOCATION_OFFSETS: {
34400b57cec5SDimitry Andric       F.SLocEntryOffsets = (const uint32_t *)Blob.data();
34410b57cec5SDimitry Andric       F.LocalNumSLocEntries = Record[0];
3442fe6060f1SDimitry Andric       SourceLocation::UIntTy SLocSpaceSize = Record[1];
34435ffd83dbSDimitry Andric       F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
34440b57cec5SDimitry Andric       std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
34450b57cec5SDimitry Andric           SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
34460b57cec5SDimitry Andric                                               SLocSpaceSize);
3447*bdd1243dSDimitry Andric       if (!F.SLocEntryBaseID) {
3448*bdd1243dSDimitry Andric         if (!Diags.isDiagnosticInFlight()) {
3449*bdd1243dSDimitry Andric           Diags.Report(SourceLocation(), diag::remark_sloc_usage);
3450*bdd1243dSDimitry Andric           SourceMgr.noteSLocAddressSpaceUsage(Diags);
3451*bdd1243dSDimitry Andric         }
3452349cc55cSDimitry Andric         return llvm::createStringError(std::errc::invalid_argument,
3453349cc55cSDimitry Andric                                        "ran out of source locations");
3454*bdd1243dSDimitry Andric       }
34550b57cec5SDimitry Andric       // Make our entry in the range map. BaseID is negative and growing, so
34560b57cec5SDimitry Andric       // we invert it. Because we invert it, though, we need the other end of
34570b57cec5SDimitry Andric       // the range.
34580b57cec5SDimitry Andric       unsigned RangeStart =
34590b57cec5SDimitry Andric           unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
34600b57cec5SDimitry Andric       GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
34610b57cec5SDimitry Andric       F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
34620b57cec5SDimitry Andric 
34630b57cec5SDimitry Andric       // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3464fe6060f1SDimitry Andric       assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
34650b57cec5SDimitry Andric       GlobalSLocOffsetMap.insert(
34660b57cec5SDimitry Andric           std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
34670b57cec5SDimitry Andric                            - SLocSpaceSize,&F));
34680b57cec5SDimitry Andric 
34690b57cec5SDimitry Andric       // Initialize the remapping table.
34700b57cec5SDimitry Andric       // Invalid stays invalid.
34710b57cec5SDimitry Andric       F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
34720b57cec5SDimitry Andric       // This module. Base was 2 when being compiled.
3473fe6060f1SDimitry Andric       F.SLocRemap.insertOrReplace(std::make_pair(
3474fe6060f1SDimitry Andric           2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
34750b57cec5SDimitry Andric 
34760b57cec5SDimitry Andric       TotalNumSLocEntries += F.LocalNumSLocEntries;
34770b57cec5SDimitry Andric       break;
34780b57cec5SDimitry Andric     }
34790b57cec5SDimitry Andric 
34800b57cec5SDimitry Andric     case MODULE_OFFSET_MAP:
34810b57cec5SDimitry Andric       F.ModuleOffsetMap = Blob;
34820b57cec5SDimitry Andric       break;
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric     case SOURCE_MANAGER_LINE_TABLE:
3485349cc55cSDimitry Andric       ParseLineTable(F, Record);
34860b57cec5SDimitry Andric       break;
34870b57cec5SDimitry Andric 
34880b57cec5SDimitry Andric     case SOURCE_LOCATION_PRELOADS: {
34890b57cec5SDimitry Andric       // Need to transform from the local view (1-based IDs) to the global view,
34900b57cec5SDimitry Andric       // which is based off F.SLocEntryBaseID.
3491349cc55cSDimitry Andric       if (!F.PreloadSLocEntries.empty())
3492349cc55cSDimitry Andric         return llvm::createStringError(
3493349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3494349cc55cSDimitry Andric             "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
34950b57cec5SDimitry Andric 
34960b57cec5SDimitry Andric       F.PreloadSLocEntries.swap(Record);
34970b57cec5SDimitry Andric       break;
34980b57cec5SDimitry Andric     }
34990b57cec5SDimitry Andric 
35000b57cec5SDimitry Andric     case EXT_VECTOR_DECLS:
35010b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
35020b57cec5SDimitry Andric         ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
35030b57cec5SDimitry Andric       break;
35040b57cec5SDimitry Andric 
35050b57cec5SDimitry Andric     case VTABLE_USES:
3506349cc55cSDimitry Andric       if (Record.size() % 3 != 0)
3507349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3508349cc55cSDimitry Andric                                        "Invalid VTABLE_USES record");
35090b57cec5SDimitry Andric 
35100b57cec5SDimitry Andric       // Later tables overwrite earlier ones.
35110b57cec5SDimitry Andric       // FIXME: Modules will have some trouble with this. This is clearly not
35120b57cec5SDimitry Andric       // the right way to do this.
35130b57cec5SDimitry Andric       VTableUses.clear();
35140b57cec5SDimitry Andric 
35150b57cec5SDimitry Andric       for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
35160b57cec5SDimitry Andric         VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
35170b57cec5SDimitry Andric         VTableUses.push_back(
35180b57cec5SDimitry Andric           ReadSourceLocation(F, Record, Idx).getRawEncoding());
35190b57cec5SDimitry Andric         VTableUses.push_back(Record[Idx++]);
35200b57cec5SDimitry Andric       }
35210b57cec5SDimitry Andric       break;
35220b57cec5SDimitry Andric 
35230b57cec5SDimitry Andric     case PENDING_IMPLICIT_INSTANTIATIONS:
3524349cc55cSDimitry Andric       if (PendingInstantiations.size() % 2 != 0)
3525349cc55cSDimitry Andric         return llvm::createStringError(
3526349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3527349cc55cSDimitry Andric             "Invalid existing PendingInstantiations");
35280b57cec5SDimitry Andric 
3529349cc55cSDimitry Andric       if (Record.size() % 2 != 0)
3530349cc55cSDimitry Andric         return llvm::createStringError(
3531349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3532349cc55cSDimitry Andric             "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
35330b57cec5SDimitry Andric 
35340b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
35350b57cec5SDimitry Andric         PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
35360b57cec5SDimitry Andric         PendingInstantiations.push_back(
35370b57cec5SDimitry Andric           ReadSourceLocation(F, Record, I).getRawEncoding());
35380b57cec5SDimitry Andric       }
35390b57cec5SDimitry Andric       break;
35400b57cec5SDimitry Andric 
35410b57cec5SDimitry Andric     case SEMA_DECL_REFS:
3542349cc55cSDimitry Andric       if (Record.size() != 3)
3543349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3544349cc55cSDimitry Andric                                        "Invalid SEMA_DECL_REFS block");
35450b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
35460b57cec5SDimitry Andric         SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
35470b57cec5SDimitry Andric       break;
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric     case PPD_ENTITIES_OFFSETS: {
35500b57cec5SDimitry Andric       F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
35510b57cec5SDimitry Andric       assert(Blob.size() % sizeof(PPEntityOffset) == 0);
35520b57cec5SDimitry Andric       F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric       unsigned LocalBasePreprocessedEntityID = Record[0];
35550b57cec5SDimitry Andric 
35560b57cec5SDimitry Andric       unsigned StartingID;
35570b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord())
35580b57cec5SDimitry Andric         PP.createPreprocessingRecord();
35590b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord()->getExternalSource())
35600b57cec5SDimitry Andric         PP.getPreprocessingRecord()->SetExternalSource(*this);
35610b57cec5SDimitry Andric       StartingID
35620b57cec5SDimitry Andric         = PP.getPreprocessingRecord()
35630b57cec5SDimitry Andric             ->allocateLoadedEntities(F.NumPreprocessedEntities);
35640b57cec5SDimitry Andric       F.BasePreprocessedEntityID = StartingID;
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric       if (F.NumPreprocessedEntities > 0) {
35670b57cec5SDimitry Andric         // Introduce the global -> local mapping for preprocessed entities in
35680b57cec5SDimitry Andric         // this module.
35690b57cec5SDimitry Andric         GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
35700b57cec5SDimitry Andric 
35710b57cec5SDimitry Andric         // Introduce the local -> global mapping for preprocessed entities in
35720b57cec5SDimitry Andric         // this module.
35730b57cec5SDimitry Andric         F.PreprocessedEntityRemap.insertOrReplace(
35740b57cec5SDimitry Andric           std::make_pair(LocalBasePreprocessedEntityID,
35750b57cec5SDimitry Andric             F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
35760b57cec5SDimitry Andric       }
35770b57cec5SDimitry Andric 
35780b57cec5SDimitry Andric       break;
35790b57cec5SDimitry Andric     }
35800b57cec5SDimitry Andric 
35810b57cec5SDimitry Andric     case PPD_SKIPPED_RANGES: {
35820b57cec5SDimitry Andric       F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
35830b57cec5SDimitry Andric       assert(Blob.size() % sizeof(PPSkippedRange) == 0);
35840b57cec5SDimitry Andric       F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord())
35870b57cec5SDimitry Andric         PP.createPreprocessingRecord();
35880b57cec5SDimitry Andric       if (!PP.getPreprocessingRecord()->getExternalSource())
35890b57cec5SDimitry Andric         PP.getPreprocessingRecord()->SetExternalSource(*this);
35900b57cec5SDimitry Andric       F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
35910b57cec5SDimitry Andric           ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
35920b57cec5SDimitry Andric 
35930b57cec5SDimitry Andric       if (F.NumPreprocessedSkippedRanges > 0)
35940b57cec5SDimitry Andric         GlobalSkippedRangeMap.insert(
35950b57cec5SDimitry Andric             std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
35960b57cec5SDimitry Andric       break;
35970b57cec5SDimitry Andric     }
35980b57cec5SDimitry Andric 
35990b57cec5SDimitry Andric     case DECL_UPDATE_OFFSETS:
3600349cc55cSDimitry Andric       if (Record.size() % 2 != 0)
3601349cc55cSDimitry Andric         return llvm::createStringError(
3602349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3603349cc55cSDimitry Andric             "invalid DECL_UPDATE_OFFSETS block in AST file");
36040b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
36050b57cec5SDimitry Andric         GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
36060b57cec5SDimitry Andric         DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
36070b57cec5SDimitry Andric 
36080b57cec5SDimitry Andric         // If we've already loaded the decl, perform the updates when we finish
36090b57cec5SDimitry Andric         // loading this block.
36100b57cec5SDimitry Andric         if (Decl *D = GetExistingDecl(ID))
36110b57cec5SDimitry Andric           PendingUpdateRecords.push_back(
36120b57cec5SDimitry Andric               PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
36130b57cec5SDimitry Andric       }
36140b57cec5SDimitry Andric       break;
36150b57cec5SDimitry Andric 
36160b57cec5SDimitry Andric     case OBJC_CATEGORIES_MAP:
3617349cc55cSDimitry Andric       if (F.LocalNumObjCCategoriesInMap != 0)
3618349cc55cSDimitry Andric         return llvm::createStringError(
3619349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3620349cc55cSDimitry Andric             "duplicate OBJC_CATEGORIES_MAP record in AST file");
36210b57cec5SDimitry Andric 
36220b57cec5SDimitry Andric       F.LocalNumObjCCategoriesInMap = Record[0];
36230b57cec5SDimitry Andric       F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
36240b57cec5SDimitry Andric       break;
36250b57cec5SDimitry Andric 
36260b57cec5SDimitry Andric     case OBJC_CATEGORIES:
36270b57cec5SDimitry Andric       F.ObjCCategories.swap(Record);
36280b57cec5SDimitry Andric       break;
36290b57cec5SDimitry Andric 
36300b57cec5SDimitry Andric     case CUDA_SPECIAL_DECL_REFS:
36310b57cec5SDimitry Andric       // Later tables overwrite earlier ones.
36320b57cec5SDimitry Andric       // FIXME: Modules will have trouble with this.
36330b57cec5SDimitry Andric       CUDASpecialDeclRefs.clear();
36340b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
36350b57cec5SDimitry Andric         CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
36360b57cec5SDimitry Andric       break;
36370b57cec5SDimitry Andric 
36380b57cec5SDimitry Andric     case HEADER_SEARCH_TABLE:
36390b57cec5SDimitry Andric       F.HeaderFileInfoTableData = Blob.data();
36400b57cec5SDimitry Andric       F.LocalNumHeaderFileInfos = Record[1];
36410b57cec5SDimitry Andric       if (Record[0]) {
36420b57cec5SDimitry Andric         F.HeaderFileInfoTable
36430b57cec5SDimitry Andric           = HeaderFileInfoLookupTable::Create(
36440b57cec5SDimitry Andric                    (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
36450b57cec5SDimitry Andric                    (const unsigned char *)F.HeaderFileInfoTableData,
36460b57cec5SDimitry Andric                    HeaderFileInfoTrait(*this, F,
36470b57cec5SDimitry Andric                                        &PP.getHeaderSearchInfo(),
36480b57cec5SDimitry Andric                                        Blob.data() + Record[2]));
36490b57cec5SDimitry Andric 
36500b57cec5SDimitry Andric         PP.getHeaderSearchInfo().SetExternalSource(this);
36510b57cec5SDimitry Andric         if (!PP.getHeaderSearchInfo().getExternalLookup())
36520b57cec5SDimitry Andric           PP.getHeaderSearchInfo().SetExternalLookup(this);
36530b57cec5SDimitry Andric       }
36540b57cec5SDimitry Andric       break;
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric     case FP_PRAGMA_OPTIONS:
36570b57cec5SDimitry Andric       // Later tables overwrite earlier ones.
36580b57cec5SDimitry Andric       FPPragmaOptions.swap(Record);
36590b57cec5SDimitry Andric       break;
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric     case OPENCL_EXTENSIONS:
36620b57cec5SDimitry Andric       for (unsigned I = 0, E = Record.size(); I != E; ) {
36630b57cec5SDimitry Andric         auto Name = ReadString(Record, I);
3664e8d8bef9SDimitry Andric         auto &OptInfo = OpenCLExtensions.OptMap[Name];
3665e8d8bef9SDimitry Andric         OptInfo.Supported = Record[I++] != 0;
3666e8d8bef9SDimitry Andric         OptInfo.Enabled = Record[I++] != 0;
3667fe6060f1SDimitry Andric         OptInfo.WithPragma = Record[I++] != 0;
3668e8d8bef9SDimitry Andric         OptInfo.Avail = Record[I++];
3669e8d8bef9SDimitry Andric         OptInfo.Core = Record[I++];
3670e8d8bef9SDimitry Andric         OptInfo.Opt = Record[I++];
36710b57cec5SDimitry Andric       }
36720b57cec5SDimitry Andric       break;
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric     case TENTATIVE_DEFINITIONS:
36750b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
36760b57cec5SDimitry Andric         TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
36770b57cec5SDimitry Andric       break;
36780b57cec5SDimitry Andric 
36790b57cec5SDimitry Andric     case KNOWN_NAMESPACES:
36800b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
36810b57cec5SDimitry Andric         KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
36820b57cec5SDimitry Andric       break;
36830b57cec5SDimitry Andric 
36840b57cec5SDimitry Andric     case UNDEFINED_BUT_USED:
3685349cc55cSDimitry Andric       if (UndefinedButUsed.size() % 2 != 0)
3686349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3687349cc55cSDimitry Andric                                        "Invalid existing UndefinedButUsed");
36880b57cec5SDimitry Andric 
3689349cc55cSDimitry Andric       if (Record.size() % 2 != 0)
3690349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3691349cc55cSDimitry Andric                                        "invalid undefined-but-used record");
36920b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
36930b57cec5SDimitry Andric         UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
36940b57cec5SDimitry Andric         UndefinedButUsed.push_back(
36950b57cec5SDimitry Andric             ReadSourceLocation(F, Record, I).getRawEncoding());
36960b57cec5SDimitry Andric       }
36970b57cec5SDimitry Andric       break;
36980b57cec5SDimitry Andric 
36990b57cec5SDimitry Andric     case DELETE_EXPRS_TO_ANALYZE:
37000b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N;) {
37010b57cec5SDimitry Andric         DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
37020b57cec5SDimitry Andric         const uint64_t Count = Record[I++];
37030b57cec5SDimitry Andric         DelayedDeleteExprs.push_back(Count);
37040b57cec5SDimitry Andric         for (uint64_t C = 0; C < Count; ++C) {
37050b57cec5SDimitry Andric           DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
37060b57cec5SDimitry Andric           bool IsArrayForm = Record[I++] == 1;
37070b57cec5SDimitry Andric           DelayedDeleteExprs.push_back(IsArrayForm);
37080b57cec5SDimitry Andric         }
37090b57cec5SDimitry Andric       }
37100b57cec5SDimitry Andric       break;
37110b57cec5SDimitry Andric 
37120b57cec5SDimitry Andric     case IMPORTED_MODULES:
37130b57cec5SDimitry Andric       if (!F.isModule()) {
37140b57cec5SDimitry Andric         // If we aren't loading a module (which has its own exports), make
37150b57cec5SDimitry Andric         // all of the imported modules visible.
37160b57cec5SDimitry Andric         // FIXME: Deal with macros-only imports.
37170b57cec5SDimitry Andric         for (unsigned I = 0, N = Record.size(); I != N; /**/) {
37180b57cec5SDimitry Andric           unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
37190b57cec5SDimitry Andric           SourceLocation Loc = ReadSourceLocation(F, Record, I);
37200b57cec5SDimitry Andric           if (GlobalID) {
37210b57cec5SDimitry Andric             ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
37220b57cec5SDimitry Andric             if (DeserializationListener)
37230b57cec5SDimitry Andric               DeserializationListener->ModuleImportRead(GlobalID, Loc);
37240b57cec5SDimitry Andric           }
37250b57cec5SDimitry Andric         }
37260b57cec5SDimitry Andric       }
37270b57cec5SDimitry Andric       break;
37280b57cec5SDimitry Andric 
37290b57cec5SDimitry Andric     case MACRO_OFFSET: {
3730349cc55cSDimitry Andric       if (F.LocalNumMacros != 0)
3731349cc55cSDimitry Andric         return llvm::createStringError(
3732349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3733349cc55cSDimitry Andric             "duplicate MACRO_OFFSET record in AST file");
37340b57cec5SDimitry Andric       F.MacroOffsets = (const uint32_t *)Blob.data();
37350b57cec5SDimitry Andric       F.LocalNumMacros = Record[0];
37360b57cec5SDimitry Andric       unsigned LocalBaseMacroID = Record[1];
37375ffd83dbSDimitry Andric       F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
37380b57cec5SDimitry Andric       F.BaseMacroID = getTotalNumMacros();
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric       if (F.LocalNumMacros > 0) {
37410b57cec5SDimitry Andric         // Introduce the global -> local mapping for macros within this module.
37420b57cec5SDimitry Andric         GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric         // Introduce the local -> global mapping for macros within this module.
37450b57cec5SDimitry Andric         F.MacroRemap.insertOrReplace(
37460b57cec5SDimitry Andric           std::make_pair(LocalBaseMacroID,
37470b57cec5SDimitry Andric                          F.BaseMacroID - LocalBaseMacroID));
37480b57cec5SDimitry Andric 
37490b57cec5SDimitry Andric         MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
37500b57cec5SDimitry Andric       }
37510b57cec5SDimitry Andric       break;
37520b57cec5SDimitry Andric     }
37530b57cec5SDimitry Andric 
375404eeddc0SDimitry Andric     case PP_INCLUDED_FILES:
375504eeddc0SDimitry Andric       readIncludedFiles(F, Blob, PP);
375604eeddc0SDimitry Andric       break;
375704eeddc0SDimitry Andric 
37580b57cec5SDimitry Andric     case LATE_PARSED_TEMPLATE:
3759e8d8bef9SDimitry Andric       LateParsedTemplates.emplace_back(
3760e8d8bef9SDimitry Andric           std::piecewise_construct, std::forward_as_tuple(&F),
3761e8d8bef9SDimitry Andric           std::forward_as_tuple(Record.begin(), Record.end()));
37620b57cec5SDimitry Andric       break;
37630b57cec5SDimitry Andric 
37640b57cec5SDimitry Andric     case OPTIMIZE_PRAGMA_OPTIONS:
3765349cc55cSDimitry Andric       if (Record.size() != 1)
3766349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3767349cc55cSDimitry Andric                                        "invalid pragma optimize record");
37680b57cec5SDimitry Andric       OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
37690b57cec5SDimitry Andric       break;
37700b57cec5SDimitry Andric 
37710b57cec5SDimitry Andric     case MSSTRUCT_PRAGMA_OPTIONS:
3772349cc55cSDimitry Andric       if (Record.size() != 1)
3773349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3774349cc55cSDimitry Andric                                        "invalid pragma ms_struct record");
37750b57cec5SDimitry Andric       PragmaMSStructState = Record[0];
37760b57cec5SDimitry Andric       break;
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3779349cc55cSDimitry Andric       if (Record.size() != 2)
3780349cc55cSDimitry Andric         return llvm::createStringError(
3781349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
3782349cc55cSDimitry Andric             "invalid pragma pointers to members record");
37830b57cec5SDimitry Andric       PragmaMSPointersToMembersState = Record[0];
37840b57cec5SDimitry Andric       PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
37850b57cec5SDimitry Andric       break;
37860b57cec5SDimitry Andric 
37870b57cec5SDimitry Andric     case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
37880b57cec5SDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
37890b57cec5SDimitry Andric         UnusedLocalTypedefNameCandidates.push_back(
37900b57cec5SDimitry Andric             getGlobalDeclID(F, Record[I]));
37910b57cec5SDimitry Andric       break;
37920b57cec5SDimitry Andric 
37930b57cec5SDimitry Andric     case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3794349cc55cSDimitry Andric       if (Record.size() != 1)
3795349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3796349cc55cSDimitry Andric                                        "invalid cuda pragma options record");
37970b57cec5SDimitry Andric       ForceCUDAHostDeviceDepth = Record[0];
37980b57cec5SDimitry Andric       break;
37990b57cec5SDimitry Andric 
3800e8d8bef9SDimitry Andric     case ALIGN_PACK_PRAGMA_OPTIONS: {
3801349cc55cSDimitry Andric       if (Record.size() < 3)
3802349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3803349cc55cSDimitry Andric                                        "invalid pragma pack record");
3804e8d8bef9SDimitry Andric       PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
3805e8d8bef9SDimitry Andric       PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
38060b57cec5SDimitry Andric       unsigned NumStackEntries = Record[2];
38070b57cec5SDimitry Andric       unsigned Idx = 3;
38080b57cec5SDimitry Andric       // Reset the stack when importing a new module.
3809e8d8bef9SDimitry Andric       PragmaAlignPackStack.clear();
38100b57cec5SDimitry Andric       for (unsigned I = 0; I < NumStackEntries; ++I) {
3811e8d8bef9SDimitry Andric         PragmaAlignPackStackEntry Entry;
3812e8d8bef9SDimitry Andric         Entry.Value = ReadAlignPackInfo(Record[Idx++]);
38130b57cec5SDimitry Andric         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
38140b57cec5SDimitry Andric         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3815e8d8bef9SDimitry Andric         PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
3816e8d8bef9SDimitry Andric         Entry.SlotLabel = PragmaAlignPackStrings.back();
3817e8d8bef9SDimitry Andric         PragmaAlignPackStack.push_back(Entry);
38180b57cec5SDimitry Andric       }
38190b57cec5SDimitry Andric       break;
38200b57cec5SDimitry Andric     }
38215ffd83dbSDimitry Andric 
38225ffd83dbSDimitry Andric     case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3823349cc55cSDimitry Andric       if (Record.size() < 3)
3824349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
3825349cc55cSDimitry Andric                                        "invalid pragma float control record");
3826e8d8bef9SDimitry Andric       FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
38275ffd83dbSDimitry Andric       FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
38285ffd83dbSDimitry Andric       unsigned NumStackEntries = Record[2];
38295ffd83dbSDimitry Andric       unsigned Idx = 3;
38305ffd83dbSDimitry Andric       // Reset the stack when importing a new module.
38315ffd83dbSDimitry Andric       FpPragmaStack.clear();
38325ffd83dbSDimitry Andric       for (unsigned I = 0; I < NumStackEntries; ++I) {
38335ffd83dbSDimitry Andric         FpPragmaStackEntry Entry;
3834e8d8bef9SDimitry Andric         Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
38355ffd83dbSDimitry Andric         Entry.Location = ReadSourceLocation(F, Record[Idx++]);
38365ffd83dbSDimitry Andric         Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
38375ffd83dbSDimitry Andric         FpPragmaStrings.push_back(ReadString(Record, Idx));
38385ffd83dbSDimitry Andric         Entry.SlotLabel = FpPragmaStrings.back();
38395ffd83dbSDimitry Andric         FpPragmaStack.push_back(Entry);
38405ffd83dbSDimitry Andric       }
38415ffd83dbSDimitry Andric       break;
38425ffd83dbSDimitry Andric     }
38435ffd83dbSDimitry Andric 
38445ffd83dbSDimitry Andric     case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
38455ffd83dbSDimitry Andric       for (unsigned I = 0, N = Record.size(); I != N; ++I)
3846fe6060f1SDimitry Andric         DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
38475ffd83dbSDimitry Andric       break;
38480b57cec5SDimitry Andric     }
38490b57cec5SDimitry Andric   }
38500b57cec5SDimitry Andric }
38510b57cec5SDimitry Andric 
38520b57cec5SDimitry Andric void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
38530b57cec5SDimitry Andric   assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
38540b57cec5SDimitry Andric 
38550b57cec5SDimitry Andric   // Additional remapping information.
38560b57cec5SDimitry Andric   const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
38570b57cec5SDimitry Andric   const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
38580b57cec5SDimitry Andric   F.ModuleOffsetMap = StringRef();
38590b57cec5SDimitry Andric 
38600b57cec5SDimitry Andric   // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
38610b57cec5SDimitry Andric   if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
38620b57cec5SDimitry Andric     F.SLocRemap.insert(std::make_pair(0U, 0));
38630b57cec5SDimitry Andric     F.SLocRemap.insert(std::make_pair(2U, 1));
38640b57cec5SDimitry Andric   }
38650b57cec5SDimitry Andric 
38660b57cec5SDimitry Andric   // Continuous range maps we may be updating in our module.
3867fe6060f1SDimitry Andric   using SLocRemapBuilder =
3868fe6060f1SDimitry Andric       ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
3869fe6060f1SDimitry Andric                          2>::Builder;
38700b57cec5SDimitry Andric   using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
3871fe6060f1SDimitry Andric   SLocRemapBuilder SLocRemap(F.SLocRemap);
38720b57cec5SDimitry Andric   RemapBuilder IdentifierRemap(F.IdentifierRemap);
38730b57cec5SDimitry Andric   RemapBuilder MacroRemap(F.MacroRemap);
38740b57cec5SDimitry Andric   RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
38750b57cec5SDimitry Andric   RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
38760b57cec5SDimitry Andric   RemapBuilder SelectorRemap(F.SelectorRemap);
38770b57cec5SDimitry Andric   RemapBuilder DeclRemap(F.DeclRemap);
38780b57cec5SDimitry Andric   RemapBuilder TypeRemap(F.TypeRemap);
38790b57cec5SDimitry Andric 
38800b57cec5SDimitry Andric   while (Data < DataEnd) {
38810b57cec5SDimitry Andric     // FIXME: Looking up dependency modules by filename is horrible. Let's
38825ffd83dbSDimitry Andric     // start fixing this with prebuilt, explicit and implicit modules and see
38835ffd83dbSDimitry Andric     // how it goes...
38840b57cec5SDimitry Andric     using namespace llvm::support;
38850b57cec5SDimitry Andric     ModuleKind Kind = static_cast<ModuleKind>(
38860b57cec5SDimitry Andric       endian::readNext<uint8_t, little, unaligned>(Data));
38870b57cec5SDimitry Andric     uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
38880b57cec5SDimitry Andric     StringRef Name = StringRef((const char*)Data, Len);
38890b57cec5SDimitry Andric     Data += Len;
38905ffd83dbSDimitry Andric     ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
38915ffd83dbSDimitry Andric                               Kind == MK_ImplicitModule
38920b57cec5SDimitry Andric                           ? ModuleMgr.lookupByModuleName(Name)
38930b57cec5SDimitry Andric                           : ModuleMgr.lookupByFileName(Name));
38940b57cec5SDimitry Andric     if (!OM) {
38950b57cec5SDimitry Andric       std::string Msg =
38960b57cec5SDimitry Andric           "SourceLocation remap refers to unknown module, cannot find ";
38975ffd83dbSDimitry Andric       Msg.append(std::string(Name));
38980b57cec5SDimitry Andric       Error(Msg);
38990b57cec5SDimitry Andric       return;
39000b57cec5SDimitry Andric     }
39010b57cec5SDimitry Andric 
3902fe6060f1SDimitry Andric     SourceLocation::UIntTy SLocOffset =
39030b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39040b57cec5SDimitry Andric     uint32_t IdentifierIDOffset =
39050b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39060b57cec5SDimitry Andric     uint32_t MacroIDOffset =
39070b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39080b57cec5SDimitry Andric     uint32_t PreprocessedEntityIDOffset =
39090b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39100b57cec5SDimitry Andric     uint32_t SubmoduleIDOffset =
39110b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39120b57cec5SDimitry Andric     uint32_t SelectorIDOffset =
39130b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39140b57cec5SDimitry Andric     uint32_t DeclIDOffset =
39150b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39160b57cec5SDimitry Andric     uint32_t TypeIndexOffset =
39170b57cec5SDimitry Andric         endian::readNext<uint32_t, little, unaligned>(Data);
39180b57cec5SDimitry Andric 
39190b57cec5SDimitry Andric     auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
39200b57cec5SDimitry Andric                          RemapBuilder &Remap) {
3921fe6060f1SDimitry Andric       constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
39220b57cec5SDimitry Andric       if (Offset != None)
39230b57cec5SDimitry Andric         Remap.insert(std::make_pair(Offset,
39240b57cec5SDimitry Andric                                     static_cast<int>(BaseOffset - Offset)));
39250b57cec5SDimitry Andric     };
3926fe6060f1SDimitry Andric 
3927fe6060f1SDimitry Andric     constexpr SourceLocation::UIntTy SLocNone =
3928fe6060f1SDimitry Andric         std::numeric_limits<SourceLocation::UIntTy>::max();
3929fe6060f1SDimitry Andric     if (SLocOffset != SLocNone)
3930fe6060f1SDimitry Andric       SLocRemap.insert(std::make_pair(
3931fe6060f1SDimitry Andric           SLocOffset, static_cast<SourceLocation::IntTy>(
3932fe6060f1SDimitry Andric                           OM->SLocEntryBaseOffset - SLocOffset)));
3933fe6060f1SDimitry Andric 
39340b57cec5SDimitry Andric     mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
39350b57cec5SDimitry Andric     mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
39360b57cec5SDimitry Andric     mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
39370b57cec5SDimitry Andric               PreprocessedEntityRemap);
39380b57cec5SDimitry Andric     mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
39390b57cec5SDimitry Andric     mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
39400b57cec5SDimitry Andric     mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
39410b57cec5SDimitry Andric     mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
39420b57cec5SDimitry Andric 
39430b57cec5SDimitry Andric     // Global -> local mappings.
39440b57cec5SDimitry Andric     F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
39450b57cec5SDimitry Andric   }
39460b57cec5SDimitry Andric }
39470b57cec5SDimitry Andric 
39480b57cec5SDimitry Andric ASTReader::ASTReadResult
39490b57cec5SDimitry Andric ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
39500b57cec5SDimitry Andric                                   const ModuleFile *ImportedBy,
39510b57cec5SDimitry Andric                                   unsigned ClientLoadCapabilities) {
39520b57cec5SDimitry Andric   unsigned Idx = 0;
39530b57cec5SDimitry Andric   F.ModuleMapPath = ReadPath(F, Record, Idx);
39540b57cec5SDimitry Andric 
39550b57cec5SDimitry Andric   // Try to resolve ModuleName in the current header search context and
39560b57cec5SDimitry Andric   // verify that it is found in the same module map file as we saved. If the
39570b57cec5SDimitry Andric   // top-level AST file is a main file, skip this check because there is no
39580b57cec5SDimitry Andric   // usable header search context.
39590b57cec5SDimitry Andric   assert(!F.ModuleName.empty() &&
39600b57cec5SDimitry Andric          "MODULE_NAME should come before MODULE_MAP_FILE");
39610b57cec5SDimitry Andric   if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
39620b57cec5SDimitry Andric     // An implicitly-loaded module file should have its module listed in some
39630b57cec5SDimitry Andric     // module map file that we've already loaded.
3964349cc55cSDimitry Andric     Module *M =
3965349cc55cSDimitry Andric         PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
39660b57cec5SDimitry Andric     auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3967*bdd1243dSDimitry Andric     OptionalFileEntryRef ModMap =
3968*bdd1243dSDimitry Andric         M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
39690b57cec5SDimitry Andric     // Don't emit module relocation error if we have -fno-validate-pch
3970e8d8bef9SDimitry Andric     if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
3971e8d8bef9SDimitry Andric               DisableValidationForModuleKind::Module) &&
3972e8d8bef9SDimitry Andric         !ModMap) {
3973fe6060f1SDimitry Andric       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
3974*bdd1243dSDimitry Andric         if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
39750b57cec5SDimitry Andric           // This module was defined by an imported (explicit) module.
39760b57cec5SDimitry Andric           Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
39770b57cec5SDimitry Andric                                                << ASTFE->getName();
39780b57cec5SDimitry Andric         } else {
39790b57cec5SDimitry Andric           // This module was built with a different module map.
39800b57cec5SDimitry Andric           Diag(diag::err_imported_module_not_found)
3981a7dea167SDimitry Andric               << F.ModuleName << F.FileName
3982a7dea167SDimitry Andric               << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3983a7dea167SDimitry Andric               << !ImportedBy;
39840b57cec5SDimitry Andric           // In case it was imported by a PCH, there's a chance the user is
39850b57cec5SDimitry Andric           // just missing to include the search path to the directory containing
39860b57cec5SDimitry Andric           // the modulemap.
3987a7dea167SDimitry Andric           if (ImportedBy && ImportedBy->Kind == MK_PCH)
39880b57cec5SDimitry Andric             Diag(diag::note_imported_by_pch_module_not_found)
39890b57cec5SDimitry Andric                 << llvm::sys::path::parent_path(F.ModuleMapPath);
39900b57cec5SDimitry Andric         }
39910b57cec5SDimitry Andric       }
39920b57cec5SDimitry Andric       return OutOfDate;
39930b57cec5SDimitry Andric     }
39940b57cec5SDimitry Andric 
3995e8d8bef9SDimitry Andric     assert(M && M->Name == F.ModuleName && "found module with different name");
39960b57cec5SDimitry Andric 
39970b57cec5SDimitry Andric     // Check the primary module map file.
3998a7dea167SDimitry Andric     auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3999a7dea167SDimitry Andric     if (!StoredModMap || *StoredModMap != ModMap) {
40000b57cec5SDimitry Andric       assert(ModMap && "found module is missing module map file");
4001a7dea167SDimitry Andric       assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
4002a7dea167SDimitry Andric              "top-level import should be verified");
4003a7dea167SDimitry Andric       bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
4004fe6060f1SDimitry Andric       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
40050b57cec5SDimitry Andric         Diag(diag::err_imported_module_modmap_changed)
4006a7dea167SDimitry Andric             << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
4007a7dea167SDimitry Andric             << ModMap->getName() << F.ModuleMapPath << NotImported;
40080b57cec5SDimitry Andric       return OutOfDate;
40090b57cec5SDimitry Andric     }
40100b57cec5SDimitry Andric 
40110b57cec5SDimitry Andric     llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
40120b57cec5SDimitry Andric     for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
40130b57cec5SDimitry Andric       // FIXME: we should use input files rather than storing names.
40140b57cec5SDimitry Andric       std::string Filename = ReadPath(F, Record, Idx);
4015fe6060f1SDimitry Andric       auto SF = FileMgr.getFile(Filename, false, false);
4016fe6060f1SDimitry Andric       if (!SF) {
4017fe6060f1SDimitry Andric         if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
40180b57cec5SDimitry Andric           Error("could not find file '" + Filename +"' referenced by AST file");
40190b57cec5SDimitry Andric         return OutOfDate;
40200b57cec5SDimitry Andric       }
4021fe6060f1SDimitry Andric       AdditionalStoredMaps.insert(*SF);
40220b57cec5SDimitry Andric     }
40230b57cec5SDimitry Andric 
40240b57cec5SDimitry Andric     // Check any additional module map files (e.g. module.private.modulemap)
40250b57cec5SDimitry Andric     // that are not in the pcm.
40260b57cec5SDimitry Andric     if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
40270b57cec5SDimitry Andric       for (const FileEntry *ModMap : *AdditionalModuleMaps) {
40280b57cec5SDimitry Andric         // Remove files that match
40290b57cec5SDimitry Andric         // Note: SmallPtrSet::erase is really remove
40300b57cec5SDimitry Andric         if (!AdditionalStoredMaps.erase(ModMap)) {
4031fe6060f1SDimitry Andric           if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
40320b57cec5SDimitry Andric             Diag(diag::err_module_different_modmap)
40330b57cec5SDimitry Andric               << F.ModuleName << /*new*/0 << ModMap->getName();
40340b57cec5SDimitry Andric           return OutOfDate;
40350b57cec5SDimitry Andric         }
40360b57cec5SDimitry Andric       }
40370b57cec5SDimitry Andric     }
40380b57cec5SDimitry Andric 
40390b57cec5SDimitry Andric     // Check any additional module map files that are in the pcm, but not
40400b57cec5SDimitry Andric     // found in header search. Cases that match are already removed.
40410b57cec5SDimitry Andric     for (const FileEntry *ModMap : AdditionalStoredMaps) {
4042fe6060f1SDimitry Andric       if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
40430b57cec5SDimitry Andric         Diag(diag::err_module_different_modmap)
40440b57cec5SDimitry Andric           << F.ModuleName << /*not new*/1 << ModMap->getName();
40450b57cec5SDimitry Andric       return OutOfDate;
40460b57cec5SDimitry Andric     }
40470b57cec5SDimitry Andric   }
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric   if (Listener)
40500b57cec5SDimitry Andric     Listener->ReadModuleMapFile(F.ModuleMapPath);
40510b57cec5SDimitry Andric   return Success;
40520b57cec5SDimitry Andric }
40530b57cec5SDimitry Andric 
40540b57cec5SDimitry Andric /// Move the given method to the back of the global list of methods.
40550b57cec5SDimitry Andric static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
40560b57cec5SDimitry Andric   // Find the entry for this selector in the method pool.
40570b57cec5SDimitry Andric   Sema::GlobalMethodPool::iterator Known
40580b57cec5SDimitry Andric     = S.MethodPool.find(Method->getSelector());
40590b57cec5SDimitry Andric   if (Known == S.MethodPool.end())
40600b57cec5SDimitry Andric     return;
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric   // Retrieve the appropriate method list.
40630b57cec5SDimitry Andric   ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
40640b57cec5SDimitry Andric                                                     : Known->second.second;
40650b57cec5SDimitry Andric   bool Found = false;
40660b57cec5SDimitry Andric   for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
40670b57cec5SDimitry Andric     if (!Found) {
40680b57cec5SDimitry Andric       if (List->getMethod() == Method) {
40690b57cec5SDimitry Andric         Found = true;
40700b57cec5SDimitry Andric       } else {
40710b57cec5SDimitry Andric         // Keep searching.
40720b57cec5SDimitry Andric         continue;
40730b57cec5SDimitry Andric       }
40740b57cec5SDimitry Andric     }
40750b57cec5SDimitry Andric 
40760b57cec5SDimitry Andric     if (List->getNext())
40770b57cec5SDimitry Andric       List->setMethod(List->getNext()->getMethod());
40780b57cec5SDimitry Andric     else
40790b57cec5SDimitry Andric       List->setMethod(Method);
40800b57cec5SDimitry Andric   }
40810b57cec5SDimitry Andric }
40820b57cec5SDimitry Andric 
40830b57cec5SDimitry Andric void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
40840b57cec5SDimitry Andric   assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
40850b57cec5SDimitry Andric   for (Decl *D : Names) {
40865ffd83dbSDimitry Andric     bool wasHidden = !D->isUnconditionallyVisible();
40870b57cec5SDimitry Andric     D->setVisibleDespiteOwningModule();
40880b57cec5SDimitry Andric 
40890b57cec5SDimitry Andric     if (wasHidden && SemaObj) {
40900b57cec5SDimitry Andric       if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
40910b57cec5SDimitry Andric         moveMethodToBackOfGlobalList(*SemaObj, Method);
40920b57cec5SDimitry Andric       }
40930b57cec5SDimitry Andric     }
40940b57cec5SDimitry Andric   }
40950b57cec5SDimitry Andric }
40960b57cec5SDimitry Andric 
40970b57cec5SDimitry Andric void ASTReader::makeModuleVisible(Module *Mod,
40980b57cec5SDimitry Andric                                   Module::NameVisibilityKind NameVisibility,
40990b57cec5SDimitry Andric                                   SourceLocation ImportLoc) {
41000b57cec5SDimitry Andric   llvm::SmallPtrSet<Module *, 4> Visited;
41010b57cec5SDimitry Andric   SmallVector<Module *, 4> Stack;
41020b57cec5SDimitry Andric   Stack.push_back(Mod);
41030b57cec5SDimitry Andric   while (!Stack.empty()) {
41040b57cec5SDimitry Andric     Mod = Stack.pop_back_val();
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric     if (NameVisibility <= Mod->NameVisibility) {
41070b57cec5SDimitry Andric       // This module already has this level of visibility (or greater), so
41080b57cec5SDimitry Andric       // there is nothing more to do.
41090b57cec5SDimitry Andric       continue;
41100b57cec5SDimitry Andric     }
41110b57cec5SDimitry Andric 
41125ffd83dbSDimitry Andric     if (Mod->isUnimportable()) {
41135ffd83dbSDimitry Andric       // Modules that aren't importable cannot be made visible.
41140b57cec5SDimitry Andric       continue;
41150b57cec5SDimitry Andric     }
41160b57cec5SDimitry Andric 
41170b57cec5SDimitry Andric     // Update the module's name visibility.
41180b57cec5SDimitry Andric     Mod->NameVisibility = NameVisibility;
41190b57cec5SDimitry Andric 
41200b57cec5SDimitry Andric     // If we've already deserialized any names from this module,
41210b57cec5SDimitry Andric     // mark them as visible.
41220b57cec5SDimitry Andric     HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
41230b57cec5SDimitry Andric     if (Hidden != HiddenNamesMap.end()) {
41240b57cec5SDimitry Andric       auto HiddenNames = std::move(*Hidden);
41250b57cec5SDimitry Andric       HiddenNamesMap.erase(Hidden);
41260b57cec5SDimitry Andric       makeNamesVisible(HiddenNames.second, HiddenNames.first);
41270b57cec5SDimitry Andric       assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
41280b57cec5SDimitry Andric              "making names visible added hidden names");
41290b57cec5SDimitry Andric     }
41300b57cec5SDimitry Andric 
41310b57cec5SDimitry Andric     // Push any exported modules onto the stack to be marked as visible.
41320b57cec5SDimitry Andric     SmallVector<Module *, 16> Exports;
41330b57cec5SDimitry Andric     Mod->getExportedModules(Exports);
41340b57cec5SDimitry Andric     for (SmallVectorImpl<Module *>::iterator
41350b57cec5SDimitry Andric            I = Exports.begin(), E = Exports.end(); I != E; ++I) {
41360b57cec5SDimitry Andric       Module *Exported = *I;
41370b57cec5SDimitry Andric       if (Visited.insert(Exported).second)
41380b57cec5SDimitry Andric         Stack.push_back(Exported);
41390b57cec5SDimitry Andric     }
41400b57cec5SDimitry Andric   }
41410b57cec5SDimitry Andric }
41420b57cec5SDimitry Andric 
41430b57cec5SDimitry Andric /// We've merged the definition \p MergedDef into the existing definition
41440b57cec5SDimitry Andric /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
41450b57cec5SDimitry Andric /// visible.
41460b57cec5SDimitry Andric void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
41470b57cec5SDimitry Andric                                           NamedDecl *MergedDef) {
41485ffd83dbSDimitry Andric   if (!Def->isUnconditionallyVisible()) {
41490b57cec5SDimitry Andric     // If MergedDef is visible or becomes visible, make the definition visible.
41505ffd83dbSDimitry Andric     if (MergedDef->isUnconditionallyVisible())
41510b57cec5SDimitry Andric       Def->setVisibleDespiteOwningModule();
41520b57cec5SDimitry Andric     else {
41530b57cec5SDimitry Andric       getContext().mergeDefinitionIntoModule(
41540b57cec5SDimitry Andric           Def, MergedDef->getImportedOwningModule(),
41550b57cec5SDimitry Andric           /*NotifyListeners*/ false);
41560b57cec5SDimitry Andric       PendingMergedDefinitionsToDeduplicate.insert(Def);
41570b57cec5SDimitry Andric     }
41580b57cec5SDimitry Andric   }
41590b57cec5SDimitry Andric }
41600b57cec5SDimitry Andric 
41610b57cec5SDimitry Andric bool ASTReader::loadGlobalIndex() {
41620b57cec5SDimitry Andric   if (GlobalIndex)
41630b57cec5SDimitry Andric     return false;
41640b57cec5SDimitry Andric 
41650b57cec5SDimitry Andric   if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
41660b57cec5SDimitry Andric       !PP.getLangOpts().Modules)
41670b57cec5SDimitry Andric     return true;
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric   // Try to load the global index.
41700b57cec5SDimitry Andric   TriedLoadingGlobalIndex = true;
41710b57cec5SDimitry Andric   StringRef ModuleCachePath
41720b57cec5SDimitry Andric     = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
41730b57cec5SDimitry Andric   std::pair<GlobalModuleIndex *, llvm::Error> Result =
41740b57cec5SDimitry Andric       GlobalModuleIndex::readIndex(ModuleCachePath);
41750b57cec5SDimitry Andric   if (llvm::Error Err = std::move(Result.second)) {
41760b57cec5SDimitry Andric     assert(!Result.first);
41770b57cec5SDimitry Andric     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
41780b57cec5SDimitry Andric     return true;
41790b57cec5SDimitry Andric   }
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric   GlobalIndex.reset(Result.first);
41820b57cec5SDimitry Andric   ModuleMgr.setGlobalIndex(GlobalIndex.get());
41830b57cec5SDimitry Andric   return false;
41840b57cec5SDimitry Andric }
41850b57cec5SDimitry Andric 
41860b57cec5SDimitry Andric bool ASTReader::isGlobalIndexUnavailable() const {
41870b57cec5SDimitry Andric   return PP.getLangOpts().Modules && UseGlobalIndex &&
41880b57cec5SDimitry Andric          !hasGlobalIndex() && TriedLoadingGlobalIndex;
41890b57cec5SDimitry Andric }
41900b57cec5SDimitry Andric 
41910b57cec5SDimitry Andric static void updateModuleTimestamp(ModuleFile &MF) {
41920b57cec5SDimitry Andric   // Overwrite the timestamp file contents so that file's mtime changes.
41930b57cec5SDimitry Andric   std::string TimestampFilename = MF.getTimestampFilename();
41940b57cec5SDimitry Andric   std::error_code EC;
4195fe6060f1SDimitry Andric   llvm::raw_fd_ostream OS(TimestampFilename, EC,
4196fe6060f1SDimitry Andric                           llvm::sys::fs::OF_TextWithCRLF);
41970b57cec5SDimitry Andric   if (EC)
41980b57cec5SDimitry Andric     return;
41990b57cec5SDimitry Andric   OS << "Timestamp file\n";
42000b57cec5SDimitry Andric   OS.close();
42010b57cec5SDimitry Andric   OS.clear_error(); // Avoid triggering a fatal error.
42020b57cec5SDimitry Andric }
42030b57cec5SDimitry Andric 
42040b57cec5SDimitry Andric /// Given a cursor at the start of an AST file, scan ahead and drop the
42050b57cec5SDimitry Andric /// cursor into the start of the given block ID, returning false on success and
42060b57cec5SDimitry Andric /// true on failure.
42070b57cec5SDimitry Andric static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
42080b57cec5SDimitry Andric   while (true) {
42090b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
42100b57cec5SDimitry Andric     if (!MaybeEntry) {
42110b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
42120b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
42130b57cec5SDimitry Andric       return true;
42140b57cec5SDimitry Andric     }
42150b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
42160b57cec5SDimitry Andric 
42170b57cec5SDimitry Andric     switch (Entry.Kind) {
42180b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
42190b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
42200b57cec5SDimitry Andric       return true;
42210b57cec5SDimitry Andric 
42220b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
42230b57cec5SDimitry Andric       // Ignore top-level records.
42240b57cec5SDimitry Andric       if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
42250b57cec5SDimitry Andric         break;
42260b57cec5SDimitry Andric       else {
42270b57cec5SDimitry Andric         // FIXME this drops errors on the floor.
42280b57cec5SDimitry Andric         consumeError(Skipped.takeError());
42290b57cec5SDimitry Andric         return true;
42300b57cec5SDimitry Andric       }
42310b57cec5SDimitry Andric 
42320b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
42330b57cec5SDimitry Andric       if (Entry.ID == BlockID) {
42340b57cec5SDimitry Andric         if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
42350b57cec5SDimitry Andric           // FIXME this drops the error on the floor.
42360b57cec5SDimitry Andric           consumeError(std::move(Err));
42370b57cec5SDimitry Andric           return true;
42380b57cec5SDimitry Andric         }
42390b57cec5SDimitry Andric         // Found it!
42400b57cec5SDimitry Andric         return false;
42410b57cec5SDimitry Andric       }
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric       if (llvm::Error Err = Cursor.SkipBlock()) {
42440b57cec5SDimitry Andric         // FIXME this drops the error on the floor.
42450b57cec5SDimitry Andric         consumeError(std::move(Err));
42460b57cec5SDimitry Andric         return true;
42470b57cec5SDimitry Andric       }
42480b57cec5SDimitry Andric     }
42490b57cec5SDimitry Andric   }
42500b57cec5SDimitry Andric }
42510b57cec5SDimitry Andric 
42520b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
42530b57cec5SDimitry Andric                                             ModuleKind Type,
42540b57cec5SDimitry Andric                                             SourceLocation ImportLoc,
42550b57cec5SDimitry Andric                                             unsigned ClientLoadCapabilities,
42560b57cec5SDimitry Andric                                             SmallVectorImpl<ImportedSubmodule> *Imported) {
4257*bdd1243dSDimitry Andric   llvm::TimeTraceScope scope("ReadAST", FileName);
4258*bdd1243dSDimitry Andric 
4259*bdd1243dSDimitry Andric   llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4260*bdd1243dSDimitry Andric   llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
4261e8d8bef9SDimitry Andric       CurrentDeserializingModuleKind, Type);
42620b57cec5SDimitry Andric 
42630b57cec5SDimitry Andric   // Defer any pending actions until we get to the end of reading the AST file.
42640b57cec5SDimitry Andric   Deserializing AnASTFile(this);
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric   // Bump the generation number.
42670b57cec5SDimitry Andric   unsigned PreviousGeneration = 0;
42680b57cec5SDimitry Andric   if (ContextObj)
42690b57cec5SDimitry Andric     PreviousGeneration = incrementGeneration(*ContextObj);
42700b57cec5SDimitry Andric 
42710b57cec5SDimitry Andric   unsigned NumModules = ModuleMgr.size();
4272349cc55cSDimitry Andric   SmallVector<ImportedModule, 4> Loaded;
4273349cc55cSDimitry Andric   if (ASTReadResult ReadResult =
4274349cc55cSDimitry Andric           ReadASTCore(FileName, Type, ImportLoc,
4275349cc55cSDimitry Andric                       /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
4276349cc55cSDimitry Andric                       ClientLoadCapabilities)) {
4277*bdd1243dSDimitry Andric     ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
4278480093f4SDimitry Andric 
4279480093f4SDimitry Andric     // If we find that any modules are unusable, the global index is going
4280480093f4SDimitry Andric     // to be out-of-date. Just remove it.
4281480093f4SDimitry Andric     GlobalIndex.reset();
4282480093f4SDimitry Andric     ModuleMgr.setGlobalIndex(nullptr);
4283480093f4SDimitry Andric     return ReadResult;
42840b57cec5SDimitry Andric   }
42850b57cec5SDimitry Andric 
4286349cc55cSDimitry Andric   // Here comes stuff that we only do once the entire chain is loaded. Do *not*
4287349cc55cSDimitry Andric   // remove modules from this point. Various fields are updated during reading
4288349cc55cSDimitry Andric   // the AST block and removing the modules would result in dangling pointers.
4289349cc55cSDimitry Andric   // They are generally only incidentally dereferenced, ie. a binary search
4290349cc55cSDimitry Andric   // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
4291349cc55cSDimitry Andric   // be dereferenced but it wouldn't actually be used.
42920b57cec5SDimitry Andric 
4293480093f4SDimitry Andric   // Load the AST blocks of all of the modules that we loaded. We can still
4294480093f4SDimitry Andric   // hit errors parsing the ASTs at this point.
4295480093f4SDimitry Andric   for (ImportedModule &M : Loaded) {
4296480093f4SDimitry Andric     ModuleFile &F = *M.Mod;
4297*bdd1243dSDimitry Andric     llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
42980b57cec5SDimitry Andric 
42990b57cec5SDimitry Andric     // Read the AST block.
4300349cc55cSDimitry Andric     if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
4301349cc55cSDimitry Andric       Error(std::move(Err));
4302349cc55cSDimitry Andric       return Failure;
4303349cc55cSDimitry Andric     }
4304480093f4SDimitry Andric 
4305480093f4SDimitry Andric     // The AST block should always have a definition for the main module.
4306480093f4SDimitry Andric     if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4307480093f4SDimitry Andric       Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4308349cc55cSDimitry Andric       return Failure;
4309480093f4SDimitry Andric     }
43100b57cec5SDimitry Andric 
43110b57cec5SDimitry Andric     // Read the extension blocks.
43120b57cec5SDimitry Andric     while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4313349cc55cSDimitry Andric       if (llvm::Error Err = ReadExtensionBlock(F)) {
4314349cc55cSDimitry Andric         Error(std::move(Err));
4315349cc55cSDimitry Andric         return Failure;
4316349cc55cSDimitry Andric       }
43170b57cec5SDimitry Andric     }
43180b57cec5SDimitry Andric 
43190b57cec5SDimitry Andric     // Once read, set the ModuleFile bit base offset and update the size in
43200b57cec5SDimitry Andric     // bits of all files we've seen.
43210b57cec5SDimitry Andric     F.GlobalBitOffset = TotalModulesSizeInBits;
43220b57cec5SDimitry Andric     TotalModulesSizeInBits += F.SizeInBits;
43230b57cec5SDimitry Andric     GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
4324480093f4SDimitry Andric   }
4325480093f4SDimitry Andric 
4326480093f4SDimitry Andric   // Preload source locations and interesting indentifiers.
4327480093f4SDimitry Andric   for (ImportedModule &M : Loaded) {
4328480093f4SDimitry Andric     ModuleFile &F = *M.Mod;
43290b57cec5SDimitry Andric 
43300b57cec5SDimitry Andric     // Preload SLocEntries.
43310b57cec5SDimitry Andric     for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
43320b57cec5SDimitry Andric       int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
43330b57cec5SDimitry Andric       // Load it through the SourceManager and don't call ReadSLocEntry()
43340b57cec5SDimitry Andric       // directly because the entry may have already been loaded in which case
43350b57cec5SDimitry Andric       // calling ReadSLocEntry() directly would trigger an assertion in
43360b57cec5SDimitry Andric       // SourceManager.
43370b57cec5SDimitry Andric       SourceMgr.getLoadedSLocEntryByID(Index);
43380b57cec5SDimitry Andric     }
43390b57cec5SDimitry Andric 
43400b57cec5SDimitry Andric     // Map the original source file ID into the ID space of the current
43410b57cec5SDimitry Andric     // compilation.
4342*bdd1243dSDimitry Andric     if (F.OriginalSourceFileID.isValid())
4343*bdd1243dSDimitry Andric       F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
43440b57cec5SDimitry Andric 
43450b57cec5SDimitry Andric     // Preload all the pending interesting identifiers by marking them out of
43460b57cec5SDimitry Andric     // date.
43470b57cec5SDimitry Andric     for (auto Offset : F.PreloadIdentifierOffsets) {
4348fe6060f1SDimitry Andric       const unsigned char *Data = F.IdentifierTableData + Offset;
43490b57cec5SDimitry Andric 
43500b57cec5SDimitry Andric       ASTIdentifierLookupTrait Trait(*this, F);
43510b57cec5SDimitry Andric       auto KeyDataLen = Trait.ReadKeyDataLength(Data);
43520b57cec5SDimitry Andric       auto Key = Trait.ReadKey(Data, KeyDataLen.first);
43530b57cec5SDimitry Andric       auto &II = PP.getIdentifierTable().getOwn(Key);
43540b57cec5SDimitry Andric       II.setOutOfDate(true);
43550b57cec5SDimitry Andric 
43560b57cec5SDimitry Andric       // Mark this identifier as being from an AST file so that we can track
43570b57cec5SDimitry Andric       // whether we need to serialize it.
43580b57cec5SDimitry Andric       markIdentifierFromAST(*this, II);
43590b57cec5SDimitry Andric 
43600b57cec5SDimitry Andric       // Associate the ID with the identifier so that the writer can reuse it.
43610b57cec5SDimitry Andric       auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
43620b57cec5SDimitry Andric       SetIdentifierInfo(ID, &II);
43630b57cec5SDimitry Andric     }
43640b57cec5SDimitry Andric   }
43650b57cec5SDimitry Andric 
43660b57cec5SDimitry Andric   // Setup the import locations and notify the module manager that we've
43670b57cec5SDimitry Andric   // committed to these module files.
4368480093f4SDimitry Andric   for (ImportedModule &M : Loaded) {
4369480093f4SDimitry Andric     ModuleFile &F = *M.Mod;
43700b57cec5SDimitry Andric 
43710b57cec5SDimitry Andric     ModuleMgr.moduleFileAccepted(&F);
43720b57cec5SDimitry Andric 
43730b57cec5SDimitry Andric     // Set the import location.
43740b57cec5SDimitry Andric     F.DirectImportLoc = ImportLoc;
43750b57cec5SDimitry Andric     // FIXME: We assume that locations from PCH / preamble do not need
43760b57cec5SDimitry Andric     // any translation.
4377480093f4SDimitry Andric     if (!M.ImportedBy)
4378480093f4SDimitry Andric       F.ImportLoc = M.ImportLoc;
43790b57cec5SDimitry Andric     else
4380480093f4SDimitry Andric       F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
43810b57cec5SDimitry Andric   }
43820b57cec5SDimitry Andric 
43830b57cec5SDimitry Andric   if (!PP.getLangOpts().CPlusPlus ||
43840b57cec5SDimitry Andric       (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
43850b57cec5SDimitry Andric        Type != MK_PrebuiltModule)) {
43860b57cec5SDimitry Andric     // Mark all of the identifiers in the identifier table as being out of date,
43870b57cec5SDimitry Andric     // so that various accessors know to check the loaded modules when the
43880b57cec5SDimitry Andric     // identifier is used.
43890b57cec5SDimitry Andric     //
43900b57cec5SDimitry Andric     // For C++ modules, we don't need information on many identifiers (just
43910b57cec5SDimitry Andric     // those that provide macros or are poisoned), so we mark all of
43920b57cec5SDimitry Andric     // the interesting ones via PreloadIdentifierOffsets.
43930b57cec5SDimitry Andric     for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
43940b57cec5SDimitry Andric                                 IdEnd = PP.getIdentifierTable().end();
43950b57cec5SDimitry Andric          Id != IdEnd; ++Id)
43960b57cec5SDimitry Andric       Id->second->setOutOfDate(true);
43970b57cec5SDimitry Andric   }
43980b57cec5SDimitry Andric   // Mark selectors as out of date.
43990b57cec5SDimitry Andric   for (auto Sel : SelectorGeneration)
44000b57cec5SDimitry Andric     SelectorOutOfDate[Sel.first] = true;
44010b57cec5SDimitry Andric 
44020b57cec5SDimitry Andric   // Resolve any unresolved module exports.
44030b57cec5SDimitry Andric   for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
44040b57cec5SDimitry Andric     UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
44050b57cec5SDimitry Andric     SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
44060b57cec5SDimitry Andric     Module *ResolvedMod = getSubmodule(GlobalID);
44070b57cec5SDimitry Andric 
44080b57cec5SDimitry Andric     switch (Unresolved.Kind) {
44090b57cec5SDimitry Andric     case UnresolvedModuleRef::Conflict:
44100b57cec5SDimitry Andric       if (ResolvedMod) {
44110b57cec5SDimitry Andric         Module::Conflict Conflict;
44120b57cec5SDimitry Andric         Conflict.Other = ResolvedMod;
44130b57cec5SDimitry Andric         Conflict.Message = Unresolved.String.str();
44140b57cec5SDimitry Andric         Unresolved.Mod->Conflicts.push_back(Conflict);
44150b57cec5SDimitry Andric       }
44160b57cec5SDimitry Andric       continue;
44170b57cec5SDimitry Andric 
44180b57cec5SDimitry Andric     case UnresolvedModuleRef::Import:
44190b57cec5SDimitry Andric       if (ResolvedMod)
44200b57cec5SDimitry Andric         Unresolved.Mod->Imports.insert(ResolvedMod);
44210b57cec5SDimitry Andric       continue;
44220b57cec5SDimitry Andric 
4423*bdd1243dSDimitry Andric     case UnresolvedModuleRef::Affecting:
4424*bdd1243dSDimitry Andric       if (ResolvedMod)
4425*bdd1243dSDimitry Andric         Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
4426*bdd1243dSDimitry Andric       continue;
4427*bdd1243dSDimitry Andric 
44280b57cec5SDimitry Andric     case UnresolvedModuleRef::Export:
44290b57cec5SDimitry Andric       if (ResolvedMod || Unresolved.IsWildcard)
44300b57cec5SDimitry Andric         Unresolved.Mod->Exports.push_back(
44310b57cec5SDimitry Andric           Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
44320b57cec5SDimitry Andric       continue;
44330b57cec5SDimitry Andric     }
44340b57cec5SDimitry Andric   }
44350b57cec5SDimitry Andric   UnresolvedModuleRefs.clear();
44360b57cec5SDimitry Andric 
44370b57cec5SDimitry Andric   if (Imported)
44380b57cec5SDimitry Andric     Imported->append(ImportedModules.begin(),
44390b57cec5SDimitry Andric                      ImportedModules.end());
44400b57cec5SDimitry Andric 
44410b57cec5SDimitry Andric   // FIXME: How do we load the 'use'd modules? They may not be submodules.
44420b57cec5SDimitry Andric   // Might be unnecessary as use declarations are only used to build the
44430b57cec5SDimitry Andric   // module itself.
44440b57cec5SDimitry Andric 
44450b57cec5SDimitry Andric   if (ContextObj)
44460b57cec5SDimitry Andric     InitializeContext();
44470b57cec5SDimitry Andric 
44480b57cec5SDimitry Andric   if (SemaObj)
44490b57cec5SDimitry Andric     UpdateSema();
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric   if (DeserializationListener)
44520b57cec5SDimitry Andric     DeserializationListener->ReaderInitialized(this);
44530b57cec5SDimitry Andric 
44540b57cec5SDimitry Andric   ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
44550b57cec5SDimitry Andric   if (PrimaryModule.OriginalSourceFileID.isValid()) {
44560b57cec5SDimitry Andric     // If this AST file is a precompiled preamble, then set the
44570b57cec5SDimitry Andric     // preamble file ID of the source manager to the file source file
44580b57cec5SDimitry Andric     // from which the preamble was built.
44590b57cec5SDimitry Andric     if (Type == MK_Preamble) {
44600b57cec5SDimitry Andric       SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
44610b57cec5SDimitry Andric     } else if (Type == MK_MainFile) {
44620b57cec5SDimitry Andric       SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
44630b57cec5SDimitry Andric     }
44640b57cec5SDimitry Andric   }
44650b57cec5SDimitry Andric 
44660b57cec5SDimitry Andric   // For any Objective-C class definitions we have already loaded, make sure
44670b57cec5SDimitry Andric   // that we load any additional categories.
44680b57cec5SDimitry Andric   if (ContextObj) {
44690b57cec5SDimitry Andric     for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
44700b57cec5SDimitry Andric       loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
44710b57cec5SDimitry Andric                          ObjCClassesLoaded[I],
44720b57cec5SDimitry Andric                          PreviousGeneration);
44730b57cec5SDimitry Andric     }
44740b57cec5SDimitry Andric   }
44750b57cec5SDimitry Andric 
44760b57cec5SDimitry Andric   if (PP.getHeaderSearchInfo()
44770b57cec5SDimitry Andric           .getHeaderSearchOpts()
44780b57cec5SDimitry Andric           .ModulesValidateOncePerBuildSession) {
44790b57cec5SDimitry Andric     // Now we are certain that the module and all modules it depends on are
44800b57cec5SDimitry Andric     // up to date.  Create or update timestamp files for modules that are
44810b57cec5SDimitry Andric     // located in the module cache (not for PCH files that could be anywhere
44820b57cec5SDimitry Andric     // in the filesystem).
44830b57cec5SDimitry Andric     for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
44840b57cec5SDimitry Andric       ImportedModule &M = Loaded[I];
44850b57cec5SDimitry Andric       if (M.Mod->Kind == MK_ImplicitModule) {
44860b57cec5SDimitry Andric         updateModuleTimestamp(*M.Mod);
44870b57cec5SDimitry Andric       }
44880b57cec5SDimitry Andric     }
44890b57cec5SDimitry Andric   }
44900b57cec5SDimitry Andric 
44910b57cec5SDimitry Andric   return Success;
44920b57cec5SDimitry Andric }
44930b57cec5SDimitry Andric 
44940b57cec5SDimitry Andric static ASTFileSignature readASTFileSignature(StringRef PCH);
44950b57cec5SDimitry Andric 
44960b57cec5SDimitry Andric /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
44970b57cec5SDimitry Andric static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
44980b57cec5SDimitry Andric   // FIXME checking magic headers is done in other places such as
44990b57cec5SDimitry Andric   // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
45000b57cec5SDimitry Andric   // always done the same. Unify it all with a helper.
45010b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
45020b57cec5SDimitry Andric     return llvm::createStringError(std::errc::illegal_byte_sequence,
45030b57cec5SDimitry Andric                                    "file too small to contain AST file magic");
45040b57cec5SDimitry Andric   for (unsigned C : {'C', 'P', 'C', 'H'})
45050b57cec5SDimitry Andric     if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
45060b57cec5SDimitry Andric       if (Res.get() != C)
45070b57cec5SDimitry Andric         return llvm::createStringError(
45080b57cec5SDimitry Andric             std::errc::illegal_byte_sequence,
45090b57cec5SDimitry Andric             "file doesn't start with AST file magic");
45100b57cec5SDimitry Andric     } else
45110b57cec5SDimitry Andric       return Res.takeError();
45120b57cec5SDimitry Andric   return llvm::Error::success();
45130b57cec5SDimitry Andric }
45140b57cec5SDimitry Andric 
45150b57cec5SDimitry Andric static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
45160b57cec5SDimitry Andric   switch (Kind) {
45170b57cec5SDimitry Andric   case MK_PCH:
45180b57cec5SDimitry Andric     return 0; // PCH
45190b57cec5SDimitry Andric   case MK_ImplicitModule:
45200b57cec5SDimitry Andric   case MK_ExplicitModule:
45210b57cec5SDimitry Andric   case MK_PrebuiltModule:
45220b57cec5SDimitry Andric     return 1; // module
45230b57cec5SDimitry Andric   case MK_MainFile:
45240b57cec5SDimitry Andric   case MK_Preamble:
45250b57cec5SDimitry Andric     return 2; // main source file
45260b57cec5SDimitry Andric   }
45270b57cec5SDimitry Andric   llvm_unreachable("unknown module kind");
45280b57cec5SDimitry Andric }
45290b57cec5SDimitry Andric 
45300b57cec5SDimitry Andric ASTReader::ASTReadResult
45310b57cec5SDimitry Andric ASTReader::ReadASTCore(StringRef FileName,
45320b57cec5SDimitry Andric                        ModuleKind Type,
45330b57cec5SDimitry Andric                        SourceLocation ImportLoc,
45340b57cec5SDimitry Andric                        ModuleFile *ImportedBy,
45350b57cec5SDimitry Andric                        SmallVectorImpl<ImportedModule> &Loaded,
45360b57cec5SDimitry Andric                        off_t ExpectedSize, time_t ExpectedModTime,
45370b57cec5SDimitry Andric                        ASTFileSignature ExpectedSignature,
45380b57cec5SDimitry Andric                        unsigned ClientLoadCapabilities) {
45390b57cec5SDimitry Andric   ModuleFile *M;
45400b57cec5SDimitry Andric   std::string ErrorStr;
45410b57cec5SDimitry Andric   ModuleManager::AddModuleResult AddResult
45420b57cec5SDimitry Andric     = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
45430b57cec5SDimitry Andric                           getGeneration(), ExpectedSize, ExpectedModTime,
45440b57cec5SDimitry Andric                           ExpectedSignature, readASTFileSignature,
45450b57cec5SDimitry Andric                           M, ErrorStr);
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric   switch (AddResult) {
45480b57cec5SDimitry Andric   case ModuleManager::AlreadyLoaded:
45490b57cec5SDimitry Andric     Diag(diag::remark_module_import)
45500b57cec5SDimitry Andric         << M->ModuleName << M->FileName << (ImportedBy ? true : false)
45510b57cec5SDimitry Andric         << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
45520b57cec5SDimitry Andric     return Success;
45530b57cec5SDimitry Andric 
45540b57cec5SDimitry Andric   case ModuleManager::NewlyLoaded:
45550b57cec5SDimitry Andric     // Load module file below.
45560b57cec5SDimitry Andric     break;
45570b57cec5SDimitry Andric 
45580b57cec5SDimitry Andric   case ModuleManager::Missing:
45590b57cec5SDimitry Andric     // The module file was missing; if the client can handle that, return
45600b57cec5SDimitry Andric     // it.
45610b57cec5SDimitry Andric     if (ClientLoadCapabilities & ARR_Missing)
45620b57cec5SDimitry Andric       return Missing;
45630b57cec5SDimitry Andric 
45640b57cec5SDimitry Andric     // Otherwise, return an error.
4565e8d8bef9SDimitry Andric     Diag(diag::err_ast_file_not_found)
4566e8d8bef9SDimitry Andric         << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
45670b57cec5SDimitry Andric         << ErrorStr;
45680b57cec5SDimitry Andric     return Failure;
45690b57cec5SDimitry Andric 
45700b57cec5SDimitry Andric   case ModuleManager::OutOfDate:
45710b57cec5SDimitry Andric     // We couldn't load the module file because it is out-of-date. If the
45720b57cec5SDimitry Andric     // client can handle out-of-date, return it.
45730b57cec5SDimitry Andric     if (ClientLoadCapabilities & ARR_OutOfDate)
45740b57cec5SDimitry Andric       return OutOfDate;
45750b57cec5SDimitry Andric 
45760b57cec5SDimitry Andric     // Otherwise, return an error.
4577e8d8bef9SDimitry Andric     Diag(diag::err_ast_file_out_of_date)
4578e8d8bef9SDimitry Andric         << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
45790b57cec5SDimitry Andric         << ErrorStr;
45800b57cec5SDimitry Andric     return Failure;
45810b57cec5SDimitry Andric   }
45820b57cec5SDimitry Andric 
45830b57cec5SDimitry Andric   assert(M && "Missing module file");
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric   bool ShouldFinalizePCM = false;
45860b57cec5SDimitry Andric   auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
45870b57cec5SDimitry Andric     auto &MC = getModuleManager().getModuleCache();
45880b57cec5SDimitry Andric     if (ShouldFinalizePCM)
45890b57cec5SDimitry Andric       MC.finalizePCM(FileName);
45900b57cec5SDimitry Andric     else
45910b57cec5SDimitry Andric       MC.tryToDropPCM(FileName);
45920b57cec5SDimitry Andric   });
45930b57cec5SDimitry Andric   ModuleFile &F = *M;
45940b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
45950b57cec5SDimitry Andric   Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
45960b57cec5SDimitry Andric   F.SizeInBits = F.Buffer->getBufferSize() * 8;
45970b57cec5SDimitry Andric 
45980b57cec5SDimitry Andric   // Sniff for the signature.
45990b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4600e8d8bef9SDimitry Andric     Diag(diag::err_ast_file_invalid)
46010b57cec5SDimitry Andric         << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
46020b57cec5SDimitry Andric     return Failure;
46030b57cec5SDimitry Andric   }
46040b57cec5SDimitry Andric 
46050b57cec5SDimitry Andric   // This is used for compatibility with older PCH formats.
46060b57cec5SDimitry Andric   bool HaveReadControlBlock = false;
46070b57cec5SDimitry Andric   while (true) {
46080b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
46090b57cec5SDimitry Andric     if (!MaybeEntry) {
46100b57cec5SDimitry Andric       Error(MaybeEntry.takeError());
46110b57cec5SDimitry Andric       return Failure;
46120b57cec5SDimitry Andric     }
46130b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
46140b57cec5SDimitry Andric 
46150b57cec5SDimitry Andric     switch (Entry.Kind) {
46160b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
46170b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
46180b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
46190b57cec5SDimitry Andric       Error("invalid record at top-level of AST file");
46200b57cec5SDimitry Andric       return Failure;
46210b57cec5SDimitry Andric 
46220b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
46230b57cec5SDimitry Andric       break;
46240b57cec5SDimitry Andric     }
46250b57cec5SDimitry Andric 
46260b57cec5SDimitry Andric     switch (Entry.ID) {
46270b57cec5SDimitry Andric     case CONTROL_BLOCK_ID:
46280b57cec5SDimitry Andric       HaveReadControlBlock = true;
46290b57cec5SDimitry Andric       switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
46300b57cec5SDimitry Andric       case Success:
46310b57cec5SDimitry Andric         // Check that we didn't try to load a non-module AST file as a module.
46320b57cec5SDimitry Andric         //
46330b57cec5SDimitry Andric         // FIXME: Should we also perform the converse check? Loading a module as
46340b57cec5SDimitry Andric         // a PCH file sort of works, but it's a bit wonky.
46350b57cec5SDimitry Andric         if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
46360b57cec5SDimitry Andric              Type == MK_PrebuiltModule) &&
46370b57cec5SDimitry Andric             F.ModuleName.empty()) {
46380b57cec5SDimitry Andric           auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
46390b57cec5SDimitry Andric           if (Result != OutOfDate ||
46400b57cec5SDimitry Andric               (ClientLoadCapabilities & ARR_OutOfDate) == 0)
46410b57cec5SDimitry Andric             Diag(diag::err_module_file_not_module) << FileName;
46420b57cec5SDimitry Andric           return Result;
46430b57cec5SDimitry Andric         }
46440b57cec5SDimitry Andric         break;
46450b57cec5SDimitry Andric 
46460b57cec5SDimitry Andric       case Failure: return Failure;
46470b57cec5SDimitry Andric       case Missing: return Missing;
46480b57cec5SDimitry Andric       case OutOfDate: return OutOfDate;
46490b57cec5SDimitry Andric       case VersionMismatch: return VersionMismatch;
46500b57cec5SDimitry Andric       case ConfigurationMismatch: return ConfigurationMismatch;
46510b57cec5SDimitry Andric       case HadErrors: return HadErrors;
46520b57cec5SDimitry Andric       }
46530b57cec5SDimitry Andric       break;
46540b57cec5SDimitry Andric 
46550b57cec5SDimitry Andric     case AST_BLOCK_ID:
46560b57cec5SDimitry Andric       if (!HaveReadControlBlock) {
46570b57cec5SDimitry Andric         if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
46580b57cec5SDimitry Andric           Diag(diag::err_pch_version_too_old);
46590b57cec5SDimitry Andric         return VersionMismatch;
46600b57cec5SDimitry Andric       }
46610b57cec5SDimitry Andric 
46620b57cec5SDimitry Andric       // Record that we've loaded this module.
46630b57cec5SDimitry Andric       Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
46640b57cec5SDimitry Andric       ShouldFinalizePCM = true;
46650b57cec5SDimitry Andric       return Success;
46660b57cec5SDimitry Andric 
46670b57cec5SDimitry Andric     case UNHASHED_CONTROL_BLOCK_ID:
46680b57cec5SDimitry Andric       // This block is handled using look-ahead during ReadControlBlock.  We
46690b57cec5SDimitry Andric       // shouldn't get here!
46700b57cec5SDimitry Andric       Error("malformed block record in AST file");
46710b57cec5SDimitry Andric       return Failure;
46720b57cec5SDimitry Andric 
46730b57cec5SDimitry Andric     default:
46740b57cec5SDimitry Andric       if (llvm::Error Err = Stream.SkipBlock()) {
46750b57cec5SDimitry Andric         Error(std::move(Err));
46760b57cec5SDimitry Andric         return Failure;
46770b57cec5SDimitry Andric       }
46780b57cec5SDimitry Andric       break;
46790b57cec5SDimitry Andric     }
46800b57cec5SDimitry Andric   }
46810b57cec5SDimitry Andric 
46820b57cec5SDimitry Andric   llvm_unreachable("unexpected break; expected return");
46830b57cec5SDimitry Andric }
46840b57cec5SDimitry Andric 
46850b57cec5SDimitry Andric ASTReader::ASTReadResult
46860b57cec5SDimitry Andric ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
46870b57cec5SDimitry Andric                                     unsigned ClientLoadCapabilities) {
46880b57cec5SDimitry Andric   const HeaderSearchOptions &HSOpts =
46890b57cec5SDimitry Andric       PP.getHeaderSearchInfo().getHeaderSearchOpts();
46900b57cec5SDimitry Andric   bool AllowCompatibleConfigurationMismatch =
46910b57cec5SDimitry Andric       F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4692e8d8bef9SDimitry Andric   bool DisableValidation = shouldDisableValidationForFile(F);
46930b57cec5SDimitry Andric 
46940b57cec5SDimitry Andric   ASTReadResult Result = readUnhashedControlBlockImpl(
46950b57cec5SDimitry Andric       &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
46960b57cec5SDimitry Andric       Listener.get(),
46970b57cec5SDimitry Andric       WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
46980b57cec5SDimitry Andric 
46990b57cec5SDimitry Andric   // If F was directly imported by another module, it's implicitly validated by
47000b57cec5SDimitry Andric   // the importing module.
47010b57cec5SDimitry Andric   if (DisableValidation || WasImportedBy ||
47020b57cec5SDimitry Andric       (AllowConfigurationMismatch && Result == ConfigurationMismatch))
47030b57cec5SDimitry Andric     return Success;
47040b57cec5SDimitry Andric 
47050b57cec5SDimitry Andric   if (Result == Failure) {
47060b57cec5SDimitry Andric     Error("malformed block record in AST file");
47070b57cec5SDimitry Andric     return Failure;
47080b57cec5SDimitry Andric   }
47090b57cec5SDimitry Andric 
47100b57cec5SDimitry Andric   if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
47110b57cec5SDimitry Andric     // If this module has already been finalized in the ModuleCache, we're stuck
47120b57cec5SDimitry Andric     // with it; we can only load a single version of each module.
47130b57cec5SDimitry Andric     //
47140b57cec5SDimitry Andric     // This can happen when a module is imported in two contexts: in one, as a
47150b57cec5SDimitry Andric     // user module; in another, as a system module (due to an import from
47160b57cec5SDimitry Andric     // another module marked with the [system] flag).  It usually indicates a
47170b57cec5SDimitry Andric     // bug in the module map: this module should also be marked with [system].
47180b57cec5SDimitry Andric     //
47190b57cec5SDimitry Andric     // If -Wno-system-headers (the default), and the first import is as a
47200b57cec5SDimitry Andric     // system module, then validation will fail during the as-user import,
47210b57cec5SDimitry Andric     // since -Werror flags won't have been validated.  However, it's reasonable
47220b57cec5SDimitry Andric     // to treat this consistently as a system module.
47230b57cec5SDimitry Andric     //
47240b57cec5SDimitry Andric     // If -Wsystem-headers, the PCM on disk was built with
47250b57cec5SDimitry Andric     // -Wno-system-headers, and the first import is as a user module, then
47260b57cec5SDimitry Andric     // validation will fail during the as-system import since the PCM on disk
47270b57cec5SDimitry Andric     // doesn't guarantee that -Werror was respected.  However, the -Werror
47280b57cec5SDimitry Andric     // flags were checked during the initial as-user import.
47290b57cec5SDimitry Andric     if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
47300b57cec5SDimitry Andric       Diag(diag::warn_module_system_bit_conflict) << F.FileName;
47310b57cec5SDimitry Andric       return Success;
47320b57cec5SDimitry Andric     }
47330b57cec5SDimitry Andric   }
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric   return Result;
47360b57cec5SDimitry Andric }
47370b57cec5SDimitry Andric 
47380b57cec5SDimitry Andric ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
47390b57cec5SDimitry Andric     ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
47400b57cec5SDimitry Andric     bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
47410b57cec5SDimitry Andric     bool ValidateDiagnosticOptions) {
47420b57cec5SDimitry Andric   // Initialize a stream.
47430b57cec5SDimitry Andric   BitstreamCursor Stream(StreamData);
47440b57cec5SDimitry Andric 
47450b57cec5SDimitry Andric   // Sniff for the signature.
47460b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
47470b57cec5SDimitry Andric     // FIXME this drops the error on the floor.
47480b57cec5SDimitry Andric     consumeError(std::move(Err));
47490b57cec5SDimitry Andric     return Failure;
47500b57cec5SDimitry Andric   }
47510b57cec5SDimitry Andric 
47520b57cec5SDimitry Andric   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
47530b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
47540b57cec5SDimitry Andric     return Failure;
47550b57cec5SDimitry Andric 
47560b57cec5SDimitry Andric   // Read all of the records in the options block.
47570b57cec5SDimitry Andric   RecordData Record;
47580b57cec5SDimitry Andric   ASTReadResult Result = Success;
47590b57cec5SDimitry Andric   while (true) {
47600b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
47610b57cec5SDimitry Andric     if (!MaybeEntry) {
47620b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
47630b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
47640b57cec5SDimitry Andric       return Failure;
47650b57cec5SDimitry Andric     }
47660b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
47670b57cec5SDimitry Andric 
47680b57cec5SDimitry Andric     switch (Entry.Kind) {
47690b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
47700b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
47710b57cec5SDimitry Andric       return Failure;
47720b57cec5SDimitry Andric 
47730b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
47740b57cec5SDimitry Andric       return Result;
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
47770b57cec5SDimitry Andric       // The interesting case.
47780b57cec5SDimitry Andric       break;
47790b57cec5SDimitry Andric     }
47800b57cec5SDimitry Andric 
47810b57cec5SDimitry Andric     // Read and process a record.
47820b57cec5SDimitry Andric     Record.clear();
4783349cc55cSDimitry Andric     StringRef Blob;
4784349cc55cSDimitry Andric     Expected<unsigned> MaybeRecordType =
4785349cc55cSDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
47860b57cec5SDimitry Andric     if (!MaybeRecordType) {
47870b57cec5SDimitry Andric       // FIXME this drops the error.
47880b57cec5SDimitry Andric       return Failure;
47890b57cec5SDimitry Andric     }
47900b57cec5SDimitry Andric     switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
47910b57cec5SDimitry Andric     case SIGNATURE:
47920b57cec5SDimitry Andric       if (F)
47935ffd83dbSDimitry Andric         F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
47945ffd83dbSDimitry Andric       break;
47955ffd83dbSDimitry Andric     case AST_BLOCK_HASH:
47965ffd83dbSDimitry Andric       if (F)
47975ffd83dbSDimitry Andric         F->ASTBlockHash =
47985ffd83dbSDimitry Andric             ASTFileSignature::create(Record.begin(), Record.end());
47990b57cec5SDimitry Andric       break;
48000b57cec5SDimitry Andric     case DIAGNOSTIC_OPTIONS: {
48010b57cec5SDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
48020b57cec5SDimitry Andric       if (Listener && ValidateDiagnosticOptions &&
48030b57cec5SDimitry Andric           !AllowCompatibleConfigurationMismatch &&
48040b57cec5SDimitry Andric           ParseDiagnosticOptions(Record, Complain, *Listener))
48050b57cec5SDimitry Andric         Result = OutOfDate; // Don't return early.  Read the signature.
48060b57cec5SDimitry Andric       break;
48070b57cec5SDimitry Andric     }
4808*bdd1243dSDimitry Andric     case HEADER_SEARCH_PATHS: {
4809*bdd1243dSDimitry Andric       bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
4810*bdd1243dSDimitry Andric       if (!AllowCompatibleConfigurationMismatch &&
4811*bdd1243dSDimitry Andric           ParseHeaderSearchPaths(Record, Complain, *Listener))
4812*bdd1243dSDimitry Andric         Result = ConfigurationMismatch;
4813*bdd1243dSDimitry Andric       break;
4814*bdd1243dSDimitry Andric     }
48150b57cec5SDimitry Andric     case DIAG_PRAGMA_MAPPINGS:
48160b57cec5SDimitry Andric       if (!F)
48170b57cec5SDimitry Andric         break;
48180b57cec5SDimitry Andric       if (F->PragmaDiagMappings.empty())
48190b57cec5SDimitry Andric         F->PragmaDiagMappings.swap(Record);
48200b57cec5SDimitry Andric       else
48210b57cec5SDimitry Andric         F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
48220b57cec5SDimitry Andric                                      Record.begin(), Record.end());
48230b57cec5SDimitry Andric       break;
4824349cc55cSDimitry Andric     case HEADER_SEARCH_ENTRY_USAGE:
4825349cc55cSDimitry Andric       if (!F)
4826349cc55cSDimitry Andric         break;
4827349cc55cSDimitry Andric       unsigned Count = Record[0];
4828349cc55cSDimitry Andric       const char *Byte = Blob.data();
482904eeddc0SDimitry Andric       F->SearchPathUsage = llvm::BitVector(Count, false);
4830349cc55cSDimitry Andric       for (unsigned I = 0; I < Count; ++Byte)
4831349cc55cSDimitry Andric         for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
4832349cc55cSDimitry Andric           if (*Byte & (1 << Bit))
483304eeddc0SDimitry Andric             F->SearchPathUsage[I] = true;
4834349cc55cSDimitry Andric       break;
48350b57cec5SDimitry Andric     }
48360b57cec5SDimitry Andric   }
48370b57cec5SDimitry Andric }
48380b57cec5SDimitry Andric 
48390b57cec5SDimitry Andric /// Parse a record and blob containing module file extension metadata.
48400b57cec5SDimitry Andric static bool parseModuleFileExtensionMetadata(
48410b57cec5SDimitry Andric               const SmallVectorImpl<uint64_t> &Record,
48420b57cec5SDimitry Andric               StringRef Blob,
48430b57cec5SDimitry Andric               ModuleFileExtensionMetadata &Metadata) {
48440b57cec5SDimitry Andric   if (Record.size() < 4) return true;
48450b57cec5SDimitry Andric 
48460b57cec5SDimitry Andric   Metadata.MajorVersion = Record[0];
48470b57cec5SDimitry Andric   Metadata.MinorVersion = Record[1];
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric   unsigned BlockNameLen = Record[2];
48500b57cec5SDimitry Andric   unsigned UserInfoLen = Record[3];
48510b57cec5SDimitry Andric 
48520b57cec5SDimitry Andric   if (BlockNameLen + UserInfoLen > Blob.size()) return true;
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric   Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
48550b57cec5SDimitry Andric   Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
48560b57cec5SDimitry Andric                                   Blob.data() + BlockNameLen + UserInfoLen);
48570b57cec5SDimitry Andric   return false;
48580b57cec5SDimitry Andric }
48590b57cec5SDimitry Andric 
4860349cc55cSDimitry Andric llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
48610b57cec5SDimitry Andric   BitstreamCursor &Stream = F.Stream;
48620b57cec5SDimitry Andric 
48630b57cec5SDimitry Andric   RecordData Record;
48640b57cec5SDimitry Andric   while (true) {
48650b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4866349cc55cSDimitry Andric     if (!MaybeEntry)
4867349cc55cSDimitry Andric       return MaybeEntry.takeError();
48680b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
48690b57cec5SDimitry Andric 
48700b57cec5SDimitry Andric     switch (Entry.Kind) {
48710b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock:
4872349cc55cSDimitry Andric       if (llvm::Error Err = Stream.SkipBlock())
4873349cc55cSDimitry Andric         return Err;
48740b57cec5SDimitry Andric       continue;
48750b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
4876349cc55cSDimitry Andric       return llvm::Error::success();
48770b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
4878349cc55cSDimitry Andric       return llvm::createStringError(std::errc::illegal_byte_sequence,
4879349cc55cSDimitry Andric                                      "malformed block record in AST file");
48800b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
48810b57cec5SDimitry Andric       break;
48820b57cec5SDimitry Andric     }
48830b57cec5SDimitry Andric 
48840b57cec5SDimitry Andric     Record.clear();
48850b57cec5SDimitry Andric     StringRef Blob;
48860b57cec5SDimitry Andric     Expected<unsigned> MaybeRecCode =
48870b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
4888349cc55cSDimitry Andric     if (!MaybeRecCode)
4889349cc55cSDimitry Andric       return MaybeRecCode.takeError();
48900b57cec5SDimitry Andric     switch (MaybeRecCode.get()) {
48910b57cec5SDimitry Andric     case EXTENSION_METADATA: {
48920b57cec5SDimitry Andric       ModuleFileExtensionMetadata Metadata;
4893349cc55cSDimitry Andric       if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4894349cc55cSDimitry Andric         return llvm::createStringError(
4895349cc55cSDimitry Andric             std::errc::illegal_byte_sequence,
4896349cc55cSDimitry Andric             "malformed EXTENSION_METADATA in AST file");
48970b57cec5SDimitry Andric 
48980b57cec5SDimitry Andric       // Find a module file extension with this block name.
48990b57cec5SDimitry Andric       auto Known = ModuleFileExtensions.find(Metadata.BlockName);
49000b57cec5SDimitry Andric       if (Known == ModuleFileExtensions.end()) break;
49010b57cec5SDimitry Andric 
49020b57cec5SDimitry Andric       // Form a reader.
49030b57cec5SDimitry Andric       if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
49040b57cec5SDimitry Andric                                                              F, Stream)) {
49050b57cec5SDimitry Andric         F.ExtensionReaders.push_back(std::move(Reader));
49060b57cec5SDimitry Andric       }
49070b57cec5SDimitry Andric 
49080b57cec5SDimitry Andric       break;
49090b57cec5SDimitry Andric     }
49100b57cec5SDimitry Andric     }
49110b57cec5SDimitry Andric   }
49120b57cec5SDimitry Andric 
4913349cc55cSDimitry Andric   return llvm::Error::success();
49140b57cec5SDimitry Andric }
49150b57cec5SDimitry Andric 
49160b57cec5SDimitry Andric void ASTReader::InitializeContext() {
49170b57cec5SDimitry Andric   assert(ContextObj && "no context to initialize");
49180b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
49190b57cec5SDimitry Andric 
49200b57cec5SDimitry Andric   // If there's a listener, notify them that we "read" the translation unit.
49210b57cec5SDimitry Andric   if (DeserializationListener)
49220b57cec5SDimitry Andric     DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
49230b57cec5SDimitry Andric                                       Context.getTranslationUnitDecl());
49240b57cec5SDimitry Andric 
49250b57cec5SDimitry Andric   // FIXME: Find a better way to deal with collisions between these
49260b57cec5SDimitry Andric   // built-in types. Right now, we just ignore the problem.
49270b57cec5SDimitry Andric 
49280b57cec5SDimitry Andric   // Load the special types.
49290b57cec5SDimitry Andric   if (SpecialTypes.size() >= NumSpecialTypeIDs) {
49300b57cec5SDimitry Andric     if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
49310b57cec5SDimitry Andric       if (!Context.CFConstantStringTypeDecl)
49320b57cec5SDimitry Andric         Context.setCFConstantStringType(GetType(String));
49330b57cec5SDimitry Andric     }
49340b57cec5SDimitry Andric 
49350b57cec5SDimitry Andric     if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
49360b57cec5SDimitry Andric       QualType FileType = GetType(File);
49370b57cec5SDimitry Andric       if (FileType.isNull()) {
49380b57cec5SDimitry Andric         Error("FILE type is NULL");
49390b57cec5SDimitry Andric         return;
49400b57cec5SDimitry Andric       }
49410b57cec5SDimitry Andric 
49420b57cec5SDimitry Andric       if (!Context.FILEDecl) {
49430b57cec5SDimitry Andric         if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
49440b57cec5SDimitry Andric           Context.setFILEDecl(Typedef->getDecl());
49450b57cec5SDimitry Andric         else {
49460b57cec5SDimitry Andric           const TagType *Tag = FileType->getAs<TagType>();
49470b57cec5SDimitry Andric           if (!Tag) {
49480b57cec5SDimitry Andric             Error("Invalid FILE type in AST file");
49490b57cec5SDimitry Andric             return;
49500b57cec5SDimitry Andric           }
49510b57cec5SDimitry Andric           Context.setFILEDecl(Tag->getDecl());
49520b57cec5SDimitry Andric         }
49530b57cec5SDimitry Andric       }
49540b57cec5SDimitry Andric     }
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric     if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
49570b57cec5SDimitry Andric       QualType Jmp_bufType = GetType(Jmp_buf);
49580b57cec5SDimitry Andric       if (Jmp_bufType.isNull()) {
49590b57cec5SDimitry Andric         Error("jmp_buf type is NULL");
49600b57cec5SDimitry Andric         return;
49610b57cec5SDimitry Andric       }
49620b57cec5SDimitry Andric 
49630b57cec5SDimitry Andric       if (!Context.jmp_bufDecl) {
49640b57cec5SDimitry Andric         if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
49650b57cec5SDimitry Andric           Context.setjmp_bufDecl(Typedef->getDecl());
49660b57cec5SDimitry Andric         else {
49670b57cec5SDimitry Andric           const TagType *Tag = Jmp_bufType->getAs<TagType>();
49680b57cec5SDimitry Andric           if (!Tag) {
49690b57cec5SDimitry Andric             Error("Invalid jmp_buf type in AST file");
49700b57cec5SDimitry Andric             return;
49710b57cec5SDimitry Andric           }
49720b57cec5SDimitry Andric           Context.setjmp_bufDecl(Tag->getDecl());
49730b57cec5SDimitry Andric         }
49740b57cec5SDimitry Andric       }
49750b57cec5SDimitry Andric     }
49760b57cec5SDimitry Andric 
49770b57cec5SDimitry Andric     if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
49780b57cec5SDimitry Andric       QualType Sigjmp_bufType = GetType(Sigjmp_buf);
49790b57cec5SDimitry Andric       if (Sigjmp_bufType.isNull()) {
49800b57cec5SDimitry Andric         Error("sigjmp_buf type is NULL");
49810b57cec5SDimitry Andric         return;
49820b57cec5SDimitry Andric       }
49830b57cec5SDimitry Andric 
49840b57cec5SDimitry Andric       if (!Context.sigjmp_bufDecl) {
49850b57cec5SDimitry Andric         if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
49860b57cec5SDimitry Andric           Context.setsigjmp_bufDecl(Typedef->getDecl());
49870b57cec5SDimitry Andric         else {
49880b57cec5SDimitry Andric           const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
49890b57cec5SDimitry Andric           assert(Tag && "Invalid sigjmp_buf type in AST file");
49900b57cec5SDimitry Andric           Context.setsigjmp_bufDecl(Tag->getDecl());
49910b57cec5SDimitry Andric         }
49920b57cec5SDimitry Andric       }
49930b57cec5SDimitry Andric     }
49940b57cec5SDimitry Andric 
49950b57cec5SDimitry Andric     if (unsigned ObjCIdRedef
49960b57cec5SDimitry Andric           = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
49970b57cec5SDimitry Andric       if (Context.ObjCIdRedefinitionType.isNull())
49980b57cec5SDimitry Andric         Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
49990b57cec5SDimitry Andric     }
50000b57cec5SDimitry Andric 
50010b57cec5SDimitry Andric     if (unsigned ObjCClassRedef
50020b57cec5SDimitry Andric           = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
50030b57cec5SDimitry Andric       if (Context.ObjCClassRedefinitionType.isNull())
50040b57cec5SDimitry Andric         Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
50050b57cec5SDimitry Andric     }
50060b57cec5SDimitry Andric 
50070b57cec5SDimitry Andric     if (unsigned ObjCSelRedef
50080b57cec5SDimitry Andric           = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
50090b57cec5SDimitry Andric       if (Context.ObjCSelRedefinitionType.isNull())
50100b57cec5SDimitry Andric         Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
50110b57cec5SDimitry Andric     }
50120b57cec5SDimitry Andric 
50130b57cec5SDimitry Andric     if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
50140b57cec5SDimitry Andric       QualType Ucontext_tType = GetType(Ucontext_t);
50150b57cec5SDimitry Andric       if (Ucontext_tType.isNull()) {
50160b57cec5SDimitry Andric         Error("ucontext_t type is NULL");
50170b57cec5SDimitry Andric         return;
50180b57cec5SDimitry Andric       }
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric       if (!Context.ucontext_tDecl) {
50210b57cec5SDimitry Andric         if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
50220b57cec5SDimitry Andric           Context.setucontext_tDecl(Typedef->getDecl());
50230b57cec5SDimitry Andric         else {
50240b57cec5SDimitry Andric           const TagType *Tag = Ucontext_tType->getAs<TagType>();
50250b57cec5SDimitry Andric           assert(Tag && "Invalid ucontext_t type in AST file");
50260b57cec5SDimitry Andric           Context.setucontext_tDecl(Tag->getDecl());
50270b57cec5SDimitry Andric         }
50280b57cec5SDimitry Andric       }
50290b57cec5SDimitry Andric     }
50300b57cec5SDimitry Andric   }
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric   ReadPragmaDiagnosticMappings(Context.getDiagnostics());
50330b57cec5SDimitry Andric 
50340b57cec5SDimitry Andric   // If there were any CUDA special declarations, deserialize them.
50350b57cec5SDimitry Andric   if (!CUDASpecialDeclRefs.empty()) {
50360b57cec5SDimitry Andric     assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
50370b57cec5SDimitry Andric     Context.setcudaConfigureCallDecl(
50380b57cec5SDimitry Andric                            cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
50390b57cec5SDimitry Andric   }
50400b57cec5SDimitry Andric 
50410b57cec5SDimitry Andric   // Re-export any modules that were imported by a non-module AST file.
50420b57cec5SDimitry Andric   // FIXME: This does not make macro-only imports visible again.
50430b57cec5SDimitry Andric   for (auto &Import : ImportedModules) {
50440b57cec5SDimitry Andric     if (Module *Imported = getSubmodule(Import.ID)) {
50450b57cec5SDimitry Andric       makeModuleVisible(Imported, Module::AllVisible,
50460b57cec5SDimitry Andric                         /*ImportLoc=*/Import.ImportLoc);
50470b57cec5SDimitry Andric       if (Import.ImportLoc.isValid())
50480b57cec5SDimitry Andric         PP.makeModuleVisible(Imported, Import.ImportLoc);
5049e8d8bef9SDimitry Andric       // This updates visibility for Preprocessor only. For Sema, which can be
5050e8d8bef9SDimitry Andric       // nullptr here, we do the same later, in UpdateSema().
50510b57cec5SDimitry Andric     }
50520b57cec5SDimitry Andric   }
50530b57cec5SDimitry Andric }
50540b57cec5SDimitry Andric 
50550b57cec5SDimitry Andric void ASTReader::finalizeForWriting() {
50560b57cec5SDimitry Andric   // Nothing to do for now.
50570b57cec5SDimitry Andric }
50580b57cec5SDimitry Andric 
50590b57cec5SDimitry Andric /// Reads and return the signature record from \p PCH's control block, or
50600b57cec5SDimitry Andric /// else returns 0.
50610b57cec5SDimitry Andric static ASTFileSignature readASTFileSignature(StringRef PCH) {
50620b57cec5SDimitry Andric   BitstreamCursor Stream(PCH);
50630b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
50640b57cec5SDimitry Andric     // FIXME this drops the error on the floor.
50650b57cec5SDimitry Andric     consumeError(std::move(Err));
50660b57cec5SDimitry Andric     return ASTFileSignature();
50670b57cec5SDimitry Andric   }
50680b57cec5SDimitry Andric 
50690b57cec5SDimitry Andric   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
50700b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
50710b57cec5SDimitry Andric     return ASTFileSignature();
50720b57cec5SDimitry Andric 
50730b57cec5SDimitry Andric   // Scan for SIGNATURE inside the diagnostic options block.
50740b57cec5SDimitry Andric   ASTReader::RecordData Record;
50750b57cec5SDimitry Andric   while (true) {
50760b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
50770b57cec5SDimitry Andric         Stream.advanceSkippingSubblocks();
50780b57cec5SDimitry Andric     if (!MaybeEntry) {
50790b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
50800b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
50810b57cec5SDimitry Andric       return ASTFileSignature();
50820b57cec5SDimitry Andric     }
50830b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
50840b57cec5SDimitry Andric 
50850b57cec5SDimitry Andric     if (Entry.Kind != llvm::BitstreamEntry::Record)
50860b57cec5SDimitry Andric       return ASTFileSignature();
50870b57cec5SDimitry Andric 
50880b57cec5SDimitry Andric     Record.clear();
50890b57cec5SDimitry Andric     StringRef Blob;
50900b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
50910b57cec5SDimitry Andric     if (!MaybeRecord) {
50920b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
50930b57cec5SDimitry Andric       consumeError(MaybeRecord.takeError());
50940b57cec5SDimitry Andric       return ASTFileSignature();
50950b57cec5SDimitry Andric     }
50960b57cec5SDimitry Andric     if (SIGNATURE == MaybeRecord.get())
50975ffd83dbSDimitry Andric       return ASTFileSignature::create(Record.begin(),
50985ffd83dbSDimitry Andric                                       Record.begin() + ASTFileSignature::size);
50990b57cec5SDimitry Andric   }
51000b57cec5SDimitry Andric }
51010b57cec5SDimitry Andric 
51020b57cec5SDimitry Andric /// Retrieve the name of the original source file name
51030b57cec5SDimitry Andric /// directly from the AST file, without actually loading the AST
51040b57cec5SDimitry Andric /// file.
51050b57cec5SDimitry Andric std::string ASTReader::getOriginalSourceFile(
51060b57cec5SDimitry Andric     const std::string &ASTFileName, FileManager &FileMgr,
51070b57cec5SDimitry Andric     const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
51080b57cec5SDimitry Andric   // Open the AST file.
510981ad6265SDimitry Andric   auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
511081ad6265SDimitry Andric                                          /*RequiresNullTerminator=*/false);
51110b57cec5SDimitry Andric   if (!Buffer) {
51120b57cec5SDimitry Andric     Diags.Report(diag::err_fe_unable_to_read_pch_file)
51130b57cec5SDimitry Andric         << ASTFileName << Buffer.getError().message();
51140b57cec5SDimitry Andric     return std::string();
51150b57cec5SDimitry Andric   }
51160b57cec5SDimitry Andric 
51170b57cec5SDimitry Andric   // Initialize the stream
51180b57cec5SDimitry Andric   BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
51190b57cec5SDimitry Andric 
51200b57cec5SDimitry Andric   // Sniff for the signature.
51210b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
51220b57cec5SDimitry Andric     Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
51230b57cec5SDimitry Andric     return std::string();
51240b57cec5SDimitry Andric   }
51250b57cec5SDimitry Andric 
51260b57cec5SDimitry Andric   // Scan for the CONTROL_BLOCK_ID block.
51270b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
51280b57cec5SDimitry Andric     Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
51290b57cec5SDimitry Andric     return std::string();
51300b57cec5SDimitry Andric   }
51310b57cec5SDimitry Andric 
51320b57cec5SDimitry Andric   // Scan for ORIGINAL_FILE inside the control block.
51330b57cec5SDimitry Andric   RecordData Record;
51340b57cec5SDimitry Andric   while (true) {
51350b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
51360b57cec5SDimitry Andric         Stream.advanceSkippingSubblocks();
51370b57cec5SDimitry Andric     if (!MaybeEntry) {
51380b57cec5SDimitry Andric       // FIXME this drops errors on the floor.
51390b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
51400b57cec5SDimitry Andric       return std::string();
51410b57cec5SDimitry Andric     }
51420b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric     if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
51450b57cec5SDimitry Andric       return std::string();
51460b57cec5SDimitry Andric 
51470b57cec5SDimitry Andric     if (Entry.Kind != llvm::BitstreamEntry::Record) {
51480b57cec5SDimitry Andric       Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
51490b57cec5SDimitry Andric       return std::string();
51500b57cec5SDimitry Andric     }
51510b57cec5SDimitry Andric 
51520b57cec5SDimitry Andric     Record.clear();
51530b57cec5SDimitry Andric     StringRef Blob;
51540b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
51550b57cec5SDimitry Andric     if (!MaybeRecord) {
51560b57cec5SDimitry Andric       // FIXME this drops the errors on the floor.
51570b57cec5SDimitry Andric       consumeError(MaybeRecord.takeError());
51580b57cec5SDimitry Andric       return std::string();
51590b57cec5SDimitry Andric     }
51600b57cec5SDimitry Andric     if (ORIGINAL_FILE == MaybeRecord.get())
51610b57cec5SDimitry Andric       return Blob.str();
51620b57cec5SDimitry Andric   }
51630b57cec5SDimitry Andric }
51640b57cec5SDimitry Andric 
51650b57cec5SDimitry Andric namespace {
51660b57cec5SDimitry Andric 
51670b57cec5SDimitry Andric   class SimplePCHValidator : public ASTReaderListener {
51680b57cec5SDimitry Andric     const LangOptions &ExistingLangOpts;
51690b57cec5SDimitry Andric     const TargetOptions &ExistingTargetOpts;
51700b57cec5SDimitry Andric     const PreprocessorOptions &ExistingPPOpts;
51710b57cec5SDimitry Andric     std::string ExistingModuleCachePath;
51720b57cec5SDimitry Andric     FileManager &FileMgr;
517361cfbce3SDimitry Andric     bool StrictOptionMatches;
51740b57cec5SDimitry Andric 
51750b57cec5SDimitry Andric   public:
51760b57cec5SDimitry Andric     SimplePCHValidator(const LangOptions &ExistingLangOpts,
51770b57cec5SDimitry Andric                        const TargetOptions &ExistingTargetOpts,
51780b57cec5SDimitry Andric                        const PreprocessorOptions &ExistingPPOpts,
517961cfbce3SDimitry Andric                        StringRef ExistingModuleCachePath, FileManager &FileMgr,
518061cfbce3SDimitry Andric                        bool StrictOptionMatches)
51810b57cec5SDimitry Andric         : ExistingLangOpts(ExistingLangOpts),
51820b57cec5SDimitry Andric           ExistingTargetOpts(ExistingTargetOpts),
51830b57cec5SDimitry Andric           ExistingPPOpts(ExistingPPOpts),
518461cfbce3SDimitry Andric           ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
518561cfbce3SDimitry Andric           StrictOptionMatches(StrictOptionMatches) {}
51860b57cec5SDimitry Andric 
51870b57cec5SDimitry Andric     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
51880b57cec5SDimitry Andric                              bool AllowCompatibleDifferences) override {
51890b57cec5SDimitry Andric       return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
51900b57cec5SDimitry Andric                                   AllowCompatibleDifferences);
51910b57cec5SDimitry Andric     }
51920b57cec5SDimitry Andric 
51930b57cec5SDimitry Andric     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
51940b57cec5SDimitry Andric                            bool AllowCompatibleDifferences) override {
51950b57cec5SDimitry Andric       return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
51960b57cec5SDimitry Andric                                 AllowCompatibleDifferences);
51970b57cec5SDimitry Andric     }
51980b57cec5SDimitry Andric 
51990b57cec5SDimitry Andric     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
52000b57cec5SDimitry Andric                                  StringRef SpecificModuleCachePath,
52010b57cec5SDimitry Andric                                  bool Complain) override {
52020b57cec5SDimitry Andric       return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5203fe6060f1SDimitry Andric                                       ExistingModuleCachePath, nullptr,
5204fe6060f1SDimitry Andric                                       ExistingLangOpts, ExistingPPOpts);
52050b57cec5SDimitry Andric     }
52060b57cec5SDimitry Andric 
52070b57cec5SDimitry Andric     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
52080b57cec5SDimitry Andric                                  bool Complain,
52090b57cec5SDimitry Andric                                  std::string &SuggestedPredefines) override {
521061cfbce3SDimitry Andric       return checkPreprocessorOptions(
521161cfbce3SDimitry Andric           PPOpts, ExistingPPOpts, /*Diags=*/nullptr, FileMgr,
521261cfbce3SDimitry Andric           SuggestedPredefines, ExistingLangOpts,
521361cfbce3SDimitry Andric           StrictOptionMatches ? OptionValidateStrictMatches
521461cfbce3SDimitry Andric                               : OptionValidateContradictions);
52150b57cec5SDimitry Andric     }
52160b57cec5SDimitry Andric   };
52170b57cec5SDimitry Andric 
52180b57cec5SDimitry Andric } // namespace
52190b57cec5SDimitry Andric 
52200b57cec5SDimitry Andric bool ASTReader::readASTFileControlBlock(
52210b57cec5SDimitry Andric     StringRef Filename, FileManager &FileMgr,
5222*bdd1243dSDimitry Andric     const InMemoryModuleCache &ModuleCache,
5223*bdd1243dSDimitry Andric     const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
52240b57cec5SDimitry Andric     ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
52250b57cec5SDimitry Andric   // Open the AST file.
5226*bdd1243dSDimitry Andric   std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
5227*bdd1243dSDimitry Andric   llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
5228*bdd1243dSDimitry Andric   if (!Buffer) {
5229*bdd1243dSDimitry Andric     // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
5230*bdd1243dSDimitry Andric     // read again later, but we do not have the context here to determine if it
5231*bdd1243dSDimitry Andric     // is safe to change the result of InMemoryModuleCache::getPCMState().
5232*bdd1243dSDimitry Andric 
52330b57cec5SDimitry Andric     // FIXME: This allows use of the VFS; we do not allow use of the
52340b57cec5SDimitry Andric     // VFS when actually loading a module.
5235*bdd1243dSDimitry Andric     auto BufferOrErr = FileMgr.getBufferForFile(Filename);
5236*bdd1243dSDimitry Andric     if (!BufferOrErr)
52370b57cec5SDimitry Andric       return true;
5238*bdd1243dSDimitry Andric     OwnedBuffer = std::move(*BufferOrErr);
5239*bdd1243dSDimitry Andric     Buffer = OwnedBuffer.get();
52400b57cec5SDimitry Andric   }
52410b57cec5SDimitry Andric 
52420b57cec5SDimitry Andric   // Initialize the stream
5243*bdd1243dSDimitry Andric   StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
52440b57cec5SDimitry Andric   BitstreamCursor Stream(Bytes);
52450b57cec5SDimitry Andric 
52460b57cec5SDimitry Andric   // Sniff for the signature.
52470b57cec5SDimitry Andric   if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
52480b57cec5SDimitry Andric     consumeError(std::move(Err)); // FIXME this drops errors on the floor.
52490b57cec5SDimitry Andric     return true;
52500b57cec5SDimitry Andric   }
52510b57cec5SDimitry Andric 
52520b57cec5SDimitry Andric   // Scan for the CONTROL_BLOCK_ID block.
52530b57cec5SDimitry Andric   if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
52540b57cec5SDimitry Andric     return true;
52550b57cec5SDimitry Andric 
52560b57cec5SDimitry Andric   bool NeedsInputFiles = Listener.needsInputFileVisitation();
52570b57cec5SDimitry Andric   bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
52580b57cec5SDimitry Andric   bool NeedsImports = Listener.needsImportVisitation();
52590b57cec5SDimitry Andric   BitstreamCursor InputFilesCursor;
52600b57cec5SDimitry Andric 
52610b57cec5SDimitry Andric   RecordData Record;
52620b57cec5SDimitry Andric   std::string ModuleDir;
52630b57cec5SDimitry Andric   bool DoneWithControlBlock = false;
52640b57cec5SDimitry Andric   while (!DoneWithControlBlock) {
52650b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
52660b57cec5SDimitry Andric     if (!MaybeEntry) {
52670b57cec5SDimitry Andric       // FIXME this drops the error on the floor.
52680b57cec5SDimitry Andric       consumeError(MaybeEntry.takeError());
52690b57cec5SDimitry Andric       return true;
52700b57cec5SDimitry Andric     }
52710b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
52720b57cec5SDimitry Andric 
52730b57cec5SDimitry Andric     switch (Entry.Kind) {
52740b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: {
52750b57cec5SDimitry Andric       switch (Entry.ID) {
52760b57cec5SDimitry Andric       case OPTIONS_BLOCK_ID: {
52770b57cec5SDimitry Andric         std::string IgnoredSuggestedPredefines;
52780b57cec5SDimitry Andric         if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
52790b57cec5SDimitry Andric                              /*AllowCompatibleConfigurationMismatch*/ false,
52800b57cec5SDimitry Andric                              Listener, IgnoredSuggestedPredefines) != Success)
52810b57cec5SDimitry Andric           return true;
52820b57cec5SDimitry Andric         break;
52830b57cec5SDimitry Andric       }
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric       case INPUT_FILES_BLOCK_ID:
52860b57cec5SDimitry Andric         InputFilesCursor = Stream;
52870b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
52880b57cec5SDimitry Andric           // FIXME this drops the error on the floor.
52890b57cec5SDimitry Andric           consumeError(std::move(Err));
52900b57cec5SDimitry Andric           return true;
52910b57cec5SDimitry Andric         }
52920b57cec5SDimitry Andric         if (NeedsInputFiles &&
52930b57cec5SDimitry Andric             ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
52940b57cec5SDimitry Andric           return true;
52950b57cec5SDimitry Andric         break;
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric       default:
52980b57cec5SDimitry Andric         if (llvm::Error Err = Stream.SkipBlock()) {
52990b57cec5SDimitry Andric           // FIXME this drops the error on the floor.
53000b57cec5SDimitry Andric           consumeError(std::move(Err));
53010b57cec5SDimitry Andric           return true;
53020b57cec5SDimitry Andric         }
53030b57cec5SDimitry Andric         break;
53040b57cec5SDimitry Andric       }
53050b57cec5SDimitry Andric 
53060b57cec5SDimitry Andric       continue;
53070b57cec5SDimitry Andric     }
53080b57cec5SDimitry Andric 
53090b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
53100b57cec5SDimitry Andric       DoneWithControlBlock = true;
53110b57cec5SDimitry Andric       break;
53120b57cec5SDimitry Andric 
53130b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
53140b57cec5SDimitry Andric       return true;
53150b57cec5SDimitry Andric 
53160b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
53170b57cec5SDimitry Andric       break;
53180b57cec5SDimitry Andric     }
53190b57cec5SDimitry Andric 
53200b57cec5SDimitry Andric     if (DoneWithControlBlock) break;
53210b57cec5SDimitry Andric 
53220b57cec5SDimitry Andric     Record.clear();
53230b57cec5SDimitry Andric     StringRef Blob;
53240b57cec5SDimitry Andric     Expected<unsigned> MaybeRecCode =
53250b57cec5SDimitry Andric         Stream.readRecord(Entry.ID, Record, &Blob);
53260b57cec5SDimitry Andric     if (!MaybeRecCode) {
53270b57cec5SDimitry Andric       // FIXME this drops the error.
53280b57cec5SDimitry Andric       return Failure;
53290b57cec5SDimitry Andric     }
53300b57cec5SDimitry Andric     switch ((ControlRecordTypes)MaybeRecCode.get()) {
53310b57cec5SDimitry Andric     case METADATA:
53320b57cec5SDimitry Andric       if (Record[0] != VERSION_MAJOR)
53330b57cec5SDimitry Andric         return true;
53340b57cec5SDimitry Andric       if (Listener.ReadFullVersionInformation(Blob))
53350b57cec5SDimitry Andric         return true;
53360b57cec5SDimitry Andric       break;
53370b57cec5SDimitry Andric     case MODULE_NAME:
53380b57cec5SDimitry Andric       Listener.ReadModuleName(Blob);
53390b57cec5SDimitry Andric       break;
53400b57cec5SDimitry Andric     case MODULE_DIRECTORY:
53415ffd83dbSDimitry Andric       ModuleDir = std::string(Blob);
53420b57cec5SDimitry Andric       break;
53430b57cec5SDimitry Andric     case MODULE_MAP_FILE: {
53440b57cec5SDimitry Andric       unsigned Idx = 0;
53450b57cec5SDimitry Andric       auto Path = ReadString(Record, Idx);
53460b57cec5SDimitry Andric       ResolveImportedPath(Path, ModuleDir);
53470b57cec5SDimitry Andric       Listener.ReadModuleMapFile(Path);
53480b57cec5SDimitry Andric       break;
53490b57cec5SDimitry Andric     }
53500b57cec5SDimitry Andric     case INPUT_FILE_OFFSETS: {
53510b57cec5SDimitry Andric       if (!NeedsInputFiles)
53520b57cec5SDimitry Andric         break;
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric       unsigned NumInputFiles = Record[0];
53550b57cec5SDimitry Andric       unsigned NumUserFiles = Record[1];
53560b57cec5SDimitry Andric       const llvm::support::unaligned_uint64_t *InputFileOffs =
53570b57cec5SDimitry Andric           (const llvm::support::unaligned_uint64_t *)Blob.data();
53580b57cec5SDimitry Andric       for (unsigned I = 0; I != NumInputFiles; ++I) {
53590b57cec5SDimitry Andric         // Go find this input file.
53600b57cec5SDimitry Andric         bool isSystemFile = I >= NumUserFiles;
53610b57cec5SDimitry Andric 
53620b57cec5SDimitry Andric         if (isSystemFile && !NeedsSystemInputFiles)
53630b57cec5SDimitry Andric           break; // the rest are system input files
53640b57cec5SDimitry Andric 
53650b57cec5SDimitry Andric         BitstreamCursor &Cursor = InputFilesCursor;
53660b57cec5SDimitry Andric         SavedStreamPosition SavedPosition(Cursor);
53670b57cec5SDimitry Andric         if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
53680b57cec5SDimitry Andric           // FIXME this drops errors on the floor.
53690b57cec5SDimitry Andric           consumeError(std::move(Err));
53700b57cec5SDimitry Andric         }
53710b57cec5SDimitry Andric 
53720b57cec5SDimitry Andric         Expected<unsigned> MaybeCode = Cursor.ReadCode();
53730b57cec5SDimitry Andric         if (!MaybeCode) {
53740b57cec5SDimitry Andric           // FIXME this drops errors on the floor.
53750b57cec5SDimitry Andric           consumeError(MaybeCode.takeError());
53760b57cec5SDimitry Andric         }
53770b57cec5SDimitry Andric         unsigned Code = MaybeCode.get();
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric         RecordData Record;
53800b57cec5SDimitry Andric         StringRef Blob;
53810b57cec5SDimitry Andric         bool shouldContinue = false;
53820b57cec5SDimitry Andric         Expected<unsigned> MaybeRecordType =
53830b57cec5SDimitry Andric             Cursor.readRecord(Code, Record, &Blob);
53840b57cec5SDimitry Andric         if (!MaybeRecordType) {
53850b57cec5SDimitry Andric           // FIXME this drops errors on the floor.
53860b57cec5SDimitry Andric           consumeError(MaybeRecordType.takeError());
53870b57cec5SDimitry Andric         }
53880b57cec5SDimitry Andric         switch ((InputFileRecordTypes)MaybeRecordType.get()) {
5389a7dea167SDimitry Andric         case INPUT_FILE_HASH:
5390a7dea167SDimitry Andric           break;
53910b57cec5SDimitry Andric         case INPUT_FILE:
53920b57cec5SDimitry Andric           bool Overridden = static_cast<bool>(Record[3]);
53935ffd83dbSDimitry Andric           std::string Filename = std::string(Blob);
53940b57cec5SDimitry Andric           ResolveImportedPath(Filename, ModuleDir);
53950b57cec5SDimitry Andric           shouldContinue = Listener.visitInputFile(
53960b57cec5SDimitry Andric               Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
53970b57cec5SDimitry Andric           break;
53980b57cec5SDimitry Andric         }
53990b57cec5SDimitry Andric         if (!shouldContinue)
54000b57cec5SDimitry Andric           break;
54010b57cec5SDimitry Andric       }
54020b57cec5SDimitry Andric       break;
54030b57cec5SDimitry Andric     }
54040b57cec5SDimitry Andric 
54050b57cec5SDimitry Andric     case IMPORTS: {
54060b57cec5SDimitry Andric       if (!NeedsImports)
54070b57cec5SDimitry Andric         break;
54080b57cec5SDimitry Andric 
54090b57cec5SDimitry Andric       unsigned Idx = 0, N = Record.size();
54100b57cec5SDimitry Andric       while (Idx < N) {
54110b57cec5SDimitry Andric         // Read information about the AST file.
54125ffd83dbSDimitry Andric         Idx +=
54135ffd83dbSDimitry Andric             1 + 1 + 1 + 1 +
54145ffd83dbSDimitry Andric             ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
54150b57cec5SDimitry Andric         std::string ModuleName = ReadString(Record, Idx);
54160b57cec5SDimitry Andric         std::string Filename = ReadString(Record, Idx);
54170b57cec5SDimitry Andric         ResolveImportedPath(Filename, ModuleDir);
54180b57cec5SDimitry Andric         Listener.visitImport(ModuleName, Filename);
54190b57cec5SDimitry Andric       }
54200b57cec5SDimitry Andric       break;
54210b57cec5SDimitry Andric     }
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric     default:
54240b57cec5SDimitry Andric       // No other validation to perform.
54250b57cec5SDimitry Andric       break;
54260b57cec5SDimitry Andric     }
54270b57cec5SDimitry Andric   }
54280b57cec5SDimitry Andric 
54290b57cec5SDimitry Andric   // Look for module file extension blocks, if requested.
54300b57cec5SDimitry Andric   if (FindModuleFileExtensions) {
54310b57cec5SDimitry Andric     BitstreamCursor SavedStream = Stream;
54320b57cec5SDimitry Andric     while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
54330b57cec5SDimitry Andric       bool DoneWithExtensionBlock = false;
54340b57cec5SDimitry Andric       while (!DoneWithExtensionBlock) {
54350b57cec5SDimitry Andric         Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
54360b57cec5SDimitry Andric         if (!MaybeEntry) {
54370b57cec5SDimitry Andric           // FIXME this drops the error.
54380b57cec5SDimitry Andric           return true;
54390b57cec5SDimitry Andric         }
54400b57cec5SDimitry Andric         llvm::BitstreamEntry Entry = MaybeEntry.get();
54410b57cec5SDimitry Andric 
54420b57cec5SDimitry Andric         switch (Entry.Kind) {
54430b57cec5SDimitry Andric         case llvm::BitstreamEntry::SubBlock:
54440b57cec5SDimitry Andric           if (llvm::Error Err = Stream.SkipBlock()) {
54450b57cec5SDimitry Andric             // FIXME this drops the error on the floor.
54460b57cec5SDimitry Andric             consumeError(std::move(Err));
54470b57cec5SDimitry Andric             return true;
54480b57cec5SDimitry Andric           }
54490b57cec5SDimitry Andric           continue;
54500b57cec5SDimitry Andric 
54510b57cec5SDimitry Andric         case llvm::BitstreamEntry::EndBlock:
54520b57cec5SDimitry Andric           DoneWithExtensionBlock = true;
54530b57cec5SDimitry Andric           continue;
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric         case llvm::BitstreamEntry::Error:
54560b57cec5SDimitry Andric           return true;
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric         case llvm::BitstreamEntry::Record:
54590b57cec5SDimitry Andric           break;
54600b57cec5SDimitry Andric         }
54610b57cec5SDimitry Andric 
54620b57cec5SDimitry Andric        Record.clear();
54630b57cec5SDimitry Andric        StringRef Blob;
54640b57cec5SDimitry Andric        Expected<unsigned> MaybeRecCode =
54650b57cec5SDimitry Andric            Stream.readRecord(Entry.ID, Record, &Blob);
54660b57cec5SDimitry Andric        if (!MaybeRecCode) {
54670b57cec5SDimitry Andric          // FIXME this drops the error.
54680b57cec5SDimitry Andric          return true;
54690b57cec5SDimitry Andric        }
54700b57cec5SDimitry Andric        switch (MaybeRecCode.get()) {
54710b57cec5SDimitry Andric        case EXTENSION_METADATA: {
54720b57cec5SDimitry Andric          ModuleFileExtensionMetadata Metadata;
54730b57cec5SDimitry Andric          if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
54740b57cec5SDimitry Andric            return true;
54750b57cec5SDimitry Andric 
54760b57cec5SDimitry Andric          Listener.readModuleFileExtension(Metadata);
54770b57cec5SDimitry Andric          break;
54780b57cec5SDimitry Andric        }
54790b57cec5SDimitry Andric        }
54800b57cec5SDimitry Andric       }
54810b57cec5SDimitry Andric     }
54820b57cec5SDimitry Andric     Stream = SavedStream;
54830b57cec5SDimitry Andric   }
54840b57cec5SDimitry Andric 
54850b57cec5SDimitry Andric   // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
54860b57cec5SDimitry Andric   if (readUnhashedControlBlockImpl(
54870b57cec5SDimitry Andric           nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
54880b57cec5SDimitry Andric           /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
54890b57cec5SDimitry Andric           ValidateDiagnosticOptions) != Success)
54900b57cec5SDimitry Andric     return true;
54910b57cec5SDimitry Andric 
54920b57cec5SDimitry Andric   return false;
54930b57cec5SDimitry Andric }
54940b57cec5SDimitry Andric 
54950b57cec5SDimitry Andric bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5496*bdd1243dSDimitry Andric                                     const InMemoryModuleCache &ModuleCache,
54970b57cec5SDimitry Andric                                     const PCHContainerReader &PCHContainerRdr,
54980b57cec5SDimitry Andric                                     const LangOptions &LangOpts,
54990b57cec5SDimitry Andric                                     const TargetOptions &TargetOpts,
55000b57cec5SDimitry Andric                                     const PreprocessorOptions &PPOpts,
550161cfbce3SDimitry Andric                                     StringRef ExistingModuleCachePath,
550261cfbce3SDimitry Andric                                     bool RequireStrictOptionMatches) {
55030b57cec5SDimitry Andric   SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
550461cfbce3SDimitry Andric                                ExistingModuleCachePath, FileMgr,
550561cfbce3SDimitry Andric                                RequireStrictOptionMatches);
5506*bdd1243dSDimitry Andric   return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
5507*bdd1243dSDimitry Andric                                   PCHContainerRdr,
5508*bdd1243dSDimitry Andric                                   /*FindModuleFileExtensions=*/false, validator,
55090b57cec5SDimitry Andric                                   /*ValidateDiagnosticOptions=*/true);
55100b57cec5SDimitry Andric }
55110b57cec5SDimitry Andric 
5512349cc55cSDimitry Andric llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
5513349cc55cSDimitry Andric                                           unsigned ClientLoadCapabilities) {
55140b57cec5SDimitry Andric   // Enter the submodule block.
5515349cc55cSDimitry Andric   if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
5516349cc55cSDimitry Andric     return Err;
55170b57cec5SDimitry Andric 
55180b57cec5SDimitry Andric   ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
55190b57cec5SDimitry Andric   bool First = true;
55200b57cec5SDimitry Andric   Module *CurrentModule = nullptr;
55210b57cec5SDimitry Andric   RecordData Record;
55220b57cec5SDimitry Andric   while (true) {
55230b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry =
55240b57cec5SDimitry Andric         F.Stream.advanceSkippingSubblocks();
5525349cc55cSDimitry Andric     if (!MaybeEntry)
5526349cc55cSDimitry Andric       return MaybeEntry.takeError();
55270b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
55280b57cec5SDimitry Andric 
55290b57cec5SDimitry Andric     switch (Entry.Kind) {
55300b57cec5SDimitry Andric     case llvm::BitstreamEntry::SubBlock: // Handled for us already.
55310b57cec5SDimitry Andric     case llvm::BitstreamEntry::Error:
5532349cc55cSDimitry Andric       return llvm::createStringError(std::errc::illegal_byte_sequence,
5533349cc55cSDimitry Andric                                      "malformed block record in AST file");
55340b57cec5SDimitry Andric     case llvm::BitstreamEntry::EndBlock:
5535349cc55cSDimitry Andric       return llvm::Error::success();
55360b57cec5SDimitry Andric     case llvm::BitstreamEntry::Record:
55370b57cec5SDimitry Andric       // The interesting case.
55380b57cec5SDimitry Andric       break;
55390b57cec5SDimitry Andric     }
55400b57cec5SDimitry Andric 
55410b57cec5SDimitry Andric     // Read a record.
55420b57cec5SDimitry Andric     StringRef Blob;
55430b57cec5SDimitry Andric     Record.clear();
55440b57cec5SDimitry Andric     Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5545349cc55cSDimitry Andric     if (!MaybeKind)
5546349cc55cSDimitry Andric       return MaybeKind.takeError();
55470b57cec5SDimitry Andric     unsigned Kind = MaybeKind.get();
55480b57cec5SDimitry Andric 
5549349cc55cSDimitry Andric     if ((Kind == SUBMODULE_METADATA) != First)
5550349cc55cSDimitry Andric       return llvm::createStringError(
5551349cc55cSDimitry Andric           std::errc::illegal_byte_sequence,
5552349cc55cSDimitry Andric           "submodule metadata record should be at beginning of block");
55530b57cec5SDimitry Andric     First = false;
55540b57cec5SDimitry Andric 
55550b57cec5SDimitry Andric     // Submodule information is only valid if we have a current module.
55560b57cec5SDimitry Andric     // FIXME: Should we error on these cases?
55570b57cec5SDimitry Andric     if (!CurrentModule && Kind != SUBMODULE_METADATA &&
55580b57cec5SDimitry Andric         Kind != SUBMODULE_DEFINITION)
55590b57cec5SDimitry Andric       continue;
55600b57cec5SDimitry Andric 
55610b57cec5SDimitry Andric     switch (Kind) {
55620b57cec5SDimitry Andric     default:  // Default behavior: ignore.
55630b57cec5SDimitry Andric       break;
55640b57cec5SDimitry Andric 
55650b57cec5SDimitry Andric     case SUBMODULE_DEFINITION: {
5566349cc55cSDimitry Andric       if (Record.size() < 12)
5567349cc55cSDimitry Andric         return llvm::createStringError(std::errc::illegal_byte_sequence,
5568349cc55cSDimitry Andric                                        "malformed module definition");
55690b57cec5SDimitry Andric 
55700b57cec5SDimitry Andric       StringRef Name = Blob;
55710b57cec5SDimitry Andric       unsigned Idx = 0;
55720b57cec5SDimitry Andric       SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
55730b57cec5SDimitry Andric       SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
55740b57cec5SDimitry Andric       Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
55750b57cec5SDimitry Andric       bool IsFramework = Record[Idx++];
55760b57cec5SDimitry Andric       bool IsExplicit = Record[Idx++];
55770b57cec5SDimitry Andric       bool IsSystem = Record[Idx++];
55780b57cec5SDimitry Andric       bool IsExternC = Record[Idx++];
55790b57cec5SDimitry Andric       bool InferSubmodules = Record[Idx++];
55800b57cec5SDimitry Andric       bool InferExplicitSubmodules = Record[Idx++];
55810b57cec5SDimitry Andric       bool InferExportWildcard = Record[Idx++];
55820b57cec5SDimitry Andric       bool ConfigMacrosExhaustive = Record[Idx++];
55830b57cec5SDimitry Andric       bool ModuleMapIsPrivate = Record[Idx++];
55840b57cec5SDimitry Andric 
55850b57cec5SDimitry Andric       Module *ParentModule = nullptr;
55860b57cec5SDimitry Andric       if (Parent)
55870b57cec5SDimitry Andric         ParentModule = getSubmodule(Parent);
55880b57cec5SDimitry Andric 
55890b57cec5SDimitry Andric       // Retrieve this (sub)module from the module map, creating it if
55900b57cec5SDimitry Andric       // necessary.
55910b57cec5SDimitry Andric       CurrentModule =
55920b57cec5SDimitry Andric           ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
55930b57cec5SDimitry Andric               .first;
55940b57cec5SDimitry Andric 
55950b57cec5SDimitry Andric       // FIXME: set the definition loc for CurrentModule, or call
55960b57cec5SDimitry Andric       // ModMap.setInferredModuleAllowedBy()
55970b57cec5SDimitry Andric 
55980b57cec5SDimitry Andric       SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
55990b57cec5SDimitry Andric       if (GlobalIndex >= SubmodulesLoaded.size() ||
5600349cc55cSDimitry Andric           SubmodulesLoaded[GlobalIndex])
5601349cc55cSDimitry Andric         return llvm::createStringError(std::errc::invalid_argument,
5602349cc55cSDimitry Andric                                        "too many submodules");
56030b57cec5SDimitry Andric 
56040b57cec5SDimitry Andric       if (!ParentModule) {
56050b57cec5SDimitry Andric         if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
56060b57cec5SDimitry Andric           // Don't emit module relocation error if we have -fno-validate-pch
5607e8d8bef9SDimitry Andric           if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
5608e8d8bef9SDimitry Andric                     DisableValidationForModuleKind::Module) &&
56090b57cec5SDimitry Andric               CurFile != F.File) {
5610349cc55cSDimitry Andric             auto ConflictError =
5611349cc55cSDimitry Andric                 PartialDiagnostic(diag::err_module_file_conflict,
5612349cc55cSDimitry Andric                                   ContextObj->DiagAllocator)
5613349cc55cSDimitry Andric                 << CurrentModule->getTopLevelModuleName() << CurFile->getName()
5614349cc55cSDimitry Andric                 << F.File->getName();
5615349cc55cSDimitry Andric             return DiagnosticError::create(CurrentImportLoc, ConflictError);
56160b57cec5SDimitry Andric           }
56170b57cec5SDimitry Andric         }
56180b57cec5SDimitry Andric 
5619480093f4SDimitry Andric         F.DidReadTopLevelSubmodule = true;
56200b57cec5SDimitry Andric         CurrentModule->setASTFile(F.File);
56210b57cec5SDimitry Andric         CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
56220b57cec5SDimitry Andric       }
56230b57cec5SDimitry Andric 
56240b57cec5SDimitry Andric       CurrentModule->Kind = Kind;
56250b57cec5SDimitry Andric       CurrentModule->Signature = F.Signature;
56260b57cec5SDimitry Andric       CurrentModule->IsFromModuleFile = true;
56270b57cec5SDimitry Andric       CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
56280b57cec5SDimitry Andric       CurrentModule->IsExternC = IsExternC;
56290b57cec5SDimitry Andric       CurrentModule->InferSubmodules = InferSubmodules;
56300b57cec5SDimitry Andric       CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
56310b57cec5SDimitry Andric       CurrentModule->InferExportWildcard = InferExportWildcard;
56320b57cec5SDimitry Andric       CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
56330b57cec5SDimitry Andric       CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
56340b57cec5SDimitry Andric       if (DeserializationListener)
56350b57cec5SDimitry Andric         DeserializationListener->ModuleRead(GlobalID, CurrentModule);
56360b57cec5SDimitry Andric 
56370b57cec5SDimitry Andric       SubmodulesLoaded[GlobalIndex] = CurrentModule;
56380b57cec5SDimitry Andric 
56390b57cec5SDimitry Andric       // Clear out data that will be replaced by what is in the module file.
56400b57cec5SDimitry Andric       CurrentModule->LinkLibraries.clear();
56410b57cec5SDimitry Andric       CurrentModule->ConfigMacros.clear();
56420b57cec5SDimitry Andric       CurrentModule->UnresolvedConflicts.clear();
56430b57cec5SDimitry Andric       CurrentModule->Conflicts.clear();
56440b57cec5SDimitry Andric 
56450b57cec5SDimitry Andric       // The module is available unless it's missing a requirement; relevant
56460b57cec5SDimitry Andric       // requirements will be (re-)added by SUBMODULE_REQUIRES records.
56470b57cec5SDimitry Andric       // Missing headers that were present when the module was built do not
56480b57cec5SDimitry Andric       // make it unavailable -- if we got this far, this must be an explicitly
56490b57cec5SDimitry Andric       // imported module file.
56500b57cec5SDimitry Andric       CurrentModule->Requirements.clear();
56510b57cec5SDimitry Andric       CurrentModule->MissingHeaders.clear();
56525ffd83dbSDimitry Andric       CurrentModule->IsUnimportable =
56535ffd83dbSDimitry Andric           ParentModule && ParentModule->IsUnimportable;
56545ffd83dbSDimitry Andric       CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
56550b57cec5SDimitry Andric       break;
56560b57cec5SDimitry Andric     }
56570b57cec5SDimitry Andric 
56580b57cec5SDimitry Andric     case SUBMODULE_UMBRELLA_HEADER: {
5659349cc55cSDimitry Andric       // FIXME: This doesn't work for framework modules as `Filename` is the
5660349cc55cSDimitry Andric       //        name as written in the module file and does not include
5661349cc55cSDimitry Andric       //        `Headers/`, so this path will never exist.
56625ffd83dbSDimitry Andric       std::string Filename = std::string(Blob);
56630b57cec5SDimitry Andric       ResolveImportedPath(F, Filename);
5664*bdd1243dSDimitry Andric       if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
5665349cc55cSDimitry Andric         if (!CurrentModule->getUmbrellaHeader()) {
5666fe6060f1SDimitry Andric           // FIXME: NameAsWritten
5667fe6060f1SDimitry Andric           ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
56680b57cec5SDimitry Andric         }
5669349cc55cSDimitry Andric         // Note that it's too late at this point to return out of date if the
5670349cc55cSDimitry Andric         // name from the PCM doesn't match up with the one in the module map,
5671349cc55cSDimitry Andric         // but also quite unlikely since we will have already checked the
5672349cc55cSDimitry Andric         // modification time and size of the module map file itself.
56730b57cec5SDimitry Andric       }
56740b57cec5SDimitry Andric       break;
56750b57cec5SDimitry Andric     }
56760b57cec5SDimitry Andric 
56770b57cec5SDimitry Andric     case SUBMODULE_HEADER:
56780b57cec5SDimitry Andric     case SUBMODULE_EXCLUDED_HEADER:
56790b57cec5SDimitry Andric     case SUBMODULE_PRIVATE_HEADER:
56800b57cec5SDimitry Andric       // We lazily associate headers with their modules via the HeaderInfo table.
56810b57cec5SDimitry Andric       // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
56820b57cec5SDimitry Andric       // of complete filenames or remove it entirely.
56830b57cec5SDimitry Andric       break;
56840b57cec5SDimitry Andric 
56850b57cec5SDimitry Andric     case SUBMODULE_TEXTUAL_HEADER:
56860b57cec5SDimitry Andric     case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
56870b57cec5SDimitry Andric       // FIXME: Textual headers are not marked in the HeaderInfo table. Load
56880b57cec5SDimitry Andric       // them here.
56890b57cec5SDimitry Andric       break;
56900b57cec5SDimitry Andric 
569181ad6265SDimitry Andric     case SUBMODULE_TOPHEADER: {
569281ad6265SDimitry Andric       std::string HeaderName(Blob);
569381ad6265SDimitry Andric       ResolveImportedPath(F, HeaderName);
569481ad6265SDimitry Andric       CurrentModule->addTopHeaderFilename(HeaderName);
56950b57cec5SDimitry Andric       break;
569681ad6265SDimitry Andric     }
56970b57cec5SDimitry Andric 
56980b57cec5SDimitry Andric     case SUBMODULE_UMBRELLA_DIR: {
5699349cc55cSDimitry Andric       // See comments in SUBMODULE_UMBRELLA_HEADER
57005ffd83dbSDimitry Andric       std::string Dirname = std::string(Blob);
57010b57cec5SDimitry Andric       ResolveImportedPath(F, Dirname);
5702fe6060f1SDimitry Andric       if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
5703349cc55cSDimitry Andric         if (!CurrentModule->getUmbrellaDir()) {
5704fe6060f1SDimitry Andric           // FIXME: NameAsWritten
5705fe6060f1SDimitry Andric           ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
57060b57cec5SDimitry Andric         }
57070b57cec5SDimitry Andric       }
57080b57cec5SDimitry Andric       break;
57090b57cec5SDimitry Andric     }
57100b57cec5SDimitry Andric 
57110b57cec5SDimitry Andric     case SUBMODULE_METADATA: {
57120b57cec5SDimitry Andric       F.BaseSubmoduleID = getTotalNumSubmodules();
57130b57cec5SDimitry Andric       F.LocalNumSubmodules = Record[0];
57140b57cec5SDimitry Andric       unsigned LocalBaseSubmoduleID = Record[1];
57150b57cec5SDimitry Andric       if (F.LocalNumSubmodules > 0) {
57160b57cec5SDimitry Andric         // Introduce the global -> local mapping for submodules within this
57170b57cec5SDimitry Andric         // module.
57180b57cec5SDimitry Andric         GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
57190b57cec5SDimitry Andric 
57200b57cec5SDimitry Andric         // Introduce the local -> global mapping for submodules within this
57210b57cec5SDimitry Andric         // module.
57220b57cec5SDimitry Andric         F.SubmoduleRemap.insertOrReplace(
57230b57cec5SDimitry Andric           std::make_pair(LocalBaseSubmoduleID,
57240b57cec5SDimitry Andric                          F.BaseSubmoduleID - LocalBaseSubmoduleID));
57250b57cec5SDimitry Andric 
57260b57cec5SDimitry Andric         SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
57270b57cec5SDimitry Andric       }
57280b57cec5SDimitry Andric       break;
57290b57cec5SDimitry Andric     }
57300b57cec5SDimitry Andric 
57310b57cec5SDimitry Andric     case SUBMODULE_IMPORTS:
57320b57cec5SDimitry Andric       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
57330b57cec5SDimitry Andric         UnresolvedModuleRef Unresolved;
57340b57cec5SDimitry Andric         Unresolved.File = &F;
57350b57cec5SDimitry Andric         Unresolved.Mod = CurrentModule;
57360b57cec5SDimitry Andric         Unresolved.ID = Record[Idx];
57370b57cec5SDimitry Andric         Unresolved.Kind = UnresolvedModuleRef::Import;
57380b57cec5SDimitry Andric         Unresolved.IsWildcard = false;
57390b57cec5SDimitry Andric         UnresolvedModuleRefs.push_back(Unresolved);
57400b57cec5SDimitry Andric       }
57410b57cec5SDimitry Andric       break;
57420b57cec5SDimitry Andric 
5743*bdd1243dSDimitry Andric     case SUBMODULE_AFFECTING_MODULES:
5744*bdd1243dSDimitry Andric       for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
5745*bdd1243dSDimitry Andric         UnresolvedModuleRef Unresolved;
5746*bdd1243dSDimitry Andric         Unresolved.File = &F;
5747*bdd1243dSDimitry Andric         Unresolved.Mod = CurrentModule;
5748*bdd1243dSDimitry Andric         Unresolved.ID = Record[Idx];
5749*bdd1243dSDimitry Andric         Unresolved.Kind = UnresolvedModuleRef::Affecting;
5750*bdd1243dSDimitry Andric         Unresolved.IsWildcard = false;
5751*bdd1243dSDimitry Andric         UnresolvedModuleRefs.push_back(Unresolved);
5752*bdd1243dSDimitry Andric       }
5753*bdd1243dSDimitry Andric       break;
5754*bdd1243dSDimitry Andric 
57550b57cec5SDimitry Andric     case SUBMODULE_EXPORTS:
57560b57cec5SDimitry Andric       for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
57570b57cec5SDimitry Andric         UnresolvedModuleRef Unresolved;
57580b57cec5SDimitry Andric         Unresolved.File = &F;
57590b57cec5SDimitry Andric         Unresolved.Mod = CurrentModule;
57600b57cec5SDimitry Andric         Unresolved.ID = Record[Idx];
57610b57cec5SDimitry Andric         Unresolved.Kind = UnresolvedModuleRef::Export;
57620b57cec5SDimitry Andric         Unresolved.IsWildcard = Record[Idx + 1];
57630b57cec5SDimitry Andric         UnresolvedModuleRefs.push_back(Unresolved);
57640b57cec5SDimitry Andric       }
57650b57cec5SDimitry Andric 
57660b57cec5SDimitry Andric       // Once we've loaded the set of exports, there's no reason to keep
57670b57cec5SDimitry Andric       // the parsed, unresolved exports around.
57680b57cec5SDimitry Andric       CurrentModule->UnresolvedExports.clear();
57690b57cec5SDimitry Andric       break;
57700b57cec5SDimitry Andric 
57710b57cec5SDimitry Andric     case SUBMODULE_REQUIRES:
57720b57cec5SDimitry Andric       CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
57730b57cec5SDimitry Andric                                     PP.getTargetInfo());
57740b57cec5SDimitry Andric       break;
57750b57cec5SDimitry Andric 
57760b57cec5SDimitry Andric     case SUBMODULE_LINK_LIBRARY:
57770b57cec5SDimitry Andric       ModMap.resolveLinkAsDependencies(CurrentModule);
57780b57cec5SDimitry Andric       CurrentModule->LinkLibraries.push_back(
57795ffd83dbSDimitry Andric           Module::LinkLibrary(std::string(Blob), Record[0]));
57800b57cec5SDimitry Andric       break;
57810b57cec5SDimitry Andric 
57820b57cec5SDimitry Andric     case SUBMODULE_CONFIG_MACRO:
57830b57cec5SDimitry Andric       CurrentModule->ConfigMacros.push_back(Blob.str());
57840b57cec5SDimitry Andric       break;
57850b57cec5SDimitry Andric 
57860b57cec5SDimitry Andric     case SUBMODULE_CONFLICT: {
57870b57cec5SDimitry Andric       UnresolvedModuleRef Unresolved;
57880b57cec5SDimitry Andric       Unresolved.File = &F;
57890b57cec5SDimitry Andric       Unresolved.Mod = CurrentModule;
57900b57cec5SDimitry Andric       Unresolved.ID = Record[0];
57910b57cec5SDimitry Andric       Unresolved.Kind = UnresolvedModuleRef::Conflict;
57920b57cec5SDimitry Andric       Unresolved.IsWildcard = false;
57930b57cec5SDimitry Andric       Unresolved.String = Blob;
57940b57cec5SDimitry Andric       UnresolvedModuleRefs.push_back(Unresolved);
57950b57cec5SDimitry Andric       break;
57960b57cec5SDimitry Andric     }
57970b57cec5SDimitry Andric 
57980b57cec5SDimitry Andric     case SUBMODULE_INITIALIZERS: {
57990b57cec5SDimitry Andric       if (!ContextObj)
58000b57cec5SDimitry Andric         break;
58010b57cec5SDimitry Andric       SmallVector<uint32_t, 16> Inits;
58020b57cec5SDimitry Andric       for (auto &ID : Record)
58030b57cec5SDimitry Andric         Inits.push_back(getGlobalDeclID(F, ID));
58040b57cec5SDimitry Andric       ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
58050b57cec5SDimitry Andric       break;
58060b57cec5SDimitry Andric     }
58070b57cec5SDimitry Andric 
58080b57cec5SDimitry Andric     case SUBMODULE_EXPORT_AS:
58090b57cec5SDimitry Andric       CurrentModule->ExportAsModule = Blob.str();
58100b57cec5SDimitry Andric       ModMap.addLinkAsDependency(CurrentModule);
58110b57cec5SDimitry Andric       break;
58120b57cec5SDimitry Andric     }
58130b57cec5SDimitry Andric   }
58140b57cec5SDimitry Andric }
58150b57cec5SDimitry Andric 
58160b57cec5SDimitry Andric /// Parse the record that corresponds to a LangOptions data
58170b57cec5SDimitry Andric /// structure.
58180b57cec5SDimitry Andric ///
58190b57cec5SDimitry Andric /// This routine parses the language options from the AST file and then gives
58200b57cec5SDimitry Andric /// them to the AST listener if one is set.
58210b57cec5SDimitry Andric ///
58220b57cec5SDimitry Andric /// \returns true if the listener deems the file unacceptable, false otherwise.
58230b57cec5SDimitry Andric bool ASTReader::ParseLanguageOptions(const RecordData &Record,
58240b57cec5SDimitry Andric                                      bool Complain,
58250b57cec5SDimitry Andric                                      ASTReaderListener &Listener,
58260b57cec5SDimitry Andric                                      bool AllowCompatibleDifferences) {
58270b57cec5SDimitry Andric   LangOptions LangOpts;
58280b57cec5SDimitry Andric   unsigned Idx = 0;
58290b57cec5SDimitry Andric #define LANGOPT(Name, Bits, Default, Description) \
58300b57cec5SDimitry Andric   LangOpts.Name = Record[Idx++];
58310b57cec5SDimitry Andric #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
58320b57cec5SDimitry Andric   LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
58330b57cec5SDimitry Andric #include "clang/Basic/LangOptions.def"
58340b57cec5SDimitry Andric #define SANITIZER(NAME, ID)                                                    \
58350b57cec5SDimitry Andric   LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
58360b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def"
58370b57cec5SDimitry Andric 
58380b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N)
58390b57cec5SDimitry Andric     LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
58400b57cec5SDimitry Andric 
58410b57cec5SDimitry Andric   ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
58420b57cec5SDimitry Andric   VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
58430b57cec5SDimitry Andric   LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
58440b57cec5SDimitry Andric 
58450b57cec5SDimitry Andric   LangOpts.CurrentModule = ReadString(Record, Idx);
58460b57cec5SDimitry Andric 
58470b57cec5SDimitry Andric   // Comment options.
58480b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58490b57cec5SDimitry Andric     LangOpts.CommentOpts.BlockCommandNames.push_back(
58500b57cec5SDimitry Andric       ReadString(Record, Idx));
58510b57cec5SDimitry Andric   }
58520b57cec5SDimitry Andric   LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
58530b57cec5SDimitry Andric 
58540b57cec5SDimitry Andric   // OpenMP offloading options.
58550b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58560b57cec5SDimitry Andric     LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
58570b57cec5SDimitry Andric   }
58580b57cec5SDimitry Andric 
58590b57cec5SDimitry Andric   LangOpts.OMPHostIRFile = ReadString(Record, Idx);
58600b57cec5SDimitry Andric 
58610b57cec5SDimitry Andric   return Listener.ReadLanguageOptions(LangOpts, Complain,
58620b57cec5SDimitry Andric                                       AllowCompatibleDifferences);
58630b57cec5SDimitry Andric }
58640b57cec5SDimitry Andric 
58650b57cec5SDimitry Andric bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
58660b57cec5SDimitry Andric                                    ASTReaderListener &Listener,
58670b57cec5SDimitry Andric                                    bool AllowCompatibleDifferences) {
58680b57cec5SDimitry Andric   unsigned Idx = 0;
58690b57cec5SDimitry Andric   TargetOptions TargetOpts;
58700b57cec5SDimitry Andric   TargetOpts.Triple = ReadString(Record, Idx);
58710b57cec5SDimitry Andric   TargetOpts.CPU = ReadString(Record, Idx);
5872e8d8bef9SDimitry Andric   TargetOpts.TuneCPU = ReadString(Record, Idx);
58730b57cec5SDimitry Andric   TargetOpts.ABI = ReadString(Record, Idx);
58740b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58750b57cec5SDimitry Andric     TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
58760b57cec5SDimitry Andric   }
58770b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
58780b57cec5SDimitry Andric     TargetOpts.Features.push_back(ReadString(Record, Idx));
58790b57cec5SDimitry Andric   }
58800b57cec5SDimitry Andric 
58810b57cec5SDimitry Andric   return Listener.ReadTargetOptions(TargetOpts, Complain,
58820b57cec5SDimitry Andric                                     AllowCompatibleDifferences);
58830b57cec5SDimitry Andric }
58840b57cec5SDimitry Andric 
58850b57cec5SDimitry Andric bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
58860b57cec5SDimitry Andric                                        ASTReaderListener &Listener) {
58870b57cec5SDimitry Andric   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
58880b57cec5SDimitry Andric   unsigned Idx = 0;
58890b57cec5SDimitry Andric #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
58900b57cec5SDimitry Andric #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
58910b57cec5SDimitry Andric   DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
58920b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.def"
58930b57cec5SDimitry Andric 
58940b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N)
58950b57cec5SDimitry Andric     DiagOpts->Warnings.push_back(ReadString(Record, Idx));
58960b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N)
58970b57cec5SDimitry Andric     DiagOpts->Remarks.push_back(ReadString(Record, Idx));
58980b57cec5SDimitry Andric 
58990b57cec5SDimitry Andric   return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
59000b57cec5SDimitry Andric }
59010b57cec5SDimitry Andric 
59020b57cec5SDimitry Andric bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
59030b57cec5SDimitry Andric                                        ASTReaderListener &Listener) {
59040b57cec5SDimitry Andric   FileSystemOptions FSOpts;
59050b57cec5SDimitry Andric   unsigned Idx = 0;
59060b57cec5SDimitry Andric   FSOpts.WorkingDir = ReadString(Record, Idx);
59070b57cec5SDimitry Andric   return Listener.ReadFileSystemOptions(FSOpts, Complain);
59080b57cec5SDimitry Andric }
59090b57cec5SDimitry Andric 
59100b57cec5SDimitry Andric bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
59110b57cec5SDimitry Andric                                          bool Complain,
59120b57cec5SDimitry Andric                                          ASTReaderListener &Listener) {
59130b57cec5SDimitry Andric   HeaderSearchOptions HSOpts;
59140b57cec5SDimitry Andric   unsigned Idx = 0;
59150b57cec5SDimitry Andric   HSOpts.Sysroot = ReadString(Record, Idx);
59160b57cec5SDimitry Andric 
5917*bdd1243dSDimitry Andric   HSOpts.ResourceDir = ReadString(Record, Idx);
5918*bdd1243dSDimitry Andric   HSOpts.ModuleCachePath = ReadString(Record, Idx);
5919*bdd1243dSDimitry Andric   HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
5920*bdd1243dSDimitry Andric   HSOpts.DisableModuleHash = Record[Idx++];
5921*bdd1243dSDimitry Andric   HSOpts.ImplicitModuleMaps = Record[Idx++];
5922*bdd1243dSDimitry Andric   HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
5923*bdd1243dSDimitry Andric   HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
5924*bdd1243dSDimitry Andric   HSOpts.UseBuiltinIncludes = Record[Idx++];
5925*bdd1243dSDimitry Andric   HSOpts.UseStandardSystemIncludes = Record[Idx++];
5926*bdd1243dSDimitry Andric   HSOpts.UseStandardCXXIncludes = Record[Idx++];
5927*bdd1243dSDimitry Andric   HSOpts.UseLibcxx = Record[Idx++];
5928*bdd1243dSDimitry Andric   std::string SpecificModuleCachePath = ReadString(Record, Idx);
5929*bdd1243dSDimitry Andric 
5930*bdd1243dSDimitry Andric   return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5931*bdd1243dSDimitry Andric                                           Complain);
5932*bdd1243dSDimitry Andric }
5933*bdd1243dSDimitry Andric 
5934*bdd1243dSDimitry Andric bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
5935*bdd1243dSDimitry Andric                                        ASTReaderListener &Listener) {
5936*bdd1243dSDimitry Andric   HeaderSearchOptions HSOpts;
5937*bdd1243dSDimitry Andric   unsigned Idx = 0;
5938*bdd1243dSDimitry Andric 
59390b57cec5SDimitry Andric   // Include entries.
59400b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
59410b57cec5SDimitry Andric     std::string Path = ReadString(Record, Idx);
59420b57cec5SDimitry Andric     frontend::IncludeDirGroup Group
59430b57cec5SDimitry Andric       = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
59440b57cec5SDimitry Andric     bool IsFramework = Record[Idx++];
59450b57cec5SDimitry Andric     bool IgnoreSysRoot = Record[Idx++];
59460b57cec5SDimitry Andric     HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
59470b57cec5SDimitry Andric                                     IgnoreSysRoot);
59480b57cec5SDimitry Andric   }
59490b57cec5SDimitry Andric 
59500b57cec5SDimitry Andric   // System header prefixes.
59510b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
59520b57cec5SDimitry Andric     std::string Prefix = ReadString(Record, Idx);
59530b57cec5SDimitry Andric     bool IsSystemHeader = Record[Idx++];
59540b57cec5SDimitry Andric     HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
59550b57cec5SDimitry Andric   }
59560b57cec5SDimitry Andric 
5957*bdd1243dSDimitry Andric   // VFS overlay files.
5958*bdd1243dSDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
5959*bdd1243dSDimitry Andric     std::string VFSOverlayFile = ReadString(Record, Idx);
5960*bdd1243dSDimitry Andric     HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
5961*bdd1243dSDimitry Andric   }
59620b57cec5SDimitry Andric 
5963*bdd1243dSDimitry Andric   return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
59640b57cec5SDimitry Andric }
59650b57cec5SDimitry Andric 
59660b57cec5SDimitry Andric bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
59670b57cec5SDimitry Andric                                          bool Complain,
59680b57cec5SDimitry Andric                                          ASTReaderListener &Listener,
59690b57cec5SDimitry Andric                                          std::string &SuggestedPredefines) {
59700b57cec5SDimitry Andric   PreprocessorOptions PPOpts;
59710b57cec5SDimitry Andric   unsigned Idx = 0;
59720b57cec5SDimitry Andric 
59730b57cec5SDimitry Andric   // Macro definitions/undefs
59740b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
59750b57cec5SDimitry Andric     std::string Macro = ReadString(Record, Idx);
59760b57cec5SDimitry Andric     bool IsUndef = Record[Idx++];
59770b57cec5SDimitry Andric     PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
59780b57cec5SDimitry Andric   }
59790b57cec5SDimitry Andric 
59800b57cec5SDimitry Andric   // Includes
59810b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
59820b57cec5SDimitry Andric     PPOpts.Includes.push_back(ReadString(Record, Idx));
59830b57cec5SDimitry Andric   }
59840b57cec5SDimitry Andric 
59850b57cec5SDimitry Andric   // Macro Includes
59860b57cec5SDimitry Andric   for (unsigned N = Record[Idx++]; N; --N) {
59870b57cec5SDimitry Andric     PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
59880b57cec5SDimitry Andric   }
59890b57cec5SDimitry Andric 
59900b57cec5SDimitry Andric   PPOpts.UsePredefines = Record[Idx++];
59910b57cec5SDimitry Andric   PPOpts.DetailedRecord = Record[Idx++];
59920b57cec5SDimitry Andric   PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
59930b57cec5SDimitry Andric   PPOpts.ObjCXXARCStandardLibrary =
59940b57cec5SDimitry Andric     static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
59950b57cec5SDimitry Andric   SuggestedPredefines.clear();
59960b57cec5SDimitry Andric   return Listener.ReadPreprocessorOptions(PPOpts, Complain,
59970b57cec5SDimitry Andric                                           SuggestedPredefines);
59980b57cec5SDimitry Andric }
59990b57cec5SDimitry Andric 
60000b57cec5SDimitry Andric std::pair<ModuleFile *, unsigned>
60010b57cec5SDimitry Andric ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
60020b57cec5SDimitry Andric   GlobalPreprocessedEntityMapType::iterator
60030b57cec5SDimitry Andric   I = GlobalPreprocessedEntityMap.find(GlobalIndex);
60040b57cec5SDimitry Andric   assert(I != GlobalPreprocessedEntityMap.end() &&
60050b57cec5SDimitry Andric          "Corrupted global preprocessed entity map");
60060b57cec5SDimitry Andric   ModuleFile *M = I->second;
60070b57cec5SDimitry Andric   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
60080b57cec5SDimitry Andric   return std::make_pair(M, LocalIndex);
60090b57cec5SDimitry Andric }
60100b57cec5SDimitry Andric 
60110b57cec5SDimitry Andric llvm::iterator_range<PreprocessingRecord::iterator>
60120b57cec5SDimitry Andric ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
60130b57cec5SDimitry Andric   if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
60140b57cec5SDimitry Andric     return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
60150b57cec5SDimitry Andric                                              Mod.NumPreprocessedEntities);
60160b57cec5SDimitry Andric 
60170b57cec5SDimitry Andric   return llvm::make_range(PreprocessingRecord::iterator(),
60180b57cec5SDimitry Andric                           PreprocessingRecord::iterator());
60190b57cec5SDimitry Andric }
60200b57cec5SDimitry Andric 
6021fe6060f1SDimitry Andric bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
6022fe6060f1SDimitry Andric                                         unsigned int ClientLoadCapabilities) {
6023fe6060f1SDimitry Andric   return ClientLoadCapabilities & ARR_OutOfDate &&
6024fe6060f1SDimitry Andric          !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
6025fe6060f1SDimitry Andric }
6026fe6060f1SDimitry Andric 
60270b57cec5SDimitry Andric llvm::iterator_range<ASTReader::ModuleDeclIterator>
60280b57cec5SDimitry Andric ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
60290b57cec5SDimitry Andric   return llvm::make_range(
60300b57cec5SDimitry Andric       ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
60310b57cec5SDimitry Andric       ModuleDeclIterator(this, &Mod,
60320b57cec5SDimitry Andric                          Mod.FileSortedDecls + Mod.NumFileSortedDecls));
60330b57cec5SDimitry Andric }
60340b57cec5SDimitry Andric 
60350b57cec5SDimitry Andric SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
60360b57cec5SDimitry Andric   auto I = GlobalSkippedRangeMap.find(GlobalIndex);
60370b57cec5SDimitry Andric   assert(I != GlobalSkippedRangeMap.end() &&
60380b57cec5SDimitry Andric     "Corrupted global skipped range map");
60390b57cec5SDimitry Andric   ModuleFile *M = I->second;
60400b57cec5SDimitry Andric   unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
60410b57cec5SDimitry Andric   assert(LocalIndex < M->NumPreprocessedSkippedRanges);
60420b57cec5SDimitry Andric   PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
60430b57cec5SDimitry Andric   SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
60440b57cec5SDimitry Andric                     TranslateSourceLocation(*M, RawRange.getEnd()));
60450b57cec5SDimitry Andric   assert(Range.isValid());
60460b57cec5SDimitry Andric   return Range;
60470b57cec5SDimitry Andric }
60480b57cec5SDimitry Andric 
60490b57cec5SDimitry Andric PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
60500b57cec5SDimitry Andric   PreprocessedEntityID PPID = Index+1;
60510b57cec5SDimitry Andric   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
60520b57cec5SDimitry Andric   ModuleFile &M = *PPInfo.first;
60530b57cec5SDimitry Andric   unsigned LocalIndex = PPInfo.second;
60540b57cec5SDimitry Andric   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
60550b57cec5SDimitry Andric 
60560b57cec5SDimitry Andric   if (!PP.getPreprocessingRecord()) {
60570b57cec5SDimitry Andric     Error("no preprocessing record");
60580b57cec5SDimitry Andric     return nullptr;
60590b57cec5SDimitry Andric   }
60600b57cec5SDimitry Andric 
60610b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
60625ffd83dbSDimitry Andric   if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
60635ffd83dbSDimitry Andric           M.MacroOffsetsBase + PPOffs.BitOffset)) {
60640b57cec5SDimitry Andric     Error(std::move(Err));
60650b57cec5SDimitry Andric     return nullptr;
60660b57cec5SDimitry Andric   }
60670b57cec5SDimitry Andric 
60680b57cec5SDimitry Andric   Expected<llvm::BitstreamEntry> MaybeEntry =
60690b57cec5SDimitry Andric       M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
60700b57cec5SDimitry Andric   if (!MaybeEntry) {
60710b57cec5SDimitry Andric     Error(MaybeEntry.takeError());
60720b57cec5SDimitry Andric     return nullptr;
60730b57cec5SDimitry Andric   }
60740b57cec5SDimitry Andric   llvm::BitstreamEntry Entry = MaybeEntry.get();
60750b57cec5SDimitry Andric 
60760b57cec5SDimitry Andric   if (Entry.Kind != llvm::BitstreamEntry::Record)
60770b57cec5SDimitry Andric     return nullptr;
60780b57cec5SDimitry Andric 
60790b57cec5SDimitry Andric   // Read the record.
60800b57cec5SDimitry Andric   SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
60810b57cec5SDimitry Andric                     TranslateSourceLocation(M, PPOffs.getEnd()));
60820b57cec5SDimitry Andric   PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
60830b57cec5SDimitry Andric   StringRef Blob;
60840b57cec5SDimitry Andric   RecordData Record;
60850b57cec5SDimitry Andric   Expected<unsigned> MaybeRecType =
60860b57cec5SDimitry Andric       M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
60870b57cec5SDimitry Andric   if (!MaybeRecType) {
60880b57cec5SDimitry Andric     Error(MaybeRecType.takeError());
60890b57cec5SDimitry Andric     return nullptr;
60900b57cec5SDimitry Andric   }
60910b57cec5SDimitry Andric   switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
60920b57cec5SDimitry Andric   case PPD_MACRO_EXPANSION: {
60930b57cec5SDimitry Andric     bool isBuiltin = Record[0];
60940b57cec5SDimitry Andric     IdentifierInfo *Name = nullptr;
60950b57cec5SDimitry Andric     MacroDefinitionRecord *Def = nullptr;
60960b57cec5SDimitry Andric     if (isBuiltin)
60970b57cec5SDimitry Andric       Name = getLocalIdentifier(M, Record[1]);
60980b57cec5SDimitry Andric     else {
60990b57cec5SDimitry Andric       PreprocessedEntityID GlobalID =
61000b57cec5SDimitry Andric           getGlobalPreprocessedEntityID(M, Record[1]);
61010b57cec5SDimitry Andric       Def = cast<MacroDefinitionRecord>(
61020b57cec5SDimitry Andric           PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
61030b57cec5SDimitry Andric     }
61040b57cec5SDimitry Andric 
61050b57cec5SDimitry Andric     MacroExpansion *ME;
61060b57cec5SDimitry Andric     if (isBuiltin)
61070b57cec5SDimitry Andric       ME = new (PPRec) MacroExpansion(Name, Range);
61080b57cec5SDimitry Andric     else
61090b57cec5SDimitry Andric       ME = new (PPRec) MacroExpansion(Def, Range);
61100b57cec5SDimitry Andric 
61110b57cec5SDimitry Andric     return ME;
61120b57cec5SDimitry Andric   }
61130b57cec5SDimitry Andric 
61140b57cec5SDimitry Andric   case PPD_MACRO_DEFINITION: {
61150b57cec5SDimitry Andric     // Decode the identifier info and then check again; if the macro is
61160b57cec5SDimitry Andric     // still defined and associated with the identifier,
61170b57cec5SDimitry Andric     IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
61180b57cec5SDimitry Andric     MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
61190b57cec5SDimitry Andric 
61200b57cec5SDimitry Andric     if (DeserializationListener)
61210b57cec5SDimitry Andric       DeserializationListener->MacroDefinitionRead(PPID, MD);
61220b57cec5SDimitry Andric 
61230b57cec5SDimitry Andric     return MD;
61240b57cec5SDimitry Andric   }
61250b57cec5SDimitry Andric 
61260b57cec5SDimitry Andric   case PPD_INCLUSION_DIRECTIVE: {
61270b57cec5SDimitry Andric     const char *FullFileNameStart = Blob.data() + Record[0];
61280b57cec5SDimitry Andric     StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
6129*bdd1243dSDimitry Andric     OptionalFileEntryRef File;
61300b57cec5SDimitry Andric     if (!FullFileName.empty())
613181ad6265SDimitry Andric       File = PP.getFileManager().getOptionalFileRef(FullFileName);
61320b57cec5SDimitry Andric 
61330b57cec5SDimitry Andric     // FIXME: Stable encoding
61340b57cec5SDimitry Andric     InclusionDirective::InclusionKind Kind
61350b57cec5SDimitry Andric       = static_cast<InclusionDirective::InclusionKind>(Record[2]);
61360b57cec5SDimitry Andric     InclusionDirective *ID
61370b57cec5SDimitry Andric       = new (PPRec) InclusionDirective(PPRec, Kind,
61380b57cec5SDimitry Andric                                        StringRef(Blob.data(), Record[0]),
61390b57cec5SDimitry Andric                                        Record[1], Record[3],
61400b57cec5SDimitry Andric                                        File,
61410b57cec5SDimitry Andric                                        Range);
61420b57cec5SDimitry Andric     return ID;
61430b57cec5SDimitry Andric   }
61440b57cec5SDimitry Andric   }
61450b57cec5SDimitry Andric 
61460b57cec5SDimitry Andric   llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
61470b57cec5SDimitry Andric }
61480b57cec5SDimitry Andric 
61490b57cec5SDimitry Andric /// Find the next module that contains entities and return the ID
61500b57cec5SDimitry Andric /// of the first entry.
61510b57cec5SDimitry Andric ///
61520b57cec5SDimitry Andric /// \param SLocMapI points at a chunk of a module that contains no
61530b57cec5SDimitry Andric /// preprocessed entities or the entities it contains are not the ones we are
61540b57cec5SDimitry Andric /// looking for.
61550b57cec5SDimitry Andric PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
61560b57cec5SDimitry Andric                        GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
61570b57cec5SDimitry Andric   ++SLocMapI;
61580b57cec5SDimitry Andric   for (GlobalSLocOffsetMapType::const_iterator
61590b57cec5SDimitry Andric          EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
61600b57cec5SDimitry Andric     ModuleFile &M = *SLocMapI->second;
61610b57cec5SDimitry Andric     if (M.NumPreprocessedEntities)
61620b57cec5SDimitry Andric       return M.BasePreprocessedEntityID;
61630b57cec5SDimitry Andric   }
61640b57cec5SDimitry Andric 
61650b57cec5SDimitry Andric   return getTotalNumPreprocessedEntities();
61660b57cec5SDimitry Andric }
61670b57cec5SDimitry Andric 
61680b57cec5SDimitry Andric namespace {
61690b57cec5SDimitry Andric 
61700b57cec5SDimitry Andric struct PPEntityComp {
61710b57cec5SDimitry Andric   const ASTReader &Reader;
61720b57cec5SDimitry Andric   ModuleFile &M;
61730b57cec5SDimitry Andric 
61740b57cec5SDimitry Andric   PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
61750b57cec5SDimitry Andric 
61760b57cec5SDimitry Andric   bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
61770b57cec5SDimitry Andric     SourceLocation LHS = getLoc(L);
61780b57cec5SDimitry Andric     SourceLocation RHS = getLoc(R);
61790b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
61800b57cec5SDimitry Andric   }
61810b57cec5SDimitry Andric 
61820b57cec5SDimitry Andric   bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
61830b57cec5SDimitry Andric     SourceLocation LHS = getLoc(L);
61840b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
61850b57cec5SDimitry Andric   }
61860b57cec5SDimitry Andric 
61870b57cec5SDimitry Andric   bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
61880b57cec5SDimitry Andric     SourceLocation RHS = getLoc(R);
61890b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
61900b57cec5SDimitry Andric   }
61910b57cec5SDimitry Andric 
61920b57cec5SDimitry Andric   SourceLocation getLoc(const PPEntityOffset &PPE) const {
61930b57cec5SDimitry Andric     return Reader.TranslateSourceLocation(M, PPE.getBegin());
61940b57cec5SDimitry Andric   }
61950b57cec5SDimitry Andric };
61960b57cec5SDimitry Andric 
61970b57cec5SDimitry Andric } // namespace
61980b57cec5SDimitry Andric 
61990b57cec5SDimitry Andric PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
62000b57cec5SDimitry Andric                                                        bool EndsAfter) const {
62010b57cec5SDimitry Andric   if (SourceMgr.isLocalSourceLocation(Loc))
62020b57cec5SDimitry Andric     return getTotalNumPreprocessedEntities();
62030b57cec5SDimitry Andric 
62040b57cec5SDimitry Andric   GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
62050b57cec5SDimitry Andric       SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
62060b57cec5SDimitry Andric   assert(SLocMapI != GlobalSLocOffsetMap.end() &&
62070b57cec5SDimitry Andric          "Corrupted global sloc offset map");
62080b57cec5SDimitry Andric 
62090b57cec5SDimitry Andric   if (SLocMapI->second->NumPreprocessedEntities == 0)
62100b57cec5SDimitry Andric     return findNextPreprocessedEntity(SLocMapI);
62110b57cec5SDimitry Andric 
62120b57cec5SDimitry Andric   ModuleFile &M = *SLocMapI->second;
62130b57cec5SDimitry Andric 
62140b57cec5SDimitry Andric   using pp_iterator = const PPEntityOffset *;
62150b57cec5SDimitry Andric 
62160b57cec5SDimitry Andric   pp_iterator pp_begin = M.PreprocessedEntityOffsets;
62170b57cec5SDimitry Andric   pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
62180b57cec5SDimitry Andric 
62190b57cec5SDimitry Andric   size_t Count = M.NumPreprocessedEntities;
62200b57cec5SDimitry Andric   size_t Half;
62210b57cec5SDimitry Andric   pp_iterator First = pp_begin;
62220b57cec5SDimitry Andric   pp_iterator PPI;
62230b57cec5SDimitry Andric 
62240b57cec5SDimitry Andric   if (EndsAfter) {
62250b57cec5SDimitry Andric     PPI = std::upper_bound(pp_begin, pp_end, Loc,
62260b57cec5SDimitry Andric                            PPEntityComp(*this, M));
62270b57cec5SDimitry Andric   } else {
62280b57cec5SDimitry Andric     // Do a binary search manually instead of using std::lower_bound because
62290b57cec5SDimitry Andric     // The end locations of entities may be unordered (when a macro expansion
62300b57cec5SDimitry Andric     // is inside another macro argument), but for this case it is not important
62310b57cec5SDimitry Andric     // whether we get the first macro expansion or its containing macro.
62320b57cec5SDimitry Andric     while (Count > 0) {
62330b57cec5SDimitry Andric       Half = Count / 2;
62340b57cec5SDimitry Andric       PPI = First;
62350b57cec5SDimitry Andric       std::advance(PPI, Half);
62360b57cec5SDimitry Andric       if (SourceMgr.isBeforeInTranslationUnit(
62370b57cec5SDimitry Andric               TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
62380b57cec5SDimitry Andric         First = PPI;
62390b57cec5SDimitry Andric         ++First;
62400b57cec5SDimitry Andric         Count = Count - Half - 1;
62410b57cec5SDimitry Andric       } else
62420b57cec5SDimitry Andric         Count = Half;
62430b57cec5SDimitry Andric     }
62440b57cec5SDimitry Andric   }
62450b57cec5SDimitry Andric 
62460b57cec5SDimitry Andric   if (PPI == pp_end)
62470b57cec5SDimitry Andric     return findNextPreprocessedEntity(SLocMapI);
62480b57cec5SDimitry Andric 
62490b57cec5SDimitry Andric   return M.BasePreprocessedEntityID + (PPI - pp_begin);
62500b57cec5SDimitry Andric }
62510b57cec5SDimitry Andric 
62520b57cec5SDimitry Andric /// Returns a pair of [Begin, End) indices of preallocated
62530b57cec5SDimitry Andric /// preprocessed entities that \arg Range encompasses.
62540b57cec5SDimitry Andric std::pair<unsigned, unsigned>
62550b57cec5SDimitry Andric     ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
62560b57cec5SDimitry Andric   if (Range.isInvalid())
62570b57cec5SDimitry Andric     return std::make_pair(0,0);
62580b57cec5SDimitry Andric   assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
62590b57cec5SDimitry Andric 
62600b57cec5SDimitry Andric   PreprocessedEntityID BeginID =
62610b57cec5SDimitry Andric       findPreprocessedEntity(Range.getBegin(), false);
62620b57cec5SDimitry Andric   PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
62630b57cec5SDimitry Andric   return std::make_pair(BeginID, EndID);
62640b57cec5SDimitry Andric }
62650b57cec5SDimitry Andric 
62660b57cec5SDimitry Andric /// Optionally returns true or false if the preallocated preprocessed
62670b57cec5SDimitry Andric /// entity with index \arg Index came from file \arg FID.
6268*bdd1243dSDimitry Andric std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
62690b57cec5SDimitry Andric                                                             FileID FID) {
62700b57cec5SDimitry Andric   if (FID.isInvalid())
62710b57cec5SDimitry Andric     return false;
62720b57cec5SDimitry Andric 
62730b57cec5SDimitry Andric   std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
62740b57cec5SDimitry Andric   ModuleFile &M = *PPInfo.first;
62750b57cec5SDimitry Andric   unsigned LocalIndex = PPInfo.second;
62760b57cec5SDimitry Andric   const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
62770b57cec5SDimitry Andric 
62780b57cec5SDimitry Andric   SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
62790b57cec5SDimitry Andric   if (Loc.isInvalid())
62800b57cec5SDimitry Andric     return false;
62810b57cec5SDimitry Andric 
62820b57cec5SDimitry Andric   if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
62830b57cec5SDimitry Andric     return true;
62840b57cec5SDimitry Andric   else
62850b57cec5SDimitry Andric     return false;
62860b57cec5SDimitry Andric }
62870b57cec5SDimitry Andric 
62880b57cec5SDimitry Andric namespace {
62890b57cec5SDimitry Andric 
62900b57cec5SDimitry Andric   /// Visitor used to search for information about a header file.
62910b57cec5SDimitry Andric   class HeaderFileInfoVisitor {
62920b57cec5SDimitry Andric     const FileEntry *FE;
6293*bdd1243dSDimitry Andric     std::optional<HeaderFileInfo> HFI;
62940b57cec5SDimitry Andric 
62950b57cec5SDimitry Andric   public:
62960b57cec5SDimitry Andric     explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
62970b57cec5SDimitry Andric 
62980b57cec5SDimitry Andric     bool operator()(ModuleFile &M) {
62990b57cec5SDimitry Andric       HeaderFileInfoLookupTable *Table
63000b57cec5SDimitry Andric         = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
63010b57cec5SDimitry Andric       if (!Table)
63020b57cec5SDimitry Andric         return false;
63030b57cec5SDimitry Andric 
63040b57cec5SDimitry Andric       // Look in the on-disk hash table for an entry for this file name.
63050b57cec5SDimitry Andric       HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
63060b57cec5SDimitry Andric       if (Pos == Table->end())
63070b57cec5SDimitry Andric         return false;
63080b57cec5SDimitry Andric 
63090b57cec5SDimitry Andric       HFI = *Pos;
63100b57cec5SDimitry Andric       return true;
63110b57cec5SDimitry Andric     }
63120b57cec5SDimitry Andric 
6313*bdd1243dSDimitry Andric     std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
63140b57cec5SDimitry Andric   };
63150b57cec5SDimitry Andric 
63160b57cec5SDimitry Andric } // namespace
63170b57cec5SDimitry Andric 
63180b57cec5SDimitry Andric HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
63190b57cec5SDimitry Andric   HeaderFileInfoVisitor Visitor(FE);
63200b57cec5SDimitry Andric   ModuleMgr.visit(Visitor);
6321*bdd1243dSDimitry Andric   if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
63220b57cec5SDimitry Andric       return *HFI;
63230b57cec5SDimitry Andric 
63240b57cec5SDimitry Andric   return HeaderFileInfo();
63250b57cec5SDimitry Andric }
63260b57cec5SDimitry Andric 
63270b57cec5SDimitry Andric void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
63280b57cec5SDimitry Andric   using DiagState = DiagnosticsEngine::DiagState;
63290b57cec5SDimitry Andric   SmallVector<DiagState *, 32> DiagStates;
63300b57cec5SDimitry Andric 
63310b57cec5SDimitry Andric   for (ModuleFile &F : ModuleMgr) {
63320b57cec5SDimitry Andric     unsigned Idx = 0;
63330b57cec5SDimitry Andric     auto &Record = F.PragmaDiagMappings;
63340b57cec5SDimitry Andric     if (Record.empty())
63350b57cec5SDimitry Andric       continue;
63360b57cec5SDimitry Andric 
63370b57cec5SDimitry Andric     DiagStates.clear();
63380b57cec5SDimitry Andric 
6339*bdd1243dSDimitry Andric     auto ReadDiagState = [&](const DiagState &BasedOn,
6340*bdd1243dSDimitry Andric                              bool IncludeNonPragmaStates) {
63410b57cec5SDimitry Andric       unsigned BackrefID = Record[Idx++];
63420b57cec5SDimitry Andric       if (BackrefID != 0)
63430b57cec5SDimitry Andric         return DiagStates[BackrefID - 1];
63440b57cec5SDimitry Andric 
63450b57cec5SDimitry Andric       // A new DiagState was created here.
63460b57cec5SDimitry Andric       Diag.DiagStates.push_back(BasedOn);
63470b57cec5SDimitry Andric       DiagState *NewState = &Diag.DiagStates.back();
63480b57cec5SDimitry Andric       DiagStates.push_back(NewState);
63490b57cec5SDimitry Andric       unsigned Size = Record[Idx++];
63500b57cec5SDimitry Andric       assert(Idx + Size * 2 <= Record.size() &&
63510b57cec5SDimitry Andric              "Invalid data, not enough diag/map pairs");
63520b57cec5SDimitry Andric       while (Size--) {
63530b57cec5SDimitry Andric         unsigned DiagID = Record[Idx++];
63540b57cec5SDimitry Andric         DiagnosticMapping NewMapping =
63550b57cec5SDimitry Andric             DiagnosticMapping::deserialize(Record[Idx++]);
63560b57cec5SDimitry Andric         if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
63570b57cec5SDimitry Andric           continue;
63580b57cec5SDimitry Andric 
63590b57cec5SDimitry Andric         DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
63600b57cec5SDimitry Andric 
63610b57cec5SDimitry Andric         // If this mapping was specified as a warning but the severity was
63620b57cec5SDimitry Andric         // upgraded due to diagnostic settings, simulate the current diagnostic
63630b57cec5SDimitry Andric         // settings (and use a warning).
63640b57cec5SDimitry Andric         if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
63650b57cec5SDimitry Andric           NewMapping.setSeverity(diag::Severity::Warning);
63660b57cec5SDimitry Andric           NewMapping.setUpgradedFromWarning(false);
63670b57cec5SDimitry Andric         }
63680b57cec5SDimitry Andric 
63690b57cec5SDimitry Andric         Mapping = NewMapping;
63700b57cec5SDimitry Andric       }
63710b57cec5SDimitry Andric       return NewState;
63720b57cec5SDimitry Andric     };
63730b57cec5SDimitry Andric 
63740b57cec5SDimitry Andric     // Read the first state.
63750b57cec5SDimitry Andric     DiagState *FirstState;
63760b57cec5SDimitry Andric     if (F.Kind == MK_ImplicitModule) {
63770b57cec5SDimitry Andric       // Implicitly-built modules are reused with different diagnostic
63780b57cec5SDimitry Andric       // settings.  Use the initial diagnostic state from Diag to simulate this
63790b57cec5SDimitry Andric       // compilation's diagnostic settings.
63800b57cec5SDimitry Andric       FirstState = Diag.DiagStatesByLoc.FirstDiagState;
63810b57cec5SDimitry Andric       DiagStates.push_back(FirstState);
63820b57cec5SDimitry Andric 
63830b57cec5SDimitry Andric       // Skip the initial diagnostic state from the serialized module.
63840b57cec5SDimitry Andric       assert(Record[1] == 0 &&
63850b57cec5SDimitry Andric              "Invalid data, unexpected backref in initial state");
63860b57cec5SDimitry Andric       Idx = 3 + Record[2] * 2;
63870b57cec5SDimitry Andric       assert(Idx < Record.size() &&
63880b57cec5SDimitry Andric              "Invalid data, not enough state change pairs in initial state");
63890b57cec5SDimitry Andric     } else if (F.isModule()) {
63900b57cec5SDimitry Andric       // For an explicit module, preserve the flags from the module build
63910b57cec5SDimitry Andric       // command line (-w, -Weverything, -Werror, ...) along with any explicit
63920b57cec5SDimitry Andric       // -Wblah flags.
63930b57cec5SDimitry Andric       unsigned Flags = Record[Idx++];
63940b57cec5SDimitry Andric       DiagState Initial;
63950b57cec5SDimitry Andric       Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
63960b57cec5SDimitry Andric       Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
63970b57cec5SDimitry Andric       Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
63980b57cec5SDimitry Andric       Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
63990b57cec5SDimitry Andric       Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
64000b57cec5SDimitry Andric       Initial.ExtBehavior = (diag::Severity)Flags;
6401*bdd1243dSDimitry Andric       FirstState = ReadDiagState(Initial, true);
64020b57cec5SDimitry Andric 
64030b57cec5SDimitry Andric       assert(F.OriginalSourceFileID.isValid());
64040b57cec5SDimitry Andric 
64050b57cec5SDimitry Andric       // Set up the root buffer of the module to start with the initial
64060b57cec5SDimitry Andric       // diagnostic state of the module itself, to cover files that contain no
64070b57cec5SDimitry Andric       // explicit transitions (for which we did not serialize anything).
64080b57cec5SDimitry Andric       Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
64090b57cec5SDimitry Andric           .StateTransitions.push_back({FirstState, 0});
64100b57cec5SDimitry Andric     } else {
64110b57cec5SDimitry Andric       // For prefix ASTs, start with whatever the user configured on the
64120b57cec5SDimitry Andric       // command line.
64130b57cec5SDimitry Andric       Idx++; // Skip flags.
6414*bdd1243dSDimitry Andric       FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
64150b57cec5SDimitry Andric     }
64160b57cec5SDimitry Andric 
64170b57cec5SDimitry Andric     // Read the state transitions.
64180b57cec5SDimitry Andric     unsigned NumLocations = Record[Idx++];
64190b57cec5SDimitry Andric     while (NumLocations--) {
64200b57cec5SDimitry Andric       assert(Idx < Record.size() &&
64210b57cec5SDimitry Andric              "Invalid data, missing pragma diagnostic states");
64220b57cec5SDimitry Andric       SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
64230b57cec5SDimitry Andric       auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
64240b57cec5SDimitry Andric       assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
64250b57cec5SDimitry Andric       assert(IDAndOffset.second == 0 && "not a start location for a FileID");
64260b57cec5SDimitry Andric       unsigned Transitions = Record[Idx++];
64270b57cec5SDimitry Andric 
64280b57cec5SDimitry Andric       // Note that we don't need to set up Parent/ParentOffset here, because
64290b57cec5SDimitry Andric       // we won't be changing the diagnostic state within imported FileIDs
64300b57cec5SDimitry Andric       // (other than perhaps appending to the main source file, which has no
64310b57cec5SDimitry Andric       // parent).
64320b57cec5SDimitry Andric       auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
64330b57cec5SDimitry Andric       F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
64340b57cec5SDimitry Andric       for (unsigned I = 0; I != Transitions; ++I) {
64350b57cec5SDimitry Andric         unsigned Offset = Record[Idx++];
6436*bdd1243dSDimitry Andric         auto *State = ReadDiagState(*FirstState, false);
64370b57cec5SDimitry Andric         F.StateTransitions.push_back({State, Offset});
64380b57cec5SDimitry Andric       }
64390b57cec5SDimitry Andric     }
64400b57cec5SDimitry Andric 
64410b57cec5SDimitry Andric     // Read the final state.
64420b57cec5SDimitry Andric     assert(Idx < Record.size() &&
64430b57cec5SDimitry Andric            "Invalid data, missing final pragma diagnostic state");
64440b57cec5SDimitry Andric     SourceLocation CurStateLoc =
64450b57cec5SDimitry Andric         ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6446*bdd1243dSDimitry Andric     auto *CurState = ReadDiagState(*FirstState, false);
64470b57cec5SDimitry Andric 
64480b57cec5SDimitry Andric     if (!F.isModule()) {
64490b57cec5SDimitry Andric       Diag.DiagStatesByLoc.CurDiagState = CurState;
64500b57cec5SDimitry Andric       Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
64510b57cec5SDimitry Andric 
64520b57cec5SDimitry Andric       // Preserve the property that the imaginary root file describes the
64530b57cec5SDimitry Andric       // current state.
64540b57cec5SDimitry Andric       FileID NullFile;
64550b57cec5SDimitry Andric       auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
64560b57cec5SDimitry Andric       if (T.empty())
64570b57cec5SDimitry Andric         T.push_back({CurState, 0});
64580b57cec5SDimitry Andric       else
64590b57cec5SDimitry Andric         T[0].State = CurState;
64600b57cec5SDimitry Andric     }
64610b57cec5SDimitry Andric 
64620b57cec5SDimitry Andric     // Don't try to read these mappings again.
64630b57cec5SDimitry Andric     Record.clear();
64640b57cec5SDimitry Andric   }
64650b57cec5SDimitry Andric }
64660b57cec5SDimitry Andric 
64670b57cec5SDimitry Andric /// Get the correct cursor and offset for loading a type.
64680b57cec5SDimitry Andric ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
64690b57cec5SDimitry Andric   GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
64700b57cec5SDimitry Andric   assert(I != GlobalTypeMap.end() && "Corrupted global type map");
64710b57cec5SDimitry Andric   ModuleFile *M = I->second;
64725ffd83dbSDimitry Andric   return RecordLocation(
64735ffd83dbSDimitry Andric       M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
64745ffd83dbSDimitry Andric              M->DeclsBlockStartOffset);
64750b57cec5SDimitry Andric }
64760b57cec5SDimitry Andric 
6477*bdd1243dSDimitry Andric static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6478480093f4SDimitry Andric   switch (code) {
6479480093f4SDimitry Andric #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6480480093f4SDimitry Andric   case TYPE_##CODE_ID: return Type::CLASS_ID;
6481480093f4SDimitry Andric #include "clang/Serialization/TypeBitCodes.def"
6482*bdd1243dSDimitry Andric   default:
6483*bdd1243dSDimitry Andric     return std::nullopt;
6484480093f4SDimitry Andric   }
6485480093f4SDimitry Andric }
6486480093f4SDimitry Andric 
64870b57cec5SDimitry Andric /// Read and return the type with the given index..
64880b57cec5SDimitry Andric ///
64890b57cec5SDimitry Andric /// The index is the type ID, shifted and minus the number of predefs. This
64900b57cec5SDimitry Andric /// routine actually reads the record corresponding to the type at the given
64910b57cec5SDimitry Andric /// location. It is a helper routine for GetType, which deals with reading type
64920b57cec5SDimitry Andric /// IDs.
64930b57cec5SDimitry Andric QualType ASTReader::readTypeRecord(unsigned Index) {
64940b57cec5SDimitry Andric   assert(ContextObj && "reading type with no AST context");
64950b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
64960b57cec5SDimitry Andric   RecordLocation Loc = TypeCursorForIndex(Index);
64970b57cec5SDimitry Andric   BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
64980b57cec5SDimitry Andric 
64990b57cec5SDimitry Andric   // Keep track of where we are in the stream, then jump back there
65000b57cec5SDimitry Andric   // after reading this type.
65010b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(DeclsCursor);
65020b57cec5SDimitry Andric 
65030b57cec5SDimitry Andric   ReadingKindTracker ReadingKind(Read_Type, *this);
65040b57cec5SDimitry Andric 
65050b57cec5SDimitry Andric   // Note that we are loading a type record.
65060b57cec5SDimitry Andric   Deserializing AType(this);
65070b57cec5SDimitry Andric 
65080b57cec5SDimitry Andric   if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
65090b57cec5SDimitry Andric     Error(std::move(Err));
65100b57cec5SDimitry Andric     return QualType();
65110b57cec5SDimitry Andric   }
6512480093f4SDimitry Andric   Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6513480093f4SDimitry Andric   if (!RawCode) {
6514480093f4SDimitry Andric     Error(RawCode.takeError());
65150b57cec5SDimitry Andric     return QualType();
65160b57cec5SDimitry Andric   }
65170b57cec5SDimitry Andric 
6518480093f4SDimitry Andric   ASTRecordReader Record(*this, *Loc.F);
6519480093f4SDimitry Andric   Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6520480093f4SDimitry Andric   if (!Code) {
6521480093f4SDimitry Andric     Error(Code.takeError());
6522480093f4SDimitry Andric     return QualType();
6523480093f4SDimitry Andric   }
6524480093f4SDimitry Andric   if (Code.get() == TYPE_EXT_QUAL) {
6525480093f4SDimitry Andric     QualType baseType = Record.readQualType();
6526480093f4SDimitry Andric     Qualifiers quals = Record.readQualifiers();
6527480093f4SDimitry Andric     return Context.getQualifiedType(baseType, quals);
65280b57cec5SDimitry Andric   }
65290b57cec5SDimitry Andric 
6530480093f4SDimitry Andric   auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6531480093f4SDimitry Andric   if (!maybeClass) {
6532480093f4SDimitry Andric     Error("Unexpected code for type");
65330b57cec5SDimitry Andric     return QualType();
65340b57cec5SDimitry Andric   }
65350b57cec5SDimitry Andric 
6536480093f4SDimitry Andric   serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6537480093f4SDimitry Andric   return TypeReader.read(*maybeClass);
65380b57cec5SDimitry Andric }
65390b57cec5SDimitry Andric 
65400b57cec5SDimitry Andric namespace clang {
65410b57cec5SDimitry Andric 
65420b57cec5SDimitry Andric class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
654381ad6265SDimitry Andric   using LocSeq = SourceLocationSequence;
65440b57cec5SDimitry Andric 
654581ad6265SDimitry Andric   ASTRecordReader &Reader;
654681ad6265SDimitry Andric   LocSeq *Seq;
654781ad6265SDimitry Andric 
654881ad6265SDimitry Andric   SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
654981ad6265SDimitry Andric   SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
65500b57cec5SDimitry Andric 
65510b57cec5SDimitry Andric   TypeSourceInfo *GetTypeSourceInfo() {
6552480093f4SDimitry Andric     return Reader.readTypeSourceInfo();
65530b57cec5SDimitry Andric   }
65540b57cec5SDimitry Andric 
65550b57cec5SDimitry Andric   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6556480093f4SDimitry Andric     return Reader.readNestedNameSpecifierLoc();
65570b57cec5SDimitry Andric   }
65580b57cec5SDimitry Andric 
65590b57cec5SDimitry Andric   Attr *ReadAttr() {
6560480093f4SDimitry Andric     return Reader.readAttr();
65610b57cec5SDimitry Andric   }
65620b57cec5SDimitry Andric 
65630b57cec5SDimitry Andric public:
656481ad6265SDimitry Andric   TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
656581ad6265SDimitry Andric       : Reader(Reader), Seq(Seq) {}
65660b57cec5SDimitry Andric 
65670b57cec5SDimitry Andric   // We want compile-time assurance that we've enumerated all of
65680b57cec5SDimitry Andric   // these, so unfortunately we have to declare them first, then
65690b57cec5SDimitry Andric   // define them out-of-line.
65700b57cec5SDimitry Andric #define ABSTRACT_TYPELOC(CLASS, PARENT)
65710b57cec5SDimitry Andric #define TYPELOC(CLASS, PARENT) \
65720b57cec5SDimitry Andric   void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
65730b57cec5SDimitry Andric #include "clang/AST/TypeLocNodes.def"
65740b57cec5SDimitry Andric 
65750b57cec5SDimitry Andric   void VisitFunctionTypeLoc(FunctionTypeLoc);
65760b57cec5SDimitry Andric   void VisitArrayTypeLoc(ArrayTypeLoc);
65770b57cec5SDimitry Andric };
65780b57cec5SDimitry Andric 
65790b57cec5SDimitry Andric } // namespace clang
65800b57cec5SDimitry Andric 
65810b57cec5SDimitry Andric void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
65820b57cec5SDimitry Andric   // nothing to do
65830b57cec5SDimitry Andric }
65840b57cec5SDimitry Andric 
65850b57cec5SDimitry Andric void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6586480093f4SDimitry Andric   TL.setBuiltinLoc(readSourceLocation());
65870b57cec5SDimitry Andric   if (TL.needsExtraLocalData()) {
6588480093f4SDimitry Andric     TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6589e8d8bef9SDimitry Andric     TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
6590e8d8bef9SDimitry Andric     TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
6591480093f4SDimitry Andric     TL.setModeAttr(Reader.readInt());
65920b57cec5SDimitry Andric   }
65930b57cec5SDimitry Andric }
65940b57cec5SDimitry Andric 
65950b57cec5SDimitry Andric void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
6596480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
65970b57cec5SDimitry Andric }
65980b57cec5SDimitry Andric 
65990b57cec5SDimitry Andric void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
6600480093f4SDimitry Andric   TL.setStarLoc(readSourceLocation());
66010b57cec5SDimitry Andric }
66020b57cec5SDimitry Andric 
66030b57cec5SDimitry Andric void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
66040b57cec5SDimitry Andric   // nothing to do
66050b57cec5SDimitry Andric }
66060b57cec5SDimitry Andric 
66070b57cec5SDimitry Andric void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
66080b57cec5SDimitry Andric   // nothing to do
66090b57cec5SDimitry Andric }
66100b57cec5SDimitry Andric 
66110b57cec5SDimitry Andric void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6612480093f4SDimitry Andric   TL.setExpansionLoc(readSourceLocation());
66130b57cec5SDimitry Andric }
66140b57cec5SDimitry Andric 
66150b57cec5SDimitry Andric void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6616480093f4SDimitry Andric   TL.setCaretLoc(readSourceLocation());
66170b57cec5SDimitry Andric }
66180b57cec5SDimitry Andric 
66190b57cec5SDimitry Andric void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6620480093f4SDimitry Andric   TL.setAmpLoc(readSourceLocation());
66210b57cec5SDimitry Andric }
66220b57cec5SDimitry Andric 
66230b57cec5SDimitry Andric void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6624480093f4SDimitry Andric   TL.setAmpAmpLoc(readSourceLocation());
66250b57cec5SDimitry Andric }
66260b57cec5SDimitry Andric 
66270b57cec5SDimitry Andric void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6628480093f4SDimitry Andric   TL.setStarLoc(readSourceLocation());
66290b57cec5SDimitry Andric   TL.setClassTInfo(GetTypeSourceInfo());
66300b57cec5SDimitry Andric }
66310b57cec5SDimitry Andric 
66320b57cec5SDimitry Andric void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
6633480093f4SDimitry Andric   TL.setLBracketLoc(readSourceLocation());
6634480093f4SDimitry Andric   TL.setRBracketLoc(readSourceLocation());
6635480093f4SDimitry Andric   if (Reader.readBool())
6636480093f4SDimitry Andric     TL.setSizeExpr(Reader.readExpr());
66370b57cec5SDimitry Andric   else
66380b57cec5SDimitry Andric     TL.setSizeExpr(nullptr);
66390b57cec5SDimitry Andric }
66400b57cec5SDimitry Andric 
66410b57cec5SDimitry Andric void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
66420b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
66430b57cec5SDimitry Andric }
66440b57cec5SDimitry Andric 
66450b57cec5SDimitry Andric void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
66460b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
66470b57cec5SDimitry Andric }
66480b57cec5SDimitry Andric 
66490b57cec5SDimitry Andric void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
66500b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
66510b57cec5SDimitry Andric }
66520b57cec5SDimitry Andric 
66530b57cec5SDimitry Andric void TypeLocReader::VisitDependentSizedArrayTypeLoc(
66540b57cec5SDimitry Andric                                             DependentSizedArrayTypeLoc TL) {
66550b57cec5SDimitry Andric   VisitArrayTypeLoc(TL);
66560b57cec5SDimitry Andric }
66570b57cec5SDimitry Andric 
66580b57cec5SDimitry Andric void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
66590b57cec5SDimitry Andric     DependentAddressSpaceTypeLoc TL) {
66600b57cec5SDimitry Andric 
6661480093f4SDimitry Andric     TL.setAttrNameLoc(readSourceLocation());
666281ad6265SDimitry Andric     TL.setAttrOperandParensRange(readSourceRange());
6663480093f4SDimitry Andric     TL.setAttrExprOperand(Reader.readExpr());
66640b57cec5SDimitry Andric }
66650b57cec5SDimitry Andric 
66660b57cec5SDimitry Andric void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
66670b57cec5SDimitry Andric                                         DependentSizedExtVectorTypeLoc TL) {
6668480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66690b57cec5SDimitry Andric }
66700b57cec5SDimitry Andric 
66710b57cec5SDimitry Andric void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
6672480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66730b57cec5SDimitry Andric }
66740b57cec5SDimitry Andric 
66750b57cec5SDimitry Andric void TypeLocReader::VisitDependentVectorTypeLoc(
66760b57cec5SDimitry Andric     DependentVectorTypeLoc TL) {
6677480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66780b57cec5SDimitry Andric }
66790b57cec5SDimitry Andric 
66800b57cec5SDimitry Andric void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6681480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
66820b57cec5SDimitry Andric }
66830b57cec5SDimitry Andric 
66845ffd83dbSDimitry Andric void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
66855ffd83dbSDimitry Andric   TL.setAttrNameLoc(readSourceLocation());
668681ad6265SDimitry Andric   TL.setAttrOperandParensRange(readSourceRange());
66875ffd83dbSDimitry Andric   TL.setAttrRowOperand(Reader.readExpr());
66885ffd83dbSDimitry Andric   TL.setAttrColumnOperand(Reader.readExpr());
66895ffd83dbSDimitry Andric }
66905ffd83dbSDimitry Andric 
66915ffd83dbSDimitry Andric void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
66925ffd83dbSDimitry Andric     DependentSizedMatrixTypeLoc TL) {
66935ffd83dbSDimitry Andric   TL.setAttrNameLoc(readSourceLocation());
669481ad6265SDimitry Andric   TL.setAttrOperandParensRange(readSourceRange());
66955ffd83dbSDimitry Andric   TL.setAttrRowOperand(Reader.readExpr());
66965ffd83dbSDimitry Andric   TL.setAttrColumnOperand(Reader.readExpr());
66975ffd83dbSDimitry Andric }
66985ffd83dbSDimitry Andric 
66990b57cec5SDimitry Andric void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6700480093f4SDimitry Andric   TL.setLocalRangeBegin(readSourceLocation());
6701480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6702480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
670381ad6265SDimitry Andric   TL.setExceptionSpecRange(readSourceRange());
6704480093f4SDimitry Andric   TL.setLocalRangeEnd(readSourceLocation());
67050b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
6706480093f4SDimitry Andric     TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
67070b57cec5SDimitry Andric   }
67080b57cec5SDimitry Andric }
67090b57cec5SDimitry Andric 
67100b57cec5SDimitry Andric void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
67110b57cec5SDimitry Andric   VisitFunctionTypeLoc(TL);
67120b57cec5SDimitry Andric }
67130b57cec5SDimitry Andric 
67140b57cec5SDimitry Andric void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
67150b57cec5SDimitry Andric   VisitFunctionTypeLoc(TL);
67160b57cec5SDimitry Andric }
67170b57cec5SDimitry Andric 
67180b57cec5SDimitry Andric void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6719480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
67200b57cec5SDimitry Andric }
67210b57cec5SDimitry Andric 
67220eae32dcSDimitry Andric void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
67230eae32dcSDimitry Andric   TL.setNameLoc(readSourceLocation());
67240eae32dcSDimitry Andric }
67250eae32dcSDimitry Andric 
67260b57cec5SDimitry Andric void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6727480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
67280b57cec5SDimitry Andric }
67290b57cec5SDimitry Andric 
67300b57cec5SDimitry Andric void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6731480093f4SDimitry Andric   TL.setTypeofLoc(readSourceLocation());
6732480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6733480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
67340b57cec5SDimitry Andric }
67350b57cec5SDimitry Andric 
67360b57cec5SDimitry Andric void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6737480093f4SDimitry Andric   TL.setTypeofLoc(readSourceLocation());
6738480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6739480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
6740*bdd1243dSDimitry Andric   TL.setUnmodifiedTInfo(GetTypeSourceInfo());
67410b57cec5SDimitry Andric }
67420b57cec5SDimitry Andric 
67430b57cec5SDimitry Andric void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
674404eeddc0SDimitry Andric   TL.setDecltypeLoc(readSourceLocation());
674504eeddc0SDimitry Andric   TL.setRParenLoc(readSourceLocation());
67460b57cec5SDimitry Andric }
67470b57cec5SDimitry Andric 
67480b57cec5SDimitry Andric void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6749480093f4SDimitry Andric   TL.setKWLoc(readSourceLocation());
6750480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6751480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
67520b57cec5SDimitry Andric   TL.setUnderlyingTInfo(GetTypeSourceInfo());
67530b57cec5SDimitry Andric }
67540b57cec5SDimitry Andric 
67550b57cec5SDimitry Andric void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
6756480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
675755e4f9d5SDimitry Andric   if (Reader.readBool()) {
675855e4f9d5SDimitry Andric     TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
675955e4f9d5SDimitry Andric     TL.setTemplateKWLoc(readSourceLocation());
676055e4f9d5SDimitry Andric     TL.setConceptNameLoc(readSourceLocation());
676155e4f9d5SDimitry Andric     TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
676255e4f9d5SDimitry Andric     TL.setLAngleLoc(readSourceLocation());
676355e4f9d5SDimitry Andric     TL.setRAngleLoc(readSourceLocation());
676455e4f9d5SDimitry Andric     for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6765*bdd1243dSDimitry Andric       TL.setArgLocInfo(
6766*bdd1243dSDimitry Andric           i, Reader.readTemplateArgumentLocInfo(
6767*bdd1243dSDimitry Andric                  TL.getTypePtr()->getTypeConstraintArguments()[i].getKind()));
676855e4f9d5SDimitry Andric   }
676904eeddc0SDimitry Andric   if (Reader.readBool())
677004eeddc0SDimitry Andric     TL.setRParenLoc(readSourceLocation());
67710b57cec5SDimitry Andric }
67720b57cec5SDimitry Andric 
67730b57cec5SDimitry Andric void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
67740b57cec5SDimitry Andric     DeducedTemplateSpecializationTypeLoc TL) {
6775480093f4SDimitry Andric   TL.setTemplateNameLoc(readSourceLocation());
67760b57cec5SDimitry Andric }
67770b57cec5SDimitry Andric 
67780b57cec5SDimitry Andric void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
6779480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
67800b57cec5SDimitry Andric }
67810b57cec5SDimitry Andric 
67820b57cec5SDimitry Andric void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
6783480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
67840b57cec5SDimitry Andric }
67850b57cec5SDimitry Andric 
67860b57cec5SDimitry Andric void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
67870b57cec5SDimitry Andric   TL.setAttr(ReadAttr());
67880b57cec5SDimitry Andric }
67890b57cec5SDimitry Andric 
679081ad6265SDimitry Andric void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
679181ad6265SDimitry Andric   // Nothing to do.
679281ad6265SDimitry Andric }
679381ad6265SDimitry Andric 
67940b57cec5SDimitry Andric void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
6795480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
67960b57cec5SDimitry Andric }
67970b57cec5SDimitry Andric 
67980b57cec5SDimitry Andric void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
67990b57cec5SDimitry Andric                                             SubstTemplateTypeParmTypeLoc TL) {
6800480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
68010b57cec5SDimitry Andric }
68020b57cec5SDimitry Andric 
68030b57cec5SDimitry Andric void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
68040b57cec5SDimitry Andric                                           SubstTemplateTypeParmPackTypeLoc TL) {
6805480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
68060b57cec5SDimitry Andric }
68070b57cec5SDimitry Andric 
68080b57cec5SDimitry Andric void TypeLocReader::VisitTemplateSpecializationTypeLoc(
68090b57cec5SDimitry Andric                                            TemplateSpecializationTypeLoc TL) {
6810480093f4SDimitry Andric   TL.setTemplateKeywordLoc(readSourceLocation());
6811480093f4SDimitry Andric   TL.setTemplateNameLoc(readSourceLocation());
6812480093f4SDimitry Andric   TL.setLAngleLoc(readSourceLocation());
6813480093f4SDimitry Andric   TL.setRAngleLoc(readSourceLocation());
68140b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6815*bdd1243dSDimitry Andric     TL.setArgLocInfo(i,
6816480093f4SDimitry Andric                      Reader.readTemplateArgumentLocInfo(
6817*bdd1243dSDimitry Andric                          TL.getTypePtr()->template_arguments()[i].getKind()));
68180b57cec5SDimitry Andric }
68190b57cec5SDimitry Andric 
68200b57cec5SDimitry Andric void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
6821480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6822480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
68230b57cec5SDimitry Andric }
68240b57cec5SDimitry Andric 
68250b57cec5SDimitry Andric void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6826480093f4SDimitry Andric   TL.setElaboratedKeywordLoc(readSourceLocation());
68270b57cec5SDimitry Andric   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
68280b57cec5SDimitry Andric }
68290b57cec5SDimitry Andric 
68300b57cec5SDimitry Andric void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
6831480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
68320b57cec5SDimitry Andric }
68330b57cec5SDimitry Andric 
68340b57cec5SDimitry Andric void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6835480093f4SDimitry Andric   TL.setElaboratedKeywordLoc(readSourceLocation());
68360b57cec5SDimitry Andric   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6837480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
68380b57cec5SDimitry Andric }
68390b57cec5SDimitry Andric 
68400b57cec5SDimitry Andric void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
68410b57cec5SDimitry Andric        DependentTemplateSpecializationTypeLoc TL) {
6842480093f4SDimitry Andric   TL.setElaboratedKeywordLoc(readSourceLocation());
68430b57cec5SDimitry Andric   TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
6844480093f4SDimitry Andric   TL.setTemplateKeywordLoc(readSourceLocation());
6845480093f4SDimitry Andric   TL.setTemplateNameLoc(readSourceLocation());
6846480093f4SDimitry Andric   TL.setLAngleLoc(readSourceLocation());
6847480093f4SDimitry Andric   TL.setRAngleLoc(readSourceLocation());
68480b57cec5SDimitry Andric   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
6849*bdd1243dSDimitry Andric     TL.setArgLocInfo(I,
6850480093f4SDimitry Andric                      Reader.readTemplateArgumentLocInfo(
6851*bdd1243dSDimitry Andric                          TL.getTypePtr()->template_arguments()[I].getKind()));
68520b57cec5SDimitry Andric }
68530b57cec5SDimitry Andric 
68540b57cec5SDimitry Andric void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
6855480093f4SDimitry Andric   TL.setEllipsisLoc(readSourceLocation());
68560b57cec5SDimitry Andric }
68570b57cec5SDimitry Andric 
68580b57cec5SDimitry Andric void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6859480093f4SDimitry Andric   TL.setNameLoc(readSourceLocation());
6860*bdd1243dSDimitry Andric   TL.setNameEndLoc(readSourceLocation());
68610b57cec5SDimitry Andric }
68620b57cec5SDimitry Andric 
68630b57cec5SDimitry Andric void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
68640b57cec5SDimitry Andric   if (TL.getNumProtocols()) {
6865480093f4SDimitry Andric     TL.setProtocolLAngleLoc(readSourceLocation());
6866480093f4SDimitry Andric     TL.setProtocolRAngleLoc(readSourceLocation());
68670b57cec5SDimitry Andric   }
68680b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6869480093f4SDimitry Andric     TL.setProtocolLoc(i, readSourceLocation());
68700b57cec5SDimitry Andric }
68710b57cec5SDimitry Andric 
68720b57cec5SDimitry Andric void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6873480093f4SDimitry Andric   TL.setHasBaseTypeAsWritten(Reader.readBool());
6874480093f4SDimitry Andric   TL.setTypeArgsLAngleLoc(readSourceLocation());
6875480093f4SDimitry Andric   TL.setTypeArgsRAngleLoc(readSourceLocation());
68760b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
68770b57cec5SDimitry Andric     TL.setTypeArgTInfo(i, GetTypeSourceInfo());
6878480093f4SDimitry Andric   TL.setProtocolLAngleLoc(readSourceLocation());
6879480093f4SDimitry Andric   TL.setProtocolRAngleLoc(readSourceLocation());
68800b57cec5SDimitry Andric   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
6881480093f4SDimitry Andric     TL.setProtocolLoc(i, readSourceLocation());
68820b57cec5SDimitry Andric }
68830b57cec5SDimitry Andric 
68840b57cec5SDimitry Andric void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6885480093f4SDimitry Andric   TL.setStarLoc(readSourceLocation());
68860b57cec5SDimitry Andric }
68870b57cec5SDimitry Andric 
68880b57cec5SDimitry Andric void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6889480093f4SDimitry Andric   TL.setKWLoc(readSourceLocation());
6890480093f4SDimitry Andric   TL.setLParenLoc(readSourceLocation());
6891480093f4SDimitry Andric   TL.setRParenLoc(readSourceLocation());
68920b57cec5SDimitry Andric }
68930b57cec5SDimitry Andric 
68940b57cec5SDimitry Andric void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
6895480093f4SDimitry Andric   TL.setKWLoc(readSourceLocation());
68960b57cec5SDimitry Andric }
68970b57cec5SDimitry Andric 
68980eae32dcSDimitry Andric void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
68995ffd83dbSDimitry Andric   TL.setNameLoc(readSourceLocation());
69005ffd83dbSDimitry Andric }
69010eae32dcSDimitry Andric void TypeLocReader::VisitDependentBitIntTypeLoc(
69020eae32dcSDimitry Andric     clang::DependentBitIntTypeLoc TL) {
69035ffd83dbSDimitry Andric   TL.setNameLoc(readSourceLocation());
69045ffd83dbSDimitry Andric }
69055ffd83dbSDimitry Andric 
690681ad6265SDimitry Andric void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {
690781ad6265SDimitry Andric   LocSeq::State Seq(ParentSeq);
690881ad6265SDimitry Andric   TypeLocReader TLR(*this, Seq);
69090b57cec5SDimitry Andric   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
69100b57cec5SDimitry Andric     TLR.Visit(TL);
69110b57cec5SDimitry Andric }
69120b57cec5SDimitry Andric 
6913480093f4SDimitry Andric TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6914480093f4SDimitry Andric   QualType InfoTy = readType();
69150b57cec5SDimitry Andric   if (InfoTy.isNull())
69160b57cec5SDimitry Andric     return nullptr;
69170b57cec5SDimitry Andric 
69180b57cec5SDimitry Andric   TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
6919480093f4SDimitry Andric   readTypeLoc(TInfo->getTypeLoc());
69200b57cec5SDimitry Andric   return TInfo;
69210b57cec5SDimitry Andric }
69220b57cec5SDimitry Andric 
69230b57cec5SDimitry Andric QualType ASTReader::GetType(TypeID ID) {
69240b57cec5SDimitry Andric   assert(ContextObj && "reading type with no AST context");
69250b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
69260b57cec5SDimitry Andric 
69270b57cec5SDimitry Andric   unsigned FastQuals = ID & Qualifiers::FastMask;
69280b57cec5SDimitry Andric   unsigned Index = ID >> Qualifiers::FastWidth;
69290b57cec5SDimitry Andric 
69300b57cec5SDimitry Andric   if (Index < NUM_PREDEF_TYPE_IDS) {
69310b57cec5SDimitry Andric     QualType T;
69320b57cec5SDimitry Andric     switch ((PredefinedTypeIDs)Index) {
69330b57cec5SDimitry Andric     case PREDEF_TYPE_NULL_ID:
69340b57cec5SDimitry Andric       return QualType();
69350b57cec5SDimitry Andric     case PREDEF_TYPE_VOID_ID:
69360b57cec5SDimitry Andric       T = Context.VoidTy;
69370b57cec5SDimitry Andric       break;
69380b57cec5SDimitry Andric     case PREDEF_TYPE_BOOL_ID:
69390b57cec5SDimitry Andric       T = Context.BoolTy;
69400b57cec5SDimitry Andric       break;
69410b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR_U_ID:
69420b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR_S_ID:
69430b57cec5SDimitry Andric       // FIXME: Check that the signedness of CharTy is correct!
69440b57cec5SDimitry Andric       T = Context.CharTy;
69450b57cec5SDimitry Andric       break;
69460b57cec5SDimitry Andric     case PREDEF_TYPE_UCHAR_ID:
69470b57cec5SDimitry Andric       T = Context.UnsignedCharTy;
69480b57cec5SDimitry Andric       break;
69490b57cec5SDimitry Andric     case PREDEF_TYPE_USHORT_ID:
69500b57cec5SDimitry Andric       T = Context.UnsignedShortTy;
69510b57cec5SDimitry Andric       break;
69520b57cec5SDimitry Andric     case PREDEF_TYPE_UINT_ID:
69530b57cec5SDimitry Andric       T = Context.UnsignedIntTy;
69540b57cec5SDimitry Andric       break;
69550b57cec5SDimitry Andric     case PREDEF_TYPE_ULONG_ID:
69560b57cec5SDimitry Andric       T = Context.UnsignedLongTy;
69570b57cec5SDimitry Andric       break;
69580b57cec5SDimitry Andric     case PREDEF_TYPE_ULONGLONG_ID:
69590b57cec5SDimitry Andric       T = Context.UnsignedLongLongTy;
69600b57cec5SDimitry Andric       break;
69610b57cec5SDimitry Andric     case PREDEF_TYPE_UINT128_ID:
69620b57cec5SDimitry Andric       T = Context.UnsignedInt128Ty;
69630b57cec5SDimitry Andric       break;
69640b57cec5SDimitry Andric     case PREDEF_TYPE_SCHAR_ID:
69650b57cec5SDimitry Andric       T = Context.SignedCharTy;
69660b57cec5SDimitry Andric       break;
69670b57cec5SDimitry Andric     case PREDEF_TYPE_WCHAR_ID:
69680b57cec5SDimitry Andric       T = Context.WCharTy;
69690b57cec5SDimitry Andric       break;
69700b57cec5SDimitry Andric     case PREDEF_TYPE_SHORT_ID:
69710b57cec5SDimitry Andric       T = Context.ShortTy;
69720b57cec5SDimitry Andric       break;
69730b57cec5SDimitry Andric     case PREDEF_TYPE_INT_ID:
69740b57cec5SDimitry Andric       T = Context.IntTy;
69750b57cec5SDimitry Andric       break;
69760b57cec5SDimitry Andric     case PREDEF_TYPE_LONG_ID:
69770b57cec5SDimitry Andric       T = Context.LongTy;
69780b57cec5SDimitry Andric       break;
69790b57cec5SDimitry Andric     case PREDEF_TYPE_LONGLONG_ID:
69800b57cec5SDimitry Andric       T = Context.LongLongTy;
69810b57cec5SDimitry Andric       break;
69820b57cec5SDimitry Andric     case PREDEF_TYPE_INT128_ID:
69830b57cec5SDimitry Andric       T = Context.Int128Ty;
69840b57cec5SDimitry Andric       break;
69855ffd83dbSDimitry Andric     case PREDEF_TYPE_BFLOAT16_ID:
69865ffd83dbSDimitry Andric       T = Context.BFloat16Ty;
69875ffd83dbSDimitry Andric       break;
69880b57cec5SDimitry Andric     case PREDEF_TYPE_HALF_ID:
69890b57cec5SDimitry Andric       T = Context.HalfTy;
69900b57cec5SDimitry Andric       break;
69910b57cec5SDimitry Andric     case PREDEF_TYPE_FLOAT_ID:
69920b57cec5SDimitry Andric       T = Context.FloatTy;
69930b57cec5SDimitry Andric       break;
69940b57cec5SDimitry Andric     case PREDEF_TYPE_DOUBLE_ID:
69950b57cec5SDimitry Andric       T = Context.DoubleTy;
69960b57cec5SDimitry Andric       break;
69970b57cec5SDimitry Andric     case PREDEF_TYPE_LONGDOUBLE_ID:
69980b57cec5SDimitry Andric       T = Context.LongDoubleTy;
69990b57cec5SDimitry Andric       break;
70000b57cec5SDimitry Andric     case PREDEF_TYPE_SHORT_ACCUM_ID:
70010b57cec5SDimitry Andric       T = Context.ShortAccumTy;
70020b57cec5SDimitry Andric       break;
70030b57cec5SDimitry Andric     case PREDEF_TYPE_ACCUM_ID:
70040b57cec5SDimitry Andric       T = Context.AccumTy;
70050b57cec5SDimitry Andric       break;
70060b57cec5SDimitry Andric     case PREDEF_TYPE_LONG_ACCUM_ID:
70070b57cec5SDimitry Andric       T = Context.LongAccumTy;
70080b57cec5SDimitry Andric       break;
70090b57cec5SDimitry Andric     case PREDEF_TYPE_USHORT_ACCUM_ID:
70100b57cec5SDimitry Andric       T = Context.UnsignedShortAccumTy;
70110b57cec5SDimitry Andric       break;
70120b57cec5SDimitry Andric     case PREDEF_TYPE_UACCUM_ID:
70130b57cec5SDimitry Andric       T = Context.UnsignedAccumTy;
70140b57cec5SDimitry Andric       break;
70150b57cec5SDimitry Andric     case PREDEF_TYPE_ULONG_ACCUM_ID:
70160b57cec5SDimitry Andric       T = Context.UnsignedLongAccumTy;
70170b57cec5SDimitry Andric       break;
70180b57cec5SDimitry Andric     case PREDEF_TYPE_SHORT_FRACT_ID:
70190b57cec5SDimitry Andric       T = Context.ShortFractTy;
70200b57cec5SDimitry Andric       break;
70210b57cec5SDimitry Andric     case PREDEF_TYPE_FRACT_ID:
70220b57cec5SDimitry Andric       T = Context.FractTy;
70230b57cec5SDimitry Andric       break;
70240b57cec5SDimitry Andric     case PREDEF_TYPE_LONG_FRACT_ID:
70250b57cec5SDimitry Andric       T = Context.LongFractTy;
70260b57cec5SDimitry Andric       break;
70270b57cec5SDimitry Andric     case PREDEF_TYPE_USHORT_FRACT_ID:
70280b57cec5SDimitry Andric       T = Context.UnsignedShortFractTy;
70290b57cec5SDimitry Andric       break;
70300b57cec5SDimitry Andric     case PREDEF_TYPE_UFRACT_ID:
70310b57cec5SDimitry Andric       T = Context.UnsignedFractTy;
70320b57cec5SDimitry Andric       break;
70330b57cec5SDimitry Andric     case PREDEF_TYPE_ULONG_FRACT_ID:
70340b57cec5SDimitry Andric       T = Context.UnsignedLongFractTy;
70350b57cec5SDimitry Andric       break;
70360b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
70370b57cec5SDimitry Andric       T = Context.SatShortAccumTy;
70380b57cec5SDimitry Andric       break;
70390b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_ACCUM_ID:
70400b57cec5SDimitry Andric       T = Context.SatAccumTy;
70410b57cec5SDimitry Andric       break;
70420b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
70430b57cec5SDimitry Andric       T = Context.SatLongAccumTy;
70440b57cec5SDimitry Andric       break;
70450b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
70460b57cec5SDimitry Andric       T = Context.SatUnsignedShortAccumTy;
70470b57cec5SDimitry Andric       break;
70480b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_UACCUM_ID:
70490b57cec5SDimitry Andric       T = Context.SatUnsignedAccumTy;
70500b57cec5SDimitry Andric       break;
70510b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
70520b57cec5SDimitry Andric       T = Context.SatUnsignedLongAccumTy;
70530b57cec5SDimitry Andric       break;
70540b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
70550b57cec5SDimitry Andric       T = Context.SatShortFractTy;
70560b57cec5SDimitry Andric       break;
70570b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_FRACT_ID:
70580b57cec5SDimitry Andric       T = Context.SatFractTy;
70590b57cec5SDimitry Andric       break;
70600b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_LONG_FRACT_ID:
70610b57cec5SDimitry Andric       T = Context.SatLongFractTy;
70620b57cec5SDimitry Andric       break;
70630b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
70640b57cec5SDimitry Andric       T = Context.SatUnsignedShortFractTy;
70650b57cec5SDimitry Andric       break;
70660b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_UFRACT_ID:
70670b57cec5SDimitry Andric       T = Context.SatUnsignedFractTy;
70680b57cec5SDimitry Andric       break;
70690b57cec5SDimitry Andric     case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
70700b57cec5SDimitry Andric       T = Context.SatUnsignedLongFractTy;
70710b57cec5SDimitry Andric       break;
70720b57cec5SDimitry Andric     case PREDEF_TYPE_FLOAT16_ID:
70730b57cec5SDimitry Andric       T = Context.Float16Ty;
70740b57cec5SDimitry Andric       break;
70750b57cec5SDimitry Andric     case PREDEF_TYPE_FLOAT128_ID:
70760b57cec5SDimitry Andric       T = Context.Float128Ty;
70770b57cec5SDimitry Andric       break;
7078349cc55cSDimitry Andric     case PREDEF_TYPE_IBM128_ID:
7079349cc55cSDimitry Andric       T = Context.Ibm128Ty;
7080349cc55cSDimitry Andric       break;
70810b57cec5SDimitry Andric     case PREDEF_TYPE_OVERLOAD_ID:
70820b57cec5SDimitry Andric       T = Context.OverloadTy;
70830b57cec5SDimitry Andric       break;
70840b57cec5SDimitry Andric     case PREDEF_TYPE_BOUND_MEMBER:
70850b57cec5SDimitry Andric       T = Context.BoundMemberTy;
70860b57cec5SDimitry Andric       break;
70870b57cec5SDimitry Andric     case PREDEF_TYPE_PSEUDO_OBJECT:
70880b57cec5SDimitry Andric       T = Context.PseudoObjectTy;
70890b57cec5SDimitry Andric       break;
70900b57cec5SDimitry Andric     case PREDEF_TYPE_DEPENDENT_ID:
70910b57cec5SDimitry Andric       T = Context.DependentTy;
70920b57cec5SDimitry Andric       break;
70930b57cec5SDimitry Andric     case PREDEF_TYPE_UNKNOWN_ANY:
70940b57cec5SDimitry Andric       T = Context.UnknownAnyTy;
70950b57cec5SDimitry Andric       break;
70960b57cec5SDimitry Andric     case PREDEF_TYPE_NULLPTR_ID:
70970b57cec5SDimitry Andric       T = Context.NullPtrTy;
70980b57cec5SDimitry Andric       break;
70990b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR8_ID:
71000b57cec5SDimitry Andric       T = Context.Char8Ty;
71010b57cec5SDimitry Andric       break;
71020b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR16_ID:
71030b57cec5SDimitry Andric       T = Context.Char16Ty;
71040b57cec5SDimitry Andric       break;
71050b57cec5SDimitry Andric     case PREDEF_TYPE_CHAR32_ID:
71060b57cec5SDimitry Andric       T = Context.Char32Ty;
71070b57cec5SDimitry Andric       break;
71080b57cec5SDimitry Andric     case PREDEF_TYPE_OBJC_ID:
71090b57cec5SDimitry Andric       T = Context.ObjCBuiltinIdTy;
71100b57cec5SDimitry Andric       break;
71110b57cec5SDimitry Andric     case PREDEF_TYPE_OBJC_CLASS:
71120b57cec5SDimitry Andric       T = Context.ObjCBuiltinClassTy;
71130b57cec5SDimitry Andric       break;
71140b57cec5SDimitry Andric     case PREDEF_TYPE_OBJC_SEL:
71150b57cec5SDimitry Andric       T = Context.ObjCBuiltinSelTy;
71160b57cec5SDimitry Andric       break;
71170b57cec5SDimitry Andric #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
71180b57cec5SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
71190b57cec5SDimitry Andric       T = Context.SingletonId; \
71200b57cec5SDimitry Andric       break;
71210b57cec5SDimitry Andric #include "clang/Basic/OpenCLImageTypes.def"
71220b57cec5SDimitry Andric #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
71230b57cec5SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
71240b57cec5SDimitry Andric       T = Context.Id##Ty; \
71250b57cec5SDimitry Andric       break;
71260b57cec5SDimitry Andric #include "clang/Basic/OpenCLExtensionTypes.def"
71270b57cec5SDimitry Andric     case PREDEF_TYPE_SAMPLER_ID:
71280b57cec5SDimitry Andric       T = Context.OCLSamplerTy;
71290b57cec5SDimitry Andric       break;
71300b57cec5SDimitry Andric     case PREDEF_TYPE_EVENT_ID:
71310b57cec5SDimitry Andric       T = Context.OCLEventTy;
71320b57cec5SDimitry Andric       break;
71330b57cec5SDimitry Andric     case PREDEF_TYPE_CLK_EVENT_ID:
71340b57cec5SDimitry Andric       T = Context.OCLClkEventTy;
71350b57cec5SDimitry Andric       break;
71360b57cec5SDimitry Andric     case PREDEF_TYPE_QUEUE_ID:
71370b57cec5SDimitry Andric       T = Context.OCLQueueTy;
71380b57cec5SDimitry Andric       break;
71390b57cec5SDimitry Andric     case PREDEF_TYPE_RESERVE_ID_ID:
71400b57cec5SDimitry Andric       T = Context.OCLReserveIDTy;
71410b57cec5SDimitry Andric       break;
71420b57cec5SDimitry Andric     case PREDEF_TYPE_AUTO_DEDUCT:
71430b57cec5SDimitry Andric       T = Context.getAutoDeductType();
71440b57cec5SDimitry Andric       break;
71450b57cec5SDimitry Andric     case PREDEF_TYPE_AUTO_RREF_DEDUCT:
71460b57cec5SDimitry Andric       T = Context.getAutoRRefDeductType();
71470b57cec5SDimitry Andric       break;
71480b57cec5SDimitry Andric     case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
71490b57cec5SDimitry Andric       T = Context.ARCUnbridgedCastTy;
71500b57cec5SDimitry Andric       break;
71510b57cec5SDimitry Andric     case PREDEF_TYPE_BUILTIN_FN:
71520b57cec5SDimitry Andric       T = Context.BuiltinFnTy;
71530b57cec5SDimitry Andric       break;
71545ffd83dbSDimitry Andric     case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
71555ffd83dbSDimitry Andric       T = Context.IncompleteMatrixIdxTy;
71565ffd83dbSDimitry Andric       break;
71570b57cec5SDimitry Andric     case PREDEF_TYPE_OMP_ARRAY_SECTION:
71580b57cec5SDimitry Andric       T = Context.OMPArraySectionTy;
71590b57cec5SDimitry Andric       break;
71605ffd83dbSDimitry Andric     case PREDEF_TYPE_OMP_ARRAY_SHAPING:
71615ffd83dbSDimitry Andric       T = Context.OMPArraySectionTy;
71625ffd83dbSDimitry Andric       break;
71635ffd83dbSDimitry Andric     case PREDEF_TYPE_OMP_ITERATOR:
71645ffd83dbSDimitry Andric       T = Context.OMPIteratorTy;
71655ffd83dbSDimitry Andric       break;
7166a7dea167SDimitry Andric #define SVE_TYPE(Name, Id, SingletonId) \
7167a7dea167SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
7168a7dea167SDimitry Andric       T = Context.SingletonId; \
7169a7dea167SDimitry Andric       break;
7170a7dea167SDimitry Andric #include "clang/Basic/AArch64SVEACLETypes.def"
7171e8d8bef9SDimitry Andric #define PPC_VECTOR_TYPE(Name, Id, Size) \
7172e8d8bef9SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
7173e8d8bef9SDimitry Andric       T = Context.Id##Ty; \
7174e8d8bef9SDimitry Andric       break;
7175e8d8bef9SDimitry Andric #include "clang/Basic/PPCTypes.def"
7176fe6060f1SDimitry Andric #define RVV_TYPE(Name, Id, SingletonId) \
7177fe6060f1SDimitry Andric     case PREDEF_TYPE_##Id##_ID: \
7178fe6060f1SDimitry Andric       T = Context.SingletonId; \
7179fe6060f1SDimitry Andric       break;
7180fe6060f1SDimitry Andric #include "clang/Basic/RISCVVTypes.def"
71810b57cec5SDimitry Andric     }
71820b57cec5SDimitry Andric 
71830b57cec5SDimitry Andric     assert(!T.isNull() && "Unknown predefined type");
71840b57cec5SDimitry Andric     return T.withFastQualifiers(FastQuals);
71850b57cec5SDimitry Andric   }
71860b57cec5SDimitry Andric 
71870b57cec5SDimitry Andric   Index -= NUM_PREDEF_TYPE_IDS;
71880b57cec5SDimitry Andric   assert(Index < TypesLoaded.size() && "Type index out-of-range");
71890b57cec5SDimitry Andric   if (TypesLoaded[Index].isNull()) {
71900b57cec5SDimitry Andric     TypesLoaded[Index] = readTypeRecord(Index);
71910b57cec5SDimitry Andric     if (TypesLoaded[Index].isNull())
71920b57cec5SDimitry Andric       return QualType();
71930b57cec5SDimitry Andric 
71940b57cec5SDimitry Andric     TypesLoaded[Index]->setFromAST();
71950b57cec5SDimitry Andric     if (DeserializationListener)
71960b57cec5SDimitry Andric       DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
71970b57cec5SDimitry Andric                                         TypesLoaded[Index]);
71980b57cec5SDimitry Andric   }
71990b57cec5SDimitry Andric 
72000b57cec5SDimitry Andric   return TypesLoaded[Index].withFastQualifiers(FastQuals);
72010b57cec5SDimitry Andric }
72020b57cec5SDimitry Andric 
72030b57cec5SDimitry Andric QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
72040b57cec5SDimitry Andric   return GetType(getGlobalTypeID(F, LocalID));
72050b57cec5SDimitry Andric }
72060b57cec5SDimitry Andric 
72070b57cec5SDimitry Andric serialization::TypeID
72080b57cec5SDimitry Andric ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
72090b57cec5SDimitry Andric   unsigned FastQuals = LocalID & Qualifiers::FastMask;
72100b57cec5SDimitry Andric   unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
72110b57cec5SDimitry Andric 
72120b57cec5SDimitry Andric   if (LocalIndex < NUM_PREDEF_TYPE_IDS)
72130b57cec5SDimitry Andric     return LocalID;
72140b57cec5SDimitry Andric 
72150b57cec5SDimitry Andric   if (!F.ModuleOffsetMap.empty())
72160b57cec5SDimitry Andric     ReadModuleOffsetMap(F);
72170b57cec5SDimitry Andric 
72180b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
72190b57cec5SDimitry Andric     = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
72200b57cec5SDimitry Andric   assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
72210b57cec5SDimitry Andric 
72220b57cec5SDimitry Andric   unsigned GlobalIndex = LocalIndex + I->second;
72230b57cec5SDimitry Andric   return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
72240b57cec5SDimitry Andric }
72250b57cec5SDimitry Andric 
72260b57cec5SDimitry Andric TemplateArgumentLocInfo
7227480093f4SDimitry Andric ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
72280b57cec5SDimitry Andric   switch (Kind) {
72290b57cec5SDimitry Andric   case TemplateArgument::Expression:
7230480093f4SDimitry Andric     return readExpr();
72310b57cec5SDimitry Andric   case TemplateArgument::Type:
7232480093f4SDimitry Andric     return readTypeSourceInfo();
72330b57cec5SDimitry Andric   case TemplateArgument::Template: {
7234480093f4SDimitry Andric     NestedNameSpecifierLoc QualifierLoc =
7235480093f4SDimitry Andric       readNestedNameSpecifierLoc();
7236480093f4SDimitry Andric     SourceLocation TemplateNameLoc = readSourceLocation();
7237e8d8bef9SDimitry Andric     return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7238e8d8bef9SDimitry Andric                                    TemplateNameLoc, SourceLocation());
72390b57cec5SDimitry Andric   }
72400b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion: {
7241480093f4SDimitry Andric     NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7242480093f4SDimitry Andric     SourceLocation TemplateNameLoc = readSourceLocation();
7243480093f4SDimitry Andric     SourceLocation EllipsisLoc = readSourceLocation();
7244e8d8bef9SDimitry Andric     return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
7245e8d8bef9SDimitry Andric                                    TemplateNameLoc, EllipsisLoc);
72460b57cec5SDimitry Andric   }
72470b57cec5SDimitry Andric   case TemplateArgument::Null:
72480b57cec5SDimitry Andric   case TemplateArgument::Integral:
72490b57cec5SDimitry Andric   case TemplateArgument::Declaration:
72500b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
72510b57cec5SDimitry Andric   case TemplateArgument::Pack:
72520b57cec5SDimitry Andric     // FIXME: Is this right?
72530b57cec5SDimitry Andric     return TemplateArgumentLocInfo();
72540b57cec5SDimitry Andric   }
72550b57cec5SDimitry Andric   llvm_unreachable("unexpected template argument loc");
72560b57cec5SDimitry Andric }
72570b57cec5SDimitry Andric 
7258480093f4SDimitry Andric TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7259480093f4SDimitry Andric   TemplateArgument Arg = readTemplateArgument();
72600b57cec5SDimitry Andric 
72610b57cec5SDimitry Andric   if (Arg.getKind() == TemplateArgument::Expression) {
7262480093f4SDimitry Andric     if (readBool()) // bool InfoHasSameExpr.
72630b57cec5SDimitry Andric       return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
72640b57cec5SDimitry Andric   }
7265480093f4SDimitry Andric   return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
72660b57cec5SDimitry Andric }
72670b57cec5SDimitry Andric 
72680b57cec5SDimitry Andric const ASTTemplateArgumentListInfo *
7269480093f4SDimitry Andric ASTRecordReader::readASTTemplateArgumentListInfo() {
7270480093f4SDimitry Andric   SourceLocation LAngleLoc = readSourceLocation();
7271480093f4SDimitry Andric   SourceLocation RAngleLoc = readSourceLocation();
7272480093f4SDimitry Andric   unsigned NumArgsAsWritten = readInt();
72730b57cec5SDimitry Andric   TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
72740b57cec5SDimitry Andric   for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7275480093f4SDimitry Andric     TemplArgsInfo.addArgument(readTemplateArgumentLoc());
72760b57cec5SDimitry Andric   return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
72770b57cec5SDimitry Andric }
72780b57cec5SDimitry Andric 
72790b57cec5SDimitry Andric Decl *ASTReader::GetExternalDecl(uint32_t ID) {
72800b57cec5SDimitry Andric   return GetDecl(ID);
72810b57cec5SDimitry Andric }
72820b57cec5SDimitry Andric 
72830b57cec5SDimitry Andric void ASTReader::CompleteRedeclChain(const Decl *D) {
72840b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing) {
72850b57cec5SDimitry Andric     // We arrange to not care about the complete redeclaration chain while we're
72860b57cec5SDimitry Andric     // deserializing. Just remember that the AST has marked this one as complete
72870b57cec5SDimitry Andric     // but that it's not actually complete yet, so we know we still need to
72880b57cec5SDimitry Andric     // complete it later.
72890b57cec5SDimitry Andric     PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
72900b57cec5SDimitry Andric     return;
72910b57cec5SDimitry Andric   }
72920b57cec5SDimitry Andric 
7293fe6060f1SDimitry Andric   if (!D->getDeclContext()) {
7294fe6060f1SDimitry Andric     assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
7295fe6060f1SDimitry Andric     return;
7296fe6060f1SDimitry Andric   }
7297fe6060f1SDimitry Andric 
72980b57cec5SDimitry Andric   const DeclContext *DC = D->getDeclContext()->getRedeclContext();
72990b57cec5SDimitry Andric 
73000b57cec5SDimitry Andric   // If this is a named declaration, complete it by looking it up
73010b57cec5SDimitry Andric   // within its context.
73020b57cec5SDimitry Andric   //
73030b57cec5SDimitry Andric   // FIXME: Merging a function definition should merge
73040b57cec5SDimitry Andric   // all mergeable entities within it.
7305*bdd1243dSDimitry Andric   if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
73060b57cec5SDimitry Andric     if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
73070b57cec5SDimitry Andric       if (!getContext().getLangOpts().CPlusPlus &&
73080b57cec5SDimitry Andric           isa<TranslationUnitDecl>(DC)) {
73090b57cec5SDimitry Andric         // Outside of C++, we don't have a lookup table for the TU, so update
73100b57cec5SDimitry Andric         // the identifier instead. (For C++ modules, we don't store decls
73110b57cec5SDimitry Andric         // in the serialized identifier table, so we do the lookup in the TU.)
73120b57cec5SDimitry Andric         auto *II = Name.getAsIdentifierInfo();
73130b57cec5SDimitry Andric         assert(II && "non-identifier name in C?");
73140b57cec5SDimitry Andric         if (II->isOutOfDate())
73150b57cec5SDimitry Andric           updateOutOfDateIdentifier(*II);
73160b57cec5SDimitry Andric       } else
73170b57cec5SDimitry Andric         DC->lookup(Name);
73180b57cec5SDimitry Andric     } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
73190b57cec5SDimitry Andric       // Find all declarations of this kind from the relevant context.
73200b57cec5SDimitry Andric       for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
73210b57cec5SDimitry Andric         auto *DC = cast<DeclContext>(DCDecl);
73220b57cec5SDimitry Andric         SmallVector<Decl*, 8> Decls;
73230b57cec5SDimitry Andric         FindExternalLexicalDecls(
73240b57cec5SDimitry Andric             DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
73250b57cec5SDimitry Andric       }
73260b57cec5SDimitry Andric     }
73270b57cec5SDimitry Andric   }
73280b57cec5SDimitry Andric 
73290b57cec5SDimitry Andric   if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
73300b57cec5SDimitry Andric     CTSD->getSpecializedTemplate()->LoadLazySpecializations();
73310b57cec5SDimitry Andric   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
73320b57cec5SDimitry Andric     VTSD->getSpecializedTemplate()->LoadLazySpecializations();
73330b57cec5SDimitry Andric   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
73340b57cec5SDimitry Andric     if (auto *Template = FD->getPrimaryTemplate())
73350b57cec5SDimitry Andric       Template->LoadLazySpecializations();
73360b57cec5SDimitry Andric   }
73370b57cec5SDimitry Andric }
73380b57cec5SDimitry Andric 
73390b57cec5SDimitry Andric CXXCtorInitializer **
73400b57cec5SDimitry Andric ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
73410b57cec5SDimitry Andric   RecordLocation Loc = getLocalBitOffset(Offset);
73420b57cec5SDimitry Andric   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
73430b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
73440b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
73450b57cec5SDimitry Andric     Error(std::move(Err));
73460b57cec5SDimitry Andric     return nullptr;
73470b57cec5SDimitry Andric   }
73480b57cec5SDimitry Andric   ReadingKindTracker ReadingKind(Read_Decl, *this);
73490b57cec5SDimitry Andric 
73500b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
73510b57cec5SDimitry Andric   if (!MaybeCode) {
73520b57cec5SDimitry Andric     Error(MaybeCode.takeError());
73530b57cec5SDimitry Andric     return nullptr;
73540b57cec5SDimitry Andric   }
73550b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
73560b57cec5SDimitry Andric 
7357480093f4SDimitry Andric   ASTRecordReader Record(*this, *Loc.F);
7358480093f4SDimitry Andric   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
73590b57cec5SDimitry Andric   if (!MaybeRecCode) {
73600b57cec5SDimitry Andric     Error(MaybeRecCode.takeError());
73610b57cec5SDimitry Andric     return nullptr;
73620b57cec5SDimitry Andric   }
73630b57cec5SDimitry Andric   if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
73640b57cec5SDimitry Andric     Error("malformed AST file: missing C++ ctor initializers");
73650b57cec5SDimitry Andric     return nullptr;
73660b57cec5SDimitry Andric   }
73670b57cec5SDimitry Andric 
7368480093f4SDimitry Andric   return Record.readCXXCtorInitializers();
73690b57cec5SDimitry Andric }
73700b57cec5SDimitry Andric 
73710b57cec5SDimitry Andric CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
73720b57cec5SDimitry Andric   assert(ContextObj && "reading base specifiers with no AST context");
73730b57cec5SDimitry Andric   ASTContext &Context = *ContextObj;
73740b57cec5SDimitry Andric 
73750b57cec5SDimitry Andric   RecordLocation Loc = getLocalBitOffset(Offset);
73760b57cec5SDimitry Andric   BitstreamCursor &Cursor = Loc.F->DeclsCursor;
73770b57cec5SDimitry Andric   SavedStreamPosition SavedPosition(Cursor);
73780b57cec5SDimitry Andric   if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
73790b57cec5SDimitry Andric     Error(std::move(Err));
73800b57cec5SDimitry Andric     return nullptr;
73810b57cec5SDimitry Andric   }
73820b57cec5SDimitry Andric   ReadingKindTracker ReadingKind(Read_Decl, *this);
73830b57cec5SDimitry Andric 
73840b57cec5SDimitry Andric   Expected<unsigned> MaybeCode = Cursor.ReadCode();
73850b57cec5SDimitry Andric   if (!MaybeCode) {
73860b57cec5SDimitry Andric     Error(MaybeCode.takeError());
73870b57cec5SDimitry Andric     return nullptr;
73880b57cec5SDimitry Andric   }
73890b57cec5SDimitry Andric   unsigned Code = MaybeCode.get();
73900b57cec5SDimitry Andric 
7391480093f4SDimitry Andric   ASTRecordReader Record(*this, *Loc.F);
7392480093f4SDimitry Andric   Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
73930b57cec5SDimitry Andric   if (!MaybeRecCode) {
73940b57cec5SDimitry Andric     Error(MaybeCode.takeError());
73950b57cec5SDimitry Andric     return nullptr;
73960b57cec5SDimitry Andric   }
73970b57cec5SDimitry Andric   unsigned RecCode = MaybeRecCode.get();
73980b57cec5SDimitry Andric 
73990b57cec5SDimitry Andric   if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
74000b57cec5SDimitry Andric     Error("malformed AST file: missing C++ base specifiers");
74010b57cec5SDimitry Andric     return nullptr;
74020b57cec5SDimitry Andric   }
74030b57cec5SDimitry Andric 
7404480093f4SDimitry Andric   unsigned NumBases = Record.readInt();
74050b57cec5SDimitry Andric   void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
74060b57cec5SDimitry Andric   CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
74070b57cec5SDimitry Andric   for (unsigned I = 0; I != NumBases; ++I)
7408480093f4SDimitry Andric     Bases[I] = Record.readCXXBaseSpecifier();
74090b57cec5SDimitry Andric   return Bases;
74100b57cec5SDimitry Andric }
74110b57cec5SDimitry Andric 
74120b57cec5SDimitry Andric serialization::DeclID
74130b57cec5SDimitry Andric ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
74140b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_DECL_IDS)
74150b57cec5SDimitry Andric     return LocalID;
74160b57cec5SDimitry Andric 
74170b57cec5SDimitry Andric   if (!F.ModuleOffsetMap.empty())
74180b57cec5SDimitry Andric     ReadModuleOffsetMap(F);
74190b57cec5SDimitry Andric 
74200b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
74210b57cec5SDimitry Andric     = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
74220b57cec5SDimitry Andric   assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
74230b57cec5SDimitry Andric 
74240b57cec5SDimitry Andric   return LocalID + I->second;
74250b57cec5SDimitry Andric }
74260b57cec5SDimitry Andric 
74270b57cec5SDimitry Andric bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
74280b57cec5SDimitry Andric                                    ModuleFile &M) const {
74290b57cec5SDimitry Andric   // Predefined decls aren't from any module.
74300b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS)
74310b57cec5SDimitry Andric     return false;
74320b57cec5SDimitry Andric 
74330b57cec5SDimitry Andric   return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
74340b57cec5SDimitry Andric          ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
74350b57cec5SDimitry Andric }
74360b57cec5SDimitry Andric 
74370b57cec5SDimitry Andric ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
74380b57cec5SDimitry Andric   if (!D->isFromASTFile())
74390b57cec5SDimitry Andric     return nullptr;
74400b57cec5SDimitry Andric   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
74410b57cec5SDimitry Andric   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
74420b57cec5SDimitry Andric   return I->second;
74430b57cec5SDimitry Andric }
74440b57cec5SDimitry Andric 
74450b57cec5SDimitry Andric SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
74460b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS)
74470b57cec5SDimitry Andric     return SourceLocation();
74480b57cec5SDimitry Andric 
74490b57cec5SDimitry Andric   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
74500b57cec5SDimitry Andric 
74510b57cec5SDimitry Andric   if (Index > DeclsLoaded.size()) {
74520b57cec5SDimitry Andric     Error("declaration ID out-of-range for AST file");
74530b57cec5SDimitry Andric     return SourceLocation();
74540b57cec5SDimitry Andric   }
74550b57cec5SDimitry Andric 
74560b57cec5SDimitry Andric   if (Decl *D = DeclsLoaded[Index])
74570b57cec5SDimitry Andric     return D->getLocation();
74580b57cec5SDimitry Andric 
74590b57cec5SDimitry Andric   SourceLocation Loc;
74600b57cec5SDimitry Andric   DeclCursorForID(ID, Loc);
74610b57cec5SDimitry Andric   return Loc;
74620b57cec5SDimitry Andric }
74630b57cec5SDimitry Andric 
74640b57cec5SDimitry Andric static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
74650b57cec5SDimitry Andric   switch (ID) {
74660b57cec5SDimitry Andric   case PREDEF_DECL_NULL_ID:
74670b57cec5SDimitry Andric     return nullptr;
74680b57cec5SDimitry Andric 
74690b57cec5SDimitry Andric   case PREDEF_DECL_TRANSLATION_UNIT_ID:
74700b57cec5SDimitry Andric     return Context.getTranslationUnitDecl();
74710b57cec5SDimitry Andric 
74720b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_ID_ID:
74730b57cec5SDimitry Andric     return Context.getObjCIdDecl();
74740b57cec5SDimitry Andric 
74750b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_SEL_ID:
74760b57cec5SDimitry Andric     return Context.getObjCSelDecl();
74770b57cec5SDimitry Andric 
74780b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_CLASS_ID:
74790b57cec5SDimitry Andric     return Context.getObjCClassDecl();
74800b57cec5SDimitry Andric 
74810b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_PROTOCOL_ID:
74820b57cec5SDimitry Andric     return Context.getObjCProtocolDecl();
74830b57cec5SDimitry Andric 
74840b57cec5SDimitry Andric   case PREDEF_DECL_INT_128_ID:
74850b57cec5SDimitry Andric     return Context.getInt128Decl();
74860b57cec5SDimitry Andric 
74870b57cec5SDimitry Andric   case PREDEF_DECL_UNSIGNED_INT_128_ID:
74880b57cec5SDimitry Andric     return Context.getUInt128Decl();
74890b57cec5SDimitry Andric 
74900b57cec5SDimitry Andric   case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
74910b57cec5SDimitry Andric     return Context.getObjCInstanceTypeDecl();
74920b57cec5SDimitry Andric 
74930b57cec5SDimitry Andric   case PREDEF_DECL_BUILTIN_VA_LIST_ID:
74940b57cec5SDimitry Andric     return Context.getBuiltinVaListDecl();
74950b57cec5SDimitry Andric 
74960b57cec5SDimitry Andric   case PREDEF_DECL_VA_LIST_TAG:
74970b57cec5SDimitry Andric     return Context.getVaListTagDecl();
74980b57cec5SDimitry Andric 
74990b57cec5SDimitry Andric   case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
75000b57cec5SDimitry Andric     return Context.getBuiltinMSVaListDecl();
75010b57cec5SDimitry Andric 
75025ffd83dbSDimitry Andric   case PREDEF_DECL_BUILTIN_MS_GUID_ID:
75035ffd83dbSDimitry Andric     return Context.getMSGuidTagDecl();
75045ffd83dbSDimitry Andric 
75050b57cec5SDimitry Andric   case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
75060b57cec5SDimitry Andric     return Context.getExternCContextDecl();
75070b57cec5SDimitry Andric 
75080b57cec5SDimitry Andric   case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
75090b57cec5SDimitry Andric     return Context.getMakeIntegerSeqDecl();
75100b57cec5SDimitry Andric 
75110b57cec5SDimitry Andric   case PREDEF_DECL_CF_CONSTANT_STRING_ID:
75120b57cec5SDimitry Andric     return Context.getCFConstantStringDecl();
75130b57cec5SDimitry Andric 
75140b57cec5SDimitry Andric   case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
75150b57cec5SDimitry Andric     return Context.getCFConstantStringTagDecl();
75160b57cec5SDimitry Andric 
75170b57cec5SDimitry Andric   case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
75180b57cec5SDimitry Andric     return Context.getTypePackElementDecl();
75190b57cec5SDimitry Andric   }
75200b57cec5SDimitry Andric   llvm_unreachable("PredefinedDeclIDs unknown enum value");
75210b57cec5SDimitry Andric }
75220b57cec5SDimitry Andric 
75230b57cec5SDimitry Andric Decl *ASTReader::GetExistingDecl(DeclID ID) {
75240b57cec5SDimitry Andric   assert(ContextObj && "reading decl with no AST context");
75250b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS) {
75260b57cec5SDimitry Andric     Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
75270b57cec5SDimitry Andric     if (D) {
75280b57cec5SDimitry Andric       // Track that we have merged the declaration with ID \p ID into the
75290b57cec5SDimitry Andric       // pre-existing predefined declaration \p D.
75300b57cec5SDimitry Andric       auto &Merged = KeyDecls[D->getCanonicalDecl()];
75310b57cec5SDimitry Andric       if (Merged.empty())
75320b57cec5SDimitry Andric         Merged.push_back(ID);
75330b57cec5SDimitry Andric     }
75340b57cec5SDimitry Andric     return D;
75350b57cec5SDimitry Andric   }
75360b57cec5SDimitry Andric 
75370b57cec5SDimitry Andric   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
75380b57cec5SDimitry Andric 
75390b57cec5SDimitry Andric   if (Index >= DeclsLoaded.size()) {
75400b57cec5SDimitry Andric     assert(0 && "declaration ID out-of-range for AST file");
75410b57cec5SDimitry Andric     Error("declaration ID out-of-range for AST file");
75420b57cec5SDimitry Andric     return nullptr;
75430b57cec5SDimitry Andric   }
75440b57cec5SDimitry Andric 
75450b57cec5SDimitry Andric   return DeclsLoaded[Index];
75460b57cec5SDimitry Andric }
75470b57cec5SDimitry Andric 
75480b57cec5SDimitry Andric Decl *ASTReader::GetDecl(DeclID ID) {
75490b57cec5SDimitry Andric   if (ID < NUM_PREDEF_DECL_IDS)
75500b57cec5SDimitry Andric     return GetExistingDecl(ID);
75510b57cec5SDimitry Andric 
75520b57cec5SDimitry Andric   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
75530b57cec5SDimitry Andric 
75540b57cec5SDimitry Andric   if (Index >= DeclsLoaded.size()) {
75550b57cec5SDimitry Andric     assert(0 && "declaration ID out-of-range for AST file");
75560b57cec5SDimitry Andric     Error("declaration ID out-of-range for AST file");
75570b57cec5SDimitry Andric     return nullptr;
75580b57cec5SDimitry Andric   }
75590b57cec5SDimitry Andric 
75600b57cec5SDimitry Andric   if (!DeclsLoaded[Index]) {
75610b57cec5SDimitry Andric     ReadDeclRecord(ID);
75620b57cec5SDimitry Andric     if (DeserializationListener)
75630b57cec5SDimitry Andric       DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
75640b57cec5SDimitry Andric   }
75650b57cec5SDimitry Andric 
75660b57cec5SDimitry Andric   return DeclsLoaded[Index];
75670b57cec5SDimitry Andric }
75680b57cec5SDimitry Andric 
75690b57cec5SDimitry Andric DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
75700b57cec5SDimitry Andric                                                   DeclID GlobalID) {
75710b57cec5SDimitry Andric   if (GlobalID < NUM_PREDEF_DECL_IDS)
75720b57cec5SDimitry Andric     return GlobalID;
75730b57cec5SDimitry Andric 
75740b57cec5SDimitry Andric   GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
75750b57cec5SDimitry Andric   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
75760b57cec5SDimitry Andric   ModuleFile *Owner = I->second;
75770b57cec5SDimitry Andric 
75780b57cec5SDimitry Andric   llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
75790b57cec5SDimitry Andric     = M.GlobalToLocalDeclIDs.find(Owner);
75800b57cec5SDimitry Andric   if (Pos == M.GlobalToLocalDeclIDs.end())
75810b57cec5SDimitry Andric     return 0;
75820b57cec5SDimitry Andric 
75830b57cec5SDimitry Andric   return GlobalID - Owner->BaseDeclID + Pos->second;
75840b57cec5SDimitry Andric }
75850b57cec5SDimitry Andric 
75860b57cec5SDimitry Andric serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
75870b57cec5SDimitry Andric                                             const RecordData &Record,
75880b57cec5SDimitry Andric                                             unsigned &Idx) {
75890b57cec5SDimitry Andric   if (Idx >= Record.size()) {
75900b57cec5SDimitry Andric     Error("Corrupted AST file");
75910b57cec5SDimitry Andric     return 0;
75920b57cec5SDimitry Andric   }
75930b57cec5SDimitry Andric 
75940b57cec5SDimitry Andric   return getGlobalDeclID(F, Record[Idx++]);
75950b57cec5SDimitry Andric }
75960b57cec5SDimitry Andric 
75970b57cec5SDimitry Andric /// Resolve the offset of a statement into a statement.
75980b57cec5SDimitry Andric ///
75990b57cec5SDimitry Andric /// This operation will read a new statement from the external
76000b57cec5SDimitry Andric /// source each time it is called, and is meant to be used via a
76010b57cec5SDimitry Andric /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
76020b57cec5SDimitry Andric Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
76030b57cec5SDimitry Andric   // Switch case IDs are per Decl.
76040b57cec5SDimitry Andric   ClearSwitchCaseIDs();
76050b57cec5SDimitry Andric 
76060b57cec5SDimitry Andric   // Offset here is a global offset across the entire chain.
76070b57cec5SDimitry Andric   RecordLocation Loc = getLocalBitOffset(Offset);
76080b57cec5SDimitry Andric   if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
76090b57cec5SDimitry Andric     Error(std::move(Err));
76100b57cec5SDimitry Andric     return nullptr;
76110b57cec5SDimitry Andric   }
76120b57cec5SDimitry Andric   assert(NumCurrentElementsDeserializing == 0 &&
76130b57cec5SDimitry Andric          "should not be called while already deserializing");
76140b57cec5SDimitry Andric   Deserializing D(this);
76150b57cec5SDimitry Andric   return ReadStmtFromStream(*Loc.F);
76160b57cec5SDimitry Andric }
76170b57cec5SDimitry Andric 
76180b57cec5SDimitry Andric void ASTReader::FindExternalLexicalDecls(
76190b57cec5SDimitry Andric     const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
76200b57cec5SDimitry Andric     SmallVectorImpl<Decl *> &Decls) {
76210b57cec5SDimitry Andric   bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
76220b57cec5SDimitry Andric 
76230b57cec5SDimitry Andric   auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
76240b57cec5SDimitry Andric     assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
76250b57cec5SDimitry Andric     for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
76260b57cec5SDimitry Andric       auto K = (Decl::Kind)+LexicalDecls[I];
76270b57cec5SDimitry Andric       if (!IsKindWeWant(K))
76280b57cec5SDimitry Andric         continue;
76290b57cec5SDimitry Andric 
76300b57cec5SDimitry Andric       auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
76310b57cec5SDimitry Andric 
76320b57cec5SDimitry Andric       // Don't add predefined declarations to the lexical context more
76330b57cec5SDimitry Andric       // than once.
76340b57cec5SDimitry Andric       if (ID < NUM_PREDEF_DECL_IDS) {
76350b57cec5SDimitry Andric         if (PredefsVisited[ID])
76360b57cec5SDimitry Andric           continue;
76370b57cec5SDimitry Andric 
76380b57cec5SDimitry Andric         PredefsVisited[ID] = true;
76390b57cec5SDimitry Andric       }
76400b57cec5SDimitry Andric 
76410b57cec5SDimitry Andric       if (Decl *D = GetLocalDecl(*M, ID)) {
76420b57cec5SDimitry Andric         assert(D->getKind() == K && "wrong kind for lexical decl");
76430b57cec5SDimitry Andric         if (!DC->isDeclInLexicalTraversal(D))
76440b57cec5SDimitry Andric           Decls.push_back(D);
76450b57cec5SDimitry Andric       }
76460b57cec5SDimitry Andric     }
76470b57cec5SDimitry Andric   };
76480b57cec5SDimitry Andric 
76490b57cec5SDimitry Andric   if (isa<TranslationUnitDecl>(DC)) {
76500b57cec5SDimitry Andric     for (auto Lexical : TULexicalDecls)
76510b57cec5SDimitry Andric       Visit(Lexical.first, Lexical.second);
76520b57cec5SDimitry Andric   } else {
76530b57cec5SDimitry Andric     auto I = LexicalDecls.find(DC);
76540b57cec5SDimitry Andric     if (I != LexicalDecls.end())
76550b57cec5SDimitry Andric       Visit(I->second.first, I->second.second);
76560b57cec5SDimitry Andric   }
76570b57cec5SDimitry Andric 
76580b57cec5SDimitry Andric   ++NumLexicalDeclContextsRead;
76590b57cec5SDimitry Andric }
76600b57cec5SDimitry Andric 
76610b57cec5SDimitry Andric namespace {
76620b57cec5SDimitry Andric 
76630b57cec5SDimitry Andric class DeclIDComp {
76640b57cec5SDimitry Andric   ASTReader &Reader;
76650b57cec5SDimitry Andric   ModuleFile &Mod;
76660b57cec5SDimitry Andric 
76670b57cec5SDimitry Andric public:
76680b57cec5SDimitry Andric   DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
76690b57cec5SDimitry Andric 
76700b57cec5SDimitry Andric   bool operator()(LocalDeclID L, LocalDeclID R) const {
76710b57cec5SDimitry Andric     SourceLocation LHS = getLocation(L);
76720b57cec5SDimitry Andric     SourceLocation RHS = getLocation(R);
76730b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
76740b57cec5SDimitry Andric   }
76750b57cec5SDimitry Andric 
76760b57cec5SDimitry Andric   bool operator()(SourceLocation LHS, LocalDeclID R) const {
76770b57cec5SDimitry Andric     SourceLocation RHS = getLocation(R);
76780b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
76790b57cec5SDimitry Andric   }
76800b57cec5SDimitry Andric 
76810b57cec5SDimitry Andric   bool operator()(LocalDeclID L, SourceLocation RHS) const {
76820b57cec5SDimitry Andric     SourceLocation LHS = getLocation(L);
76830b57cec5SDimitry Andric     return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
76840b57cec5SDimitry Andric   }
76850b57cec5SDimitry Andric 
76860b57cec5SDimitry Andric   SourceLocation getLocation(LocalDeclID ID) const {
76870b57cec5SDimitry Andric     return Reader.getSourceManager().getFileLoc(
76880b57cec5SDimitry Andric             Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
76890b57cec5SDimitry Andric   }
76900b57cec5SDimitry Andric };
76910b57cec5SDimitry Andric 
76920b57cec5SDimitry Andric } // namespace
76930b57cec5SDimitry Andric 
76940b57cec5SDimitry Andric void ASTReader::FindFileRegionDecls(FileID File,
76950b57cec5SDimitry Andric                                     unsigned Offset, unsigned Length,
76960b57cec5SDimitry Andric                                     SmallVectorImpl<Decl *> &Decls) {
76970b57cec5SDimitry Andric   SourceManager &SM = getSourceManager();
76980b57cec5SDimitry Andric 
76990b57cec5SDimitry Andric   llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
77000b57cec5SDimitry Andric   if (I == FileDeclIDs.end())
77010b57cec5SDimitry Andric     return;
77020b57cec5SDimitry Andric 
77030b57cec5SDimitry Andric   FileDeclsInfo &DInfo = I->second;
77040b57cec5SDimitry Andric   if (DInfo.Decls.empty())
77050b57cec5SDimitry Andric     return;
77060b57cec5SDimitry Andric 
77070b57cec5SDimitry Andric   SourceLocation
77080b57cec5SDimitry Andric     BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
77090b57cec5SDimitry Andric   SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
77100b57cec5SDimitry Andric 
77110b57cec5SDimitry Andric   DeclIDComp DIDComp(*this, *DInfo.Mod);
77120b57cec5SDimitry Andric   ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
77130b57cec5SDimitry Andric       llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
77140b57cec5SDimitry Andric   if (BeginIt != DInfo.Decls.begin())
77150b57cec5SDimitry Andric     --BeginIt;
77160b57cec5SDimitry Andric 
77170b57cec5SDimitry Andric   // If we are pointing at a top-level decl inside an objc container, we need
77180b57cec5SDimitry Andric   // to backtrack until we find it otherwise we will fail to report that the
77190b57cec5SDimitry Andric   // region overlaps with an objc container.
77200b57cec5SDimitry Andric   while (BeginIt != DInfo.Decls.begin() &&
77210b57cec5SDimitry Andric          GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
77220b57cec5SDimitry Andric              ->isTopLevelDeclInObjCContainer())
77230b57cec5SDimitry Andric     --BeginIt;
77240b57cec5SDimitry Andric 
77250b57cec5SDimitry Andric   ArrayRef<serialization::LocalDeclID>::iterator EndIt =
77260b57cec5SDimitry Andric       llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
77270b57cec5SDimitry Andric   if (EndIt != DInfo.Decls.end())
77280b57cec5SDimitry Andric     ++EndIt;
77290b57cec5SDimitry Andric 
77300b57cec5SDimitry Andric   for (ArrayRef<serialization::LocalDeclID>::iterator
77310b57cec5SDimitry Andric          DIt = BeginIt; DIt != EndIt; ++DIt)
77320b57cec5SDimitry Andric     Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
77330b57cec5SDimitry Andric }
77340b57cec5SDimitry Andric 
77350b57cec5SDimitry Andric bool
77360b57cec5SDimitry Andric ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
77370b57cec5SDimitry Andric                                           DeclarationName Name) {
77380b57cec5SDimitry Andric   assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
77390b57cec5SDimitry Andric          "DeclContext has no visible decls in storage");
77400b57cec5SDimitry Andric   if (!Name)
77410b57cec5SDimitry Andric     return false;
77420b57cec5SDimitry Andric 
77430b57cec5SDimitry Andric   auto It = Lookups.find(DC);
77440b57cec5SDimitry Andric   if (It == Lookups.end())
77450b57cec5SDimitry Andric     return false;
77460b57cec5SDimitry Andric 
77470b57cec5SDimitry Andric   Deserializing LookupResults(this);
77480b57cec5SDimitry Andric 
77490b57cec5SDimitry Andric   // Load the list of declarations.
77500b57cec5SDimitry Andric   SmallVector<NamedDecl *, 64> Decls;
7751fe6060f1SDimitry Andric   llvm::SmallPtrSet<NamedDecl *, 8> Found;
77520b57cec5SDimitry Andric   for (DeclID ID : It->second.Table.find(Name)) {
77530b57cec5SDimitry Andric     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7754fe6060f1SDimitry Andric     if (ND->getDeclName() == Name && Found.insert(ND).second)
77550b57cec5SDimitry Andric       Decls.push_back(ND);
77560b57cec5SDimitry Andric   }
77570b57cec5SDimitry Andric 
77580b57cec5SDimitry Andric   ++NumVisibleDeclContextsRead;
77590b57cec5SDimitry Andric   SetExternalVisibleDeclsForName(DC, Name, Decls);
77600b57cec5SDimitry Andric   return !Decls.empty();
77610b57cec5SDimitry Andric }
77620b57cec5SDimitry Andric 
77630b57cec5SDimitry Andric void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
77640b57cec5SDimitry Andric   if (!DC->hasExternalVisibleStorage())
77650b57cec5SDimitry Andric     return;
77660b57cec5SDimitry Andric 
77670b57cec5SDimitry Andric   auto It = Lookups.find(DC);
77680b57cec5SDimitry Andric   assert(It != Lookups.end() &&
77690b57cec5SDimitry Andric          "have external visible storage but no lookup tables");
77700b57cec5SDimitry Andric 
77710b57cec5SDimitry Andric   DeclsMap Decls;
77720b57cec5SDimitry Andric 
77730b57cec5SDimitry Andric   for (DeclID ID : It->second.Table.findAll()) {
77740b57cec5SDimitry Andric     NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
77750b57cec5SDimitry Andric     Decls[ND->getDeclName()].push_back(ND);
77760b57cec5SDimitry Andric   }
77770b57cec5SDimitry Andric 
77780b57cec5SDimitry Andric   ++NumVisibleDeclContextsRead;
77790b57cec5SDimitry Andric 
77800b57cec5SDimitry Andric   for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
77810b57cec5SDimitry Andric     SetExternalVisibleDeclsForName(DC, I->first, I->second);
77820b57cec5SDimitry Andric   }
77830b57cec5SDimitry Andric   const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
77840b57cec5SDimitry Andric }
77850b57cec5SDimitry Andric 
77860b57cec5SDimitry Andric const serialization::reader::DeclContextLookupTable *
77870b57cec5SDimitry Andric ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
77880b57cec5SDimitry Andric   auto I = Lookups.find(Primary);
77890b57cec5SDimitry Andric   return I == Lookups.end() ? nullptr : &I->second;
77900b57cec5SDimitry Andric }
77910b57cec5SDimitry Andric 
77920b57cec5SDimitry Andric /// Under non-PCH compilation the consumer receives the objc methods
77930b57cec5SDimitry Andric /// before receiving the implementation, and codegen depends on this.
77940b57cec5SDimitry Andric /// We simulate this by deserializing and passing to consumer the methods of the
77950b57cec5SDimitry Andric /// implementation before passing the deserialized implementation decl.
77960b57cec5SDimitry Andric static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
77970b57cec5SDimitry Andric                                        ASTConsumer *Consumer) {
77980b57cec5SDimitry Andric   assert(ImplD && Consumer);
77990b57cec5SDimitry Andric 
78000b57cec5SDimitry Andric   for (auto *I : ImplD->methods())
78010b57cec5SDimitry Andric     Consumer->HandleInterestingDecl(DeclGroupRef(I));
78020b57cec5SDimitry Andric 
78030b57cec5SDimitry Andric   Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
78040b57cec5SDimitry Andric }
78050b57cec5SDimitry Andric 
78060b57cec5SDimitry Andric void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
78070b57cec5SDimitry Andric   if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
78080b57cec5SDimitry Andric     PassObjCImplDeclToConsumer(ImplD, Consumer);
78090b57cec5SDimitry Andric   else
78100b57cec5SDimitry Andric     Consumer->HandleInterestingDecl(DeclGroupRef(D));
78110b57cec5SDimitry Andric }
78120b57cec5SDimitry Andric 
78130b57cec5SDimitry Andric void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
78140b57cec5SDimitry Andric   this->Consumer = Consumer;
78150b57cec5SDimitry Andric 
78160b57cec5SDimitry Andric   if (Consumer)
78170b57cec5SDimitry Andric     PassInterestingDeclsToConsumer();
78180b57cec5SDimitry Andric 
78190b57cec5SDimitry Andric   if (DeserializationListener)
78200b57cec5SDimitry Andric     DeserializationListener->ReaderInitialized(this);
78210b57cec5SDimitry Andric }
78220b57cec5SDimitry Andric 
78230b57cec5SDimitry Andric void ASTReader::PrintStats() {
78240b57cec5SDimitry Andric   std::fprintf(stderr, "*** AST File Statistics:\n");
78250b57cec5SDimitry Andric 
7826349cc55cSDimitry Andric   unsigned NumTypesLoaded =
7827349cc55cSDimitry Andric       TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
7828349cc55cSDimitry Andric   unsigned NumDeclsLoaded =
7829349cc55cSDimitry Andric       DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
7830349cc55cSDimitry Andric   unsigned NumIdentifiersLoaded =
7831349cc55cSDimitry Andric       IdentifiersLoaded.size() -
7832349cc55cSDimitry Andric       llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
7833349cc55cSDimitry Andric   unsigned NumMacrosLoaded =
7834349cc55cSDimitry Andric       MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
7835349cc55cSDimitry Andric   unsigned NumSelectorsLoaded =
7836349cc55cSDimitry Andric       SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
78370b57cec5SDimitry Andric 
78380b57cec5SDimitry Andric   if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
78390b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u source location entries read (%f%%)\n",
78400b57cec5SDimitry Andric                  NumSLocEntriesRead, TotalNumSLocEntries,
78410b57cec5SDimitry Andric                  ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
78420b57cec5SDimitry Andric   if (!TypesLoaded.empty())
78430b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u types read (%f%%)\n",
78440b57cec5SDimitry Andric                  NumTypesLoaded, (unsigned)TypesLoaded.size(),
78450b57cec5SDimitry Andric                  ((float)NumTypesLoaded/TypesLoaded.size() * 100));
78460b57cec5SDimitry Andric   if (!DeclsLoaded.empty())
78470b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u declarations read (%f%%)\n",
78480b57cec5SDimitry Andric                  NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
78490b57cec5SDimitry Andric                  ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
78500b57cec5SDimitry Andric   if (!IdentifiersLoaded.empty())
78510b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u identifiers read (%f%%)\n",
78520b57cec5SDimitry Andric                  NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
78530b57cec5SDimitry Andric                  ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
78540b57cec5SDimitry Andric   if (!MacrosLoaded.empty())
78550b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
78560b57cec5SDimitry Andric                  NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
78570b57cec5SDimitry Andric                  ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
78580b57cec5SDimitry Andric   if (!SelectorsLoaded.empty())
78590b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u selectors read (%f%%)\n",
78600b57cec5SDimitry Andric                  NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
78610b57cec5SDimitry Andric                  ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
78620b57cec5SDimitry Andric   if (TotalNumStatements)
78630b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u statements read (%f%%)\n",
78640b57cec5SDimitry Andric                  NumStatementsRead, TotalNumStatements,
78650b57cec5SDimitry Andric                  ((float)NumStatementsRead/TotalNumStatements * 100));
78660b57cec5SDimitry Andric   if (TotalNumMacros)
78670b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u macros read (%f%%)\n",
78680b57cec5SDimitry Andric                  NumMacrosRead, TotalNumMacros,
78690b57cec5SDimitry Andric                  ((float)NumMacrosRead/TotalNumMacros * 100));
78700b57cec5SDimitry Andric   if (TotalLexicalDeclContexts)
78710b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u lexical declcontexts read (%f%%)\n",
78720b57cec5SDimitry Andric                  NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
78730b57cec5SDimitry Andric                  ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
78740b57cec5SDimitry Andric                   * 100));
78750b57cec5SDimitry Andric   if (TotalVisibleDeclContexts)
78760b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u visible declcontexts read (%f%%)\n",
78770b57cec5SDimitry Andric                  NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
78780b57cec5SDimitry Andric                  ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
78790b57cec5SDimitry Andric                   * 100));
78800b57cec5SDimitry Andric   if (TotalNumMethodPoolEntries)
78810b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u method pool entries read (%f%%)\n",
78820b57cec5SDimitry Andric                  NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
78830b57cec5SDimitry Andric                  ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
78840b57cec5SDimitry Andric                   * 100));
78850b57cec5SDimitry Andric   if (NumMethodPoolLookups)
78860b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u method pool lookups succeeded (%f%%)\n",
78870b57cec5SDimitry Andric                  NumMethodPoolHits, NumMethodPoolLookups,
78880b57cec5SDimitry Andric                  ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
78890b57cec5SDimitry Andric   if (NumMethodPoolTableLookups)
78900b57cec5SDimitry Andric     std::fprintf(stderr, "  %u/%u method pool table lookups succeeded (%f%%)\n",
78910b57cec5SDimitry Andric                  NumMethodPoolTableHits, NumMethodPoolTableLookups,
78920b57cec5SDimitry Andric                  ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
78930b57cec5SDimitry Andric                   * 100.0));
78940b57cec5SDimitry Andric   if (NumIdentifierLookupHits)
78950b57cec5SDimitry Andric     std::fprintf(stderr,
78960b57cec5SDimitry Andric                  "  %u / %u identifier table lookups succeeded (%f%%)\n",
78970b57cec5SDimitry Andric                  NumIdentifierLookupHits, NumIdentifierLookups,
78980b57cec5SDimitry Andric                  (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
78990b57cec5SDimitry Andric 
79000b57cec5SDimitry Andric   if (GlobalIndex) {
79010b57cec5SDimitry Andric     std::fprintf(stderr, "\n");
79020b57cec5SDimitry Andric     GlobalIndex->printStats();
79030b57cec5SDimitry Andric   }
79040b57cec5SDimitry Andric 
79050b57cec5SDimitry Andric   std::fprintf(stderr, "\n");
79060b57cec5SDimitry Andric   dump();
79070b57cec5SDimitry Andric   std::fprintf(stderr, "\n");
79080b57cec5SDimitry Andric }
79090b57cec5SDimitry Andric 
79100b57cec5SDimitry Andric template<typename Key, typename ModuleFile, unsigned InitialCapacity>
79110b57cec5SDimitry Andric LLVM_DUMP_METHOD static void
79120b57cec5SDimitry Andric dumpModuleIDMap(StringRef Name,
79130b57cec5SDimitry Andric                 const ContinuousRangeMap<Key, ModuleFile *,
79140b57cec5SDimitry Andric                                          InitialCapacity> &Map) {
79150b57cec5SDimitry Andric   if (Map.begin() == Map.end())
79160b57cec5SDimitry Andric     return;
79170b57cec5SDimitry Andric 
79180b57cec5SDimitry Andric   using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
79190b57cec5SDimitry Andric 
79200b57cec5SDimitry Andric   llvm::errs() << Name << ":\n";
79210b57cec5SDimitry Andric   for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
79220b57cec5SDimitry Andric        I != IEnd; ++I) {
79230b57cec5SDimitry Andric     llvm::errs() << "  " << I->first << " -> " << I->second->FileName
79240b57cec5SDimitry Andric       << "\n";
79250b57cec5SDimitry Andric   }
79260b57cec5SDimitry Andric }
79270b57cec5SDimitry Andric 
79280b57cec5SDimitry Andric LLVM_DUMP_METHOD void ASTReader::dump() {
79290b57cec5SDimitry Andric   llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
79300b57cec5SDimitry Andric   dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
79310b57cec5SDimitry Andric   dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
79320b57cec5SDimitry Andric   dumpModuleIDMap("Global type map", GlobalTypeMap);
79330b57cec5SDimitry Andric   dumpModuleIDMap("Global declaration map", GlobalDeclMap);
79340b57cec5SDimitry Andric   dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
79350b57cec5SDimitry Andric   dumpModuleIDMap("Global macro map", GlobalMacroMap);
79360b57cec5SDimitry Andric   dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
79370b57cec5SDimitry Andric   dumpModuleIDMap("Global selector map", GlobalSelectorMap);
79380b57cec5SDimitry Andric   dumpModuleIDMap("Global preprocessed entity map",
79390b57cec5SDimitry Andric                   GlobalPreprocessedEntityMap);
79400b57cec5SDimitry Andric 
79410b57cec5SDimitry Andric   llvm::errs() << "\n*** PCH/Modules Loaded:";
79420b57cec5SDimitry Andric   for (ModuleFile &M : ModuleMgr)
79430b57cec5SDimitry Andric     M.dump();
79440b57cec5SDimitry Andric }
79450b57cec5SDimitry Andric 
79460b57cec5SDimitry Andric /// Return the amount of memory used by memory buffers, breaking down
79470b57cec5SDimitry Andric /// by heap-backed versus mmap'ed memory.
79480b57cec5SDimitry Andric void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
79490b57cec5SDimitry Andric   for (ModuleFile &I : ModuleMgr) {
79500b57cec5SDimitry Andric     if (llvm::MemoryBuffer *buf = I.Buffer) {
79510b57cec5SDimitry Andric       size_t bytes = buf->getBufferSize();
79520b57cec5SDimitry Andric       switch (buf->getBufferKind()) {
79530b57cec5SDimitry Andric         case llvm::MemoryBuffer::MemoryBuffer_Malloc:
79540b57cec5SDimitry Andric           sizes.malloc_bytes += bytes;
79550b57cec5SDimitry Andric           break;
79560b57cec5SDimitry Andric         case llvm::MemoryBuffer::MemoryBuffer_MMap:
79570b57cec5SDimitry Andric           sizes.mmap_bytes += bytes;
79580b57cec5SDimitry Andric           break;
79590b57cec5SDimitry Andric       }
79600b57cec5SDimitry Andric     }
79610b57cec5SDimitry Andric   }
79620b57cec5SDimitry Andric }
79630b57cec5SDimitry Andric 
79640b57cec5SDimitry Andric void ASTReader::InitializeSema(Sema &S) {
79650b57cec5SDimitry Andric   SemaObj = &S;
79660b57cec5SDimitry Andric   S.addExternalSource(this);
79670b57cec5SDimitry Andric 
79680b57cec5SDimitry Andric   // Makes sure any declarations that were deserialized "too early"
79690b57cec5SDimitry Andric   // still get added to the identifier's declaration chains.
79700b57cec5SDimitry Andric   for (uint64_t ID : PreloadedDeclIDs) {
79710b57cec5SDimitry Andric     NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
79720b57cec5SDimitry Andric     pushExternalDeclIntoScope(D, D->getDeclName());
79730b57cec5SDimitry Andric   }
79740b57cec5SDimitry Andric   PreloadedDeclIDs.clear();
79750b57cec5SDimitry Andric 
79760b57cec5SDimitry Andric   // FIXME: What happens if these are changed by a module import?
79770b57cec5SDimitry Andric   if (!FPPragmaOptions.empty()) {
79780b57cec5SDimitry Andric     assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7979e8d8bef9SDimitry Andric     FPOptionsOverride NewOverrides =
7980e8d8bef9SDimitry Andric         FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
79815ffd83dbSDimitry Andric     SemaObj->CurFPFeatures =
79825ffd83dbSDimitry Andric         NewOverrides.applyOverrides(SemaObj->getLangOpts());
79830b57cec5SDimitry Andric   }
79840b57cec5SDimitry Andric 
7985e8d8bef9SDimitry Andric   SemaObj->OpenCLFeatures = OpenCLExtensions;
79860b57cec5SDimitry Andric 
79870b57cec5SDimitry Andric   UpdateSema();
79880b57cec5SDimitry Andric }
79890b57cec5SDimitry Andric 
79900b57cec5SDimitry Andric void ASTReader::UpdateSema() {
79910b57cec5SDimitry Andric   assert(SemaObj && "no Sema to update");
79920b57cec5SDimitry Andric 
79930b57cec5SDimitry Andric   // Load the offsets of the declarations that Sema references.
79940b57cec5SDimitry Andric   // They will be lazily deserialized when needed.
79950b57cec5SDimitry Andric   if (!SemaDeclRefs.empty()) {
79960b57cec5SDimitry Andric     assert(SemaDeclRefs.size() % 3 == 0);
79970b57cec5SDimitry Andric     for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
79980b57cec5SDimitry Andric       if (!SemaObj->StdNamespace)
79990b57cec5SDimitry Andric         SemaObj->StdNamespace = SemaDeclRefs[I];
80000b57cec5SDimitry Andric       if (!SemaObj->StdBadAlloc)
80010b57cec5SDimitry Andric         SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
80020b57cec5SDimitry Andric       if (!SemaObj->StdAlignValT)
80030b57cec5SDimitry Andric         SemaObj->StdAlignValT = SemaDeclRefs[I+2];
80040b57cec5SDimitry Andric     }
80050b57cec5SDimitry Andric     SemaDeclRefs.clear();
80060b57cec5SDimitry Andric   }
80070b57cec5SDimitry Andric 
80080b57cec5SDimitry Andric   // Update the state of pragmas. Use the same API as if we had encountered the
80090b57cec5SDimitry Andric   // pragma in the source.
80100b57cec5SDimitry Andric   if(OptimizeOffPragmaLocation.isValid())
80110b57cec5SDimitry Andric     SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
80120b57cec5SDimitry Andric   if (PragmaMSStructState != -1)
80130b57cec5SDimitry Andric     SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
80140b57cec5SDimitry Andric   if (PointersToMembersPragmaLocation.isValid()) {
80150b57cec5SDimitry Andric     SemaObj->ActOnPragmaMSPointersToMembers(
80160b57cec5SDimitry Andric         (LangOptions::PragmaMSPointersToMembersKind)
80170b57cec5SDimitry Andric             PragmaMSPointersToMembersState,
80180b57cec5SDimitry Andric         PointersToMembersPragmaLocation);
80190b57cec5SDimitry Andric   }
80200b57cec5SDimitry Andric   SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
80210b57cec5SDimitry Andric 
8022e8d8bef9SDimitry Andric   if (PragmaAlignPackCurrentValue) {
80230b57cec5SDimitry Andric     // The bottom of the stack might have a default value. It must be adjusted
80240b57cec5SDimitry Andric     // to the current value to ensure that the packing state is preserved after
80250b57cec5SDimitry Andric     // popping entries that were included/imported from a PCH/module.
80260b57cec5SDimitry Andric     bool DropFirst = false;
8027e8d8bef9SDimitry Andric     if (!PragmaAlignPackStack.empty() &&
8028e8d8bef9SDimitry Andric         PragmaAlignPackStack.front().Location.isInvalid()) {
8029e8d8bef9SDimitry Andric       assert(PragmaAlignPackStack.front().Value ==
8030e8d8bef9SDimitry Andric                  SemaObj->AlignPackStack.DefaultValue &&
80310b57cec5SDimitry Andric              "Expected a default alignment value");
8032e8d8bef9SDimitry Andric       SemaObj->AlignPackStack.Stack.emplace_back(
8033e8d8bef9SDimitry Andric           PragmaAlignPackStack.front().SlotLabel,
8034e8d8bef9SDimitry Andric           SemaObj->AlignPackStack.CurrentValue,
8035e8d8bef9SDimitry Andric           SemaObj->AlignPackStack.CurrentPragmaLocation,
8036e8d8bef9SDimitry Andric           PragmaAlignPackStack.front().PushLocation);
80370b57cec5SDimitry Andric       DropFirst = true;
80380b57cec5SDimitry Andric     }
8039*bdd1243dSDimitry Andric     for (const auto &Entry :
8040*bdd1243dSDimitry Andric          llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
8041e8d8bef9SDimitry Andric       SemaObj->AlignPackStack.Stack.emplace_back(
8042e8d8bef9SDimitry Andric           Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
8043e8d8bef9SDimitry Andric     }
8044e8d8bef9SDimitry Andric     if (PragmaAlignPackCurrentLocation.isInvalid()) {
8045e8d8bef9SDimitry Andric       assert(*PragmaAlignPackCurrentValue ==
8046e8d8bef9SDimitry Andric                  SemaObj->AlignPackStack.DefaultValue &&
8047e8d8bef9SDimitry Andric              "Expected a default align and pack value");
80480b57cec5SDimitry Andric       // Keep the current values.
80490b57cec5SDimitry Andric     } else {
8050e8d8bef9SDimitry Andric       SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
8051e8d8bef9SDimitry Andric       SemaObj->AlignPackStack.CurrentPragmaLocation =
8052e8d8bef9SDimitry Andric           PragmaAlignPackCurrentLocation;
80530b57cec5SDimitry Andric     }
80540b57cec5SDimitry Andric   }
80555ffd83dbSDimitry Andric   if (FpPragmaCurrentValue) {
80565ffd83dbSDimitry Andric     // The bottom of the stack might have a default value. It must be adjusted
80575ffd83dbSDimitry Andric     // to the current value to ensure that fp-pragma state is preserved after
80585ffd83dbSDimitry Andric     // popping entries that were included/imported from a PCH/module.
80595ffd83dbSDimitry Andric     bool DropFirst = false;
80605ffd83dbSDimitry Andric     if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
80615ffd83dbSDimitry Andric       assert(FpPragmaStack.front().Value ==
80625ffd83dbSDimitry Andric                  SemaObj->FpPragmaStack.DefaultValue &&
80635ffd83dbSDimitry Andric              "Expected a default pragma float_control value");
80645ffd83dbSDimitry Andric       SemaObj->FpPragmaStack.Stack.emplace_back(
80655ffd83dbSDimitry Andric           FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
80665ffd83dbSDimitry Andric           SemaObj->FpPragmaStack.CurrentPragmaLocation,
80675ffd83dbSDimitry Andric           FpPragmaStack.front().PushLocation);
80685ffd83dbSDimitry Andric       DropFirst = true;
80695ffd83dbSDimitry Andric     }
80705ffd83dbSDimitry Andric     for (const auto &Entry :
8071*bdd1243dSDimitry Andric          llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
80725ffd83dbSDimitry Andric       SemaObj->FpPragmaStack.Stack.emplace_back(
80735ffd83dbSDimitry Andric           Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
80745ffd83dbSDimitry Andric     if (FpPragmaCurrentLocation.isInvalid()) {
80755ffd83dbSDimitry Andric       assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
80765ffd83dbSDimitry Andric              "Expected a default pragma float_control value");
80775ffd83dbSDimitry Andric       // Keep the current values.
80785ffd83dbSDimitry Andric     } else {
80795ffd83dbSDimitry Andric       SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
80805ffd83dbSDimitry Andric       SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
80815ffd83dbSDimitry Andric     }
80825ffd83dbSDimitry Andric   }
8083e8d8bef9SDimitry Andric 
8084e8d8bef9SDimitry Andric   // For non-modular AST files, restore visiblity of modules.
8085e8d8bef9SDimitry Andric   for (auto &Import : ImportedModules) {
8086e8d8bef9SDimitry Andric     if (Import.ImportLoc.isInvalid())
8087e8d8bef9SDimitry Andric       continue;
8088e8d8bef9SDimitry Andric     if (Module *Imported = getSubmodule(Import.ID)) {
8089e8d8bef9SDimitry Andric       SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
8090e8d8bef9SDimitry Andric     }
8091e8d8bef9SDimitry Andric   }
80920b57cec5SDimitry Andric }
80930b57cec5SDimitry Andric 
80940b57cec5SDimitry Andric IdentifierInfo *ASTReader::get(StringRef Name) {
80950b57cec5SDimitry Andric   // Note that we are loading an identifier.
80960b57cec5SDimitry Andric   Deserializing AnIdentifier(this);
80970b57cec5SDimitry Andric 
80980b57cec5SDimitry Andric   IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
80990b57cec5SDimitry Andric                                   NumIdentifierLookups,
81000b57cec5SDimitry Andric                                   NumIdentifierLookupHits);
81010b57cec5SDimitry Andric 
81020b57cec5SDimitry Andric   // We don't need to do identifier table lookups in C++ modules (we preload
81030b57cec5SDimitry Andric   // all interesting declarations, and don't need to use the scope for name
81040b57cec5SDimitry Andric   // lookups). Perform the lookup in PCH files, though, since we don't build
81050b57cec5SDimitry Andric   // a complete initial identifier table if we're carrying on from a PCH.
81060b57cec5SDimitry Andric   if (PP.getLangOpts().CPlusPlus) {
8107*bdd1243dSDimitry Andric     for (auto *F : ModuleMgr.pch_modules())
81080b57cec5SDimitry Andric       if (Visitor(*F))
81090b57cec5SDimitry Andric         break;
81100b57cec5SDimitry Andric   } else {
81110b57cec5SDimitry Andric     // If there is a global index, look there first to determine which modules
81120b57cec5SDimitry Andric     // provably do not have any results for this identifier.
81130b57cec5SDimitry Andric     GlobalModuleIndex::HitSet Hits;
81140b57cec5SDimitry Andric     GlobalModuleIndex::HitSet *HitsPtr = nullptr;
81150b57cec5SDimitry Andric     if (!loadGlobalIndex()) {
81160b57cec5SDimitry Andric       if (GlobalIndex->lookupIdentifier(Name, Hits)) {
81170b57cec5SDimitry Andric         HitsPtr = &Hits;
81180b57cec5SDimitry Andric       }
81190b57cec5SDimitry Andric     }
81200b57cec5SDimitry Andric 
81210b57cec5SDimitry Andric     ModuleMgr.visit(Visitor, HitsPtr);
81220b57cec5SDimitry Andric   }
81230b57cec5SDimitry Andric 
81240b57cec5SDimitry Andric   IdentifierInfo *II = Visitor.getIdentifierInfo();
81250b57cec5SDimitry Andric   markIdentifierUpToDate(II);
81260b57cec5SDimitry Andric   return II;
81270b57cec5SDimitry Andric }
81280b57cec5SDimitry Andric 
81290b57cec5SDimitry Andric namespace clang {
81300b57cec5SDimitry Andric 
81310b57cec5SDimitry Andric   /// An identifier-lookup iterator that enumerates all of the
81320b57cec5SDimitry Andric   /// identifiers stored within a set of AST files.
81330b57cec5SDimitry Andric   class ASTIdentifierIterator : public IdentifierIterator {
81340b57cec5SDimitry Andric     /// The AST reader whose identifiers are being enumerated.
81350b57cec5SDimitry Andric     const ASTReader &Reader;
81360b57cec5SDimitry Andric 
81370b57cec5SDimitry Andric     /// The current index into the chain of AST files stored in
81380b57cec5SDimitry Andric     /// the AST reader.
81390b57cec5SDimitry Andric     unsigned Index;
81400b57cec5SDimitry Andric 
81410b57cec5SDimitry Andric     /// The current position within the identifier lookup table
81420b57cec5SDimitry Andric     /// of the current AST file.
81430b57cec5SDimitry Andric     ASTIdentifierLookupTable::key_iterator Current;
81440b57cec5SDimitry Andric 
81450b57cec5SDimitry Andric     /// The end position within the identifier lookup table of
81460b57cec5SDimitry Andric     /// the current AST file.
81470b57cec5SDimitry Andric     ASTIdentifierLookupTable::key_iterator End;
81480b57cec5SDimitry Andric 
81490b57cec5SDimitry Andric     /// Whether to skip any modules in the ASTReader.
81500b57cec5SDimitry Andric     bool SkipModules;
81510b57cec5SDimitry Andric 
81520b57cec5SDimitry Andric   public:
81530b57cec5SDimitry Andric     explicit ASTIdentifierIterator(const ASTReader &Reader,
81540b57cec5SDimitry Andric                                    bool SkipModules = false);
81550b57cec5SDimitry Andric 
81560b57cec5SDimitry Andric     StringRef Next() override;
81570b57cec5SDimitry Andric   };
81580b57cec5SDimitry Andric 
81590b57cec5SDimitry Andric } // namespace clang
81600b57cec5SDimitry Andric 
81610b57cec5SDimitry Andric ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
81620b57cec5SDimitry Andric                                              bool SkipModules)
81630b57cec5SDimitry Andric     : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
81640b57cec5SDimitry Andric }
81650b57cec5SDimitry Andric 
81660b57cec5SDimitry Andric StringRef ASTIdentifierIterator::Next() {
81670b57cec5SDimitry Andric   while (Current == End) {
81680b57cec5SDimitry Andric     // If we have exhausted all of our AST files, we're done.
81690b57cec5SDimitry Andric     if (Index == 0)
81700b57cec5SDimitry Andric       return StringRef();
81710b57cec5SDimitry Andric 
81720b57cec5SDimitry Andric     --Index;
81730b57cec5SDimitry Andric     ModuleFile &F = Reader.ModuleMgr[Index];
81740b57cec5SDimitry Andric     if (SkipModules && F.isModule())
81750b57cec5SDimitry Andric       continue;
81760b57cec5SDimitry Andric 
81770b57cec5SDimitry Andric     ASTIdentifierLookupTable *IdTable =
81780b57cec5SDimitry Andric         (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
81790b57cec5SDimitry Andric     Current = IdTable->key_begin();
81800b57cec5SDimitry Andric     End = IdTable->key_end();
81810b57cec5SDimitry Andric   }
81820b57cec5SDimitry Andric 
81830b57cec5SDimitry Andric   // We have any identifiers remaining in the current AST file; return
81840b57cec5SDimitry Andric   // the next one.
81850b57cec5SDimitry Andric   StringRef Result = *Current;
81860b57cec5SDimitry Andric   ++Current;
81870b57cec5SDimitry Andric   return Result;
81880b57cec5SDimitry Andric }
81890b57cec5SDimitry Andric 
81900b57cec5SDimitry Andric namespace {
81910b57cec5SDimitry Andric 
81920b57cec5SDimitry Andric /// A utility for appending two IdentifierIterators.
81930b57cec5SDimitry Andric class ChainedIdentifierIterator : public IdentifierIterator {
81940b57cec5SDimitry Andric   std::unique_ptr<IdentifierIterator> Current;
81950b57cec5SDimitry Andric   std::unique_ptr<IdentifierIterator> Queued;
81960b57cec5SDimitry Andric 
81970b57cec5SDimitry Andric public:
81980b57cec5SDimitry Andric   ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
81990b57cec5SDimitry Andric                             std::unique_ptr<IdentifierIterator> Second)
82000b57cec5SDimitry Andric       : Current(std::move(First)), Queued(std::move(Second)) {}
82010b57cec5SDimitry Andric 
82020b57cec5SDimitry Andric   StringRef Next() override {
82030b57cec5SDimitry Andric     if (!Current)
82040b57cec5SDimitry Andric       return StringRef();
82050b57cec5SDimitry Andric 
82060b57cec5SDimitry Andric     StringRef result = Current->Next();
82070b57cec5SDimitry Andric     if (!result.empty())
82080b57cec5SDimitry Andric       return result;
82090b57cec5SDimitry Andric 
82100b57cec5SDimitry Andric     // Try the queued iterator, which may itself be empty.
82110b57cec5SDimitry Andric     Current.reset();
82120b57cec5SDimitry Andric     std::swap(Current, Queued);
82130b57cec5SDimitry Andric     return Next();
82140b57cec5SDimitry Andric   }
82150b57cec5SDimitry Andric };
82160b57cec5SDimitry Andric 
82170b57cec5SDimitry Andric } // namespace
82180b57cec5SDimitry Andric 
82190b57cec5SDimitry Andric IdentifierIterator *ASTReader::getIdentifiers() {
82200b57cec5SDimitry Andric   if (!loadGlobalIndex()) {
82210b57cec5SDimitry Andric     std::unique_ptr<IdentifierIterator> ReaderIter(
82220b57cec5SDimitry Andric         new ASTIdentifierIterator(*this, /*SkipModules=*/true));
82230b57cec5SDimitry Andric     std::unique_ptr<IdentifierIterator> ModulesIter(
82240b57cec5SDimitry Andric         GlobalIndex->createIdentifierIterator());
82250b57cec5SDimitry Andric     return new ChainedIdentifierIterator(std::move(ReaderIter),
82260b57cec5SDimitry Andric                                          std::move(ModulesIter));
82270b57cec5SDimitry Andric   }
82280b57cec5SDimitry Andric 
82290b57cec5SDimitry Andric   return new ASTIdentifierIterator(*this);
82300b57cec5SDimitry Andric }
82310b57cec5SDimitry Andric 
82320b57cec5SDimitry Andric namespace clang {
82330b57cec5SDimitry Andric namespace serialization {
82340b57cec5SDimitry Andric 
82350b57cec5SDimitry Andric   class ReadMethodPoolVisitor {
82360b57cec5SDimitry Andric     ASTReader &Reader;
82370b57cec5SDimitry Andric     Selector Sel;
82380b57cec5SDimitry Andric     unsigned PriorGeneration;
82390b57cec5SDimitry Andric     unsigned InstanceBits = 0;
82400b57cec5SDimitry Andric     unsigned FactoryBits = 0;
82410b57cec5SDimitry Andric     bool InstanceHasMoreThanOneDecl = false;
82420b57cec5SDimitry Andric     bool FactoryHasMoreThanOneDecl = false;
82430b57cec5SDimitry Andric     SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
82440b57cec5SDimitry Andric     SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
82450b57cec5SDimitry Andric 
82460b57cec5SDimitry Andric   public:
82470b57cec5SDimitry Andric     ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
82480b57cec5SDimitry Andric                           unsigned PriorGeneration)
82490b57cec5SDimitry Andric         : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
82500b57cec5SDimitry Andric 
82510b57cec5SDimitry Andric     bool operator()(ModuleFile &M) {
82520b57cec5SDimitry Andric       if (!M.SelectorLookupTable)
82530b57cec5SDimitry Andric         return false;
82540b57cec5SDimitry Andric 
82550b57cec5SDimitry Andric       // If we've already searched this module file, skip it now.
82560b57cec5SDimitry Andric       if (M.Generation <= PriorGeneration)
82570b57cec5SDimitry Andric         return true;
82580b57cec5SDimitry Andric 
82590b57cec5SDimitry Andric       ++Reader.NumMethodPoolTableLookups;
82600b57cec5SDimitry Andric       ASTSelectorLookupTable *PoolTable
82610b57cec5SDimitry Andric         = (ASTSelectorLookupTable*)M.SelectorLookupTable;
82620b57cec5SDimitry Andric       ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
82630b57cec5SDimitry Andric       if (Pos == PoolTable->end())
82640b57cec5SDimitry Andric         return false;
82650b57cec5SDimitry Andric 
82660b57cec5SDimitry Andric       ++Reader.NumMethodPoolTableHits;
82670b57cec5SDimitry Andric       ++Reader.NumSelectorsRead;
82680b57cec5SDimitry Andric       // FIXME: Not quite happy with the statistics here. We probably should
82690b57cec5SDimitry Andric       // disable this tracking when called via LoadSelector.
82700b57cec5SDimitry Andric       // Also, should entries without methods count as misses?
82710b57cec5SDimitry Andric       ++Reader.NumMethodPoolEntriesRead;
82720b57cec5SDimitry Andric       ASTSelectorLookupTrait::data_type Data = *Pos;
82730b57cec5SDimitry Andric       if (Reader.DeserializationListener)
82740b57cec5SDimitry Andric         Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
82750b57cec5SDimitry Andric 
8276349cc55cSDimitry Andric       // Append methods in the reverse order, so that later we can process them
8277349cc55cSDimitry Andric       // in the order they appear in the source code by iterating through
8278349cc55cSDimitry Andric       // the vector in the reverse order.
8279349cc55cSDimitry Andric       InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
8280349cc55cSDimitry Andric       FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
82810b57cec5SDimitry Andric       InstanceBits = Data.InstanceBits;
82820b57cec5SDimitry Andric       FactoryBits = Data.FactoryBits;
82830b57cec5SDimitry Andric       InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
82840b57cec5SDimitry Andric       FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
8285349cc55cSDimitry Andric       return false;
82860b57cec5SDimitry Andric     }
82870b57cec5SDimitry Andric 
82880b57cec5SDimitry Andric     /// Retrieve the instance methods found by this visitor.
82890b57cec5SDimitry Andric     ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
82900b57cec5SDimitry Andric       return InstanceMethods;
82910b57cec5SDimitry Andric     }
82920b57cec5SDimitry Andric 
82930b57cec5SDimitry Andric     /// Retrieve the instance methods found by this visitor.
82940b57cec5SDimitry Andric     ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
82950b57cec5SDimitry Andric       return FactoryMethods;
82960b57cec5SDimitry Andric     }
82970b57cec5SDimitry Andric 
82980b57cec5SDimitry Andric     unsigned getInstanceBits() const { return InstanceBits; }
82990b57cec5SDimitry Andric     unsigned getFactoryBits() const { return FactoryBits; }
83000b57cec5SDimitry Andric 
83010b57cec5SDimitry Andric     bool instanceHasMoreThanOneDecl() const {
83020b57cec5SDimitry Andric       return InstanceHasMoreThanOneDecl;
83030b57cec5SDimitry Andric     }
83040b57cec5SDimitry Andric 
83050b57cec5SDimitry Andric     bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
83060b57cec5SDimitry Andric   };
83070b57cec5SDimitry Andric 
83080b57cec5SDimitry Andric } // namespace serialization
83090b57cec5SDimitry Andric } // namespace clang
83100b57cec5SDimitry Andric 
83110b57cec5SDimitry Andric /// Add the given set of methods to the method list.
83120b57cec5SDimitry Andric static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
83130b57cec5SDimitry Andric                              ObjCMethodList &List) {
8314*bdd1243dSDimitry Andric   for (ObjCMethodDecl *M : llvm::reverse(Methods))
8315*bdd1243dSDimitry Andric     S.addMethodToGlobalList(&List, M);
83160b57cec5SDimitry Andric }
83170b57cec5SDimitry Andric 
83180b57cec5SDimitry Andric void ASTReader::ReadMethodPool(Selector Sel) {
83190b57cec5SDimitry Andric   // Get the selector generation and update it to the current generation.
83200b57cec5SDimitry Andric   unsigned &Generation = SelectorGeneration[Sel];
83210b57cec5SDimitry Andric   unsigned PriorGeneration = Generation;
83220b57cec5SDimitry Andric   Generation = getGeneration();
83230b57cec5SDimitry Andric   SelectorOutOfDate[Sel] = false;
83240b57cec5SDimitry Andric 
83250b57cec5SDimitry Andric   // Search for methods defined with this selector.
83260b57cec5SDimitry Andric   ++NumMethodPoolLookups;
83270b57cec5SDimitry Andric   ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
83280b57cec5SDimitry Andric   ModuleMgr.visit(Visitor);
83290b57cec5SDimitry Andric 
83300b57cec5SDimitry Andric   if (Visitor.getInstanceMethods().empty() &&
83310b57cec5SDimitry Andric       Visitor.getFactoryMethods().empty())
83320b57cec5SDimitry Andric     return;
83330b57cec5SDimitry Andric 
83340b57cec5SDimitry Andric   ++NumMethodPoolHits;
83350b57cec5SDimitry Andric 
83360b57cec5SDimitry Andric   if (!getSema())
83370b57cec5SDimitry Andric     return;
83380b57cec5SDimitry Andric 
83390b57cec5SDimitry Andric   Sema &S = *getSema();
8340349cc55cSDimitry Andric   Sema::GlobalMethodPool::iterator Pos =
8341349cc55cSDimitry Andric       S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
8342349cc55cSDimitry Andric           .first;
83430b57cec5SDimitry Andric 
83440b57cec5SDimitry Andric   Pos->second.first.setBits(Visitor.getInstanceBits());
83450b57cec5SDimitry Andric   Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
83460b57cec5SDimitry Andric   Pos->second.second.setBits(Visitor.getFactoryBits());
83470b57cec5SDimitry Andric   Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
83480b57cec5SDimitry Andric 
83490b57cec5SDimitry Andric   // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
83500b57cec5SDimitry Andric   // when building a module we keep every method individually and may need to
83510b57cec5SDimitry Andric   // update hasMoreThanOneDecl as we add the methods.
83520b57cec5SDimitry Andric   addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
83530b57cec5SDimitry Andric   addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
83540b57cec5SDimitry Andric }
83550b57cec5SDimitry Andric 
83560b57cec5SDimitry Andric void ASTReader::updateOutOfDateSelector(Selector Sel) {
83570b57cec5SDimitry Andric   if (SelectorOutOfDate[Sel])
83580b57cec5SDimitry Andric     ReadMethodPool(Sel);
83590b57cec5SDimitry Andric }
83600b57cec5SDimitry Andric 
83610b57cec5SDimitry Andric void ASTReader::ReadKnownNamespaces(
83620b57cec5SDimitry Andric                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
83630b57cec5SDimitry Andric   Namespaces.clear();
83640b57cec5SDimitry Andric 
83650b57cec5SDimitry Andric   for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
83660b57cec5SDimitry Andric     if (NamespaceDecl *Namespace
83670b57cec5SDimitry Andric                 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
83680b57cec5SDimitry Andric       Namespaces.push_back(Namespace);
83690b57cec5SDimitry Andric   }
83700b57cec5SDimitry Andric }
83710b57cec5SDimitry Andric 
83720b57cec5SDimitry Andric void ASTReader::ReadUndefinedButUsed(
83730b57cec5SDimitry Andric     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
83740b57cec5SDimitry Andric   for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
83750b57cec5SDimitry Andric     NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
83760b57cec5SDimitry Andric     SourceLocation Loc =
83770b57cec5SDimitry Andric         SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
83780b57cec5SDimitry Andric     Undefined.insert(std::make_pair(D, Loc));
83790b57cec5SDimitry Andric   }
83800b57cec5SDimitry Andric }
83810b57cec5SDimitry Andric 
83820b57cec5SDimitry Andric void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
83830b57cec5SDimitry Andric     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
83840b57cec5SDimitry Andric                                                      Exprs) {
83850b57cec5SDimitry Andric   for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
83860b57cec5SDimitry Andric     FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
83870b57cec5SDimitry Andric     uint64_t Count = DelayedDeleteExprs[Idx++];
83880b57cec5SDimitry Andric     for (uint64_t C = 0; C < Count; ++C) {
83890b57cec5SDimitry Andric       SourceLocation DeleteLoc =
83900b57cec5SDimitry Andric           SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
83910b57cec5SDimitry Andric       const bool IsArrayForm = DelayedDeleteExprs[Idx++];
83920b57cec5SDimitry Andric       Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
83930b57cec5SDimitry Andric     }
83940b57cec5SDimitry Andric   }
83950b57cec5SDimitry Andric }
83960b57cec5SDimitry Andric 
83970b57cec5SDimitry Andric void ASTReader::ReadTentativeDefinitions(
83980b57cec5SDimitry Andric                   SmallVectorImpl<VarDecl *> &TentativeDefs) {
83990b57cec5SDimitry Andric   for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
84000b57cec5SDimitry Andric     VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
84010b57cec5SDimitry Andric     if (Var)
84020b57cec5SDimitry Andric       TentativeDefs.push_back(Var);
84030b57cec5SDimitry Andric   }
84040b57cec5SDimitry Andric   TentativeDefinitions.clear();
84050b57cec5SDimitry Andric }
84060b57cec5SDimitry Andric 
84070b57cec5SDimitry Andric void ASTReader::ReadUnusedFileScopedDecls(
84080b57cec5SDimitry Andric                                SmallVectorImpl<const DeclaratorDecl *> &Decls) {
84090b57cec5SDimitry Andric   for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
84100b57cec5SDimitry Andric     DeclaratorDecl *D
84110b57cec5SDimitry Andric       = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
84120b57cec5SDimitry Andric     if (D)
84130b57cec5SDimitry Andric       Decls.push_back(D);
84140b57cec5SDimitry Andric   }
84150b57cec5SDimitry Andric   UnusedFileScopedDecls.clear();
84160b57cec5SDimitry Andric }
84170b57cec5SDimitry Andric 
84180b57cec5SDimitry Andric void ASTReader::ReadDelegatingConstructors(
84190b57cec5SDimitry Andric                                  SmallVectorImpl<CXXConstructorDecl *> &Decls) {
84200b57cec5SDimitry Andric   for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
84210b57cec5SDimitry Andric     CXXConstructorDecl *D
84220b57cec5SDimitry Andric       = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
84230b57cec5SDimitry Andric     if (D)
84240b57cec5SDimitry Andric       Decls.push_back(D);
84250b57cec5SDimitry Andric   }
84260b57cec5SDimitry Andric   DelegatingCtorDecls.clear();
84270b57cec5SDimitry Andric }
84280b57cec5SDimitry Andric 
84290b57cec5SDimitry Andric void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
84300b57cec5SDimitry Andric   for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
84310b57cec5SDimitry Andric     TypedefNameDecl *D
84320b57cec5SDimitry Andric       = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
84330b57cec5SDimitry Andric     if (D)
84340b57cec5SDimitry Andric       Decls.push_back(D);
84350b57cec5SDimitry Andric   }
84360b57cec5SDimitry Andric   ExtVectorDecls.clear();
84370b57cec5SDimitry Andric }
84380b57cec5SDimitry Andric 
84390b57cec5SDimitry Andric void ASTReader::ReadUnusedLocalTypedefNameCandidates(
84400b57cec5SDimitry Andric     llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
84410b57cec5SDimitry Andric   for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
84420b57cec5SDimitry Andric        ++I) {
84430b57cec5SDimitry Andric     TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
84440b57cec5SDimitry Andric         GetDecl(UnusedLocalTypedefNameCandidates[I]));
84450b57cec5SDimitry Andric     if (D)
84460b57cec5SDimitry Andric       Decls.insert(D);
84470b57cec5SDimitry Andric   }
84480b57cec5SDimitry Andric   UnusedLocalTypedefNameCandidates.clear();
84490b57cec5SDimitry Andric }
84500b57cec5SDimitry Andric 
84515ffd83dbSDimitry Andric void ASTReader::ReadDeclsToCheckForDeferredDiags(
8452fe6060f1SDimitry Andric     llvm::SmallSetVector<Decl *, 4> &Decls) {
8453fe6060f1SDimitry Andric   for (auto I : DeclsToCheckForDeferredDiags) {
8454fe6060f1SDimitry Andric     auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
84555ffd83dbSDimitry Andric     if (D)
8456fe6060f1SDimitry Andric       Decls.insert(D);
84575ffd83dbSDimitry Andric   }
84585ffd83dbSDimitry Andric   DeclsToCheckForDeferredDiags.clear();
84595ffd83dbSDimitry Andric }
84605ffd83dbSDimitry Andric 
84610b57cec5SDimitry Andric void ASTReader::ReadReferencedSelectors(
84620b57cec5SDimitry Andric        SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
84630b57cec5SDimitry Andric   if (ReferencedSelectorsData.empty())
84640b57cec5SDimitry Andric     return;
84650b57cec5SDimitry Andric 
84660b57cec5SDimitry Andric   // If there are @selector references added them to its pool. This is for
84670b57cec5SDimitry Andric   // implementation of -Wselector.
84680b57cec5SDimitry Andric   unsigned int DataSize = ReferencedSelectorsData.size()-1;
84690b57cec5SDimitry Andric   unsigned I = 0;
84700b57cec5SDimitry Andric   while (I < DataSize) {
84710b57cec5SDimitry Andric     Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
84720b57cec5SDimitry Andric     SourceLocation SelLoc
84730b57cec5SDimitry Andric       = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
84740b57cec5SDimitry Andric     Sels.push_back(std::make_pair(Sel, SelLoc));
84750b57cec5SDimitry Andric   }
84760b57cec5SDimitry Andric   ReferencedSelectorsData.clear();
84770b57cec5SDimitry Andric }
84780b57cec5SDimitry Andric 
84790b57cec5SDimitry Andric void ASTReader::ReadWeakUndeclaredIdentifiers(
84800b57cec5SDimitry Andric        SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
84810b57cec5SDimitry Andric   if (WeakUndeclaredIdentifiers.empty())
84820b57cec5SDimitry Andric     return;
84830b57cec5SDimitry Andric 
84840b57cec5SDimitry Andric   for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
84850b57cec5SDimitry Andric     IdentifierInfo *WeakId
84860b57cec5SDimitry Andric       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
84870b57cec5SDimitry Andric     IdentifierInfo *AliasId
84880b57cec5SDimitry Andric       = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
848981ad6265SDimitry Andric     SourceLocation Loc =
849081ad6265SDimitry Andric         SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
84910b57cec5SDimitry Andric     WeakInfo WI(AliasId, Loc);
84920b57cec5SDimitry Andric     WeakIDs.push_back(std::make_pair(WeakId, WI));
84930b57cec5SDimitry Andric   }
84940b57cec5SDimitry Andric   WeakUndeclaredIdentifiers.clear();
84950b57cec5SDimitry Andric }
84960b57cec5SDimitry Andric 
84970b57cec5SDimitry Andric void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
84980b57cec5SDimitry Andric   for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
84990b57cec5SDimitry Andric     ExternalVTableUse VT;
85000b57cec5SDimitry Andric     VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
85010b57cec5SDimitry Andric     VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
85020b57cec5SDimitry Andric     VT.DefinitionRequired = VTableUses[Idx++];
85030b57cec5SDimitry Andric     VTables.push_back(VT);
85040b57cec5SDimitry Andric   }
85050b57cec5SDimitry Andric 
85060b57cec5SDimitry Andric   VTableUses.clear();
85070b57cec5SDimitry Andric }
85080b57cec5SDimitry Andric 
85090b57cec5SDimitry Andric void ASTReader::ReadPendingInstantiations(
85100b57cec5SDimitry Andric        SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
85110b57cec5SDimitry Andric   for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
85120b57cec5SDimitry Andric     ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
85130b57cec5SDimitry Andric     SourceLocation Loc
85140b57cec5SDimitry Andric       = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
85150b57cec5SDimitry Andric 
85160b57cec5SDimitry Andric     Pending.push_back(std::make_pair(D, Loc));
85170b57cec5SDimitry Andric   }
85180b57cec5SDimitry Andric   PendingInstantiations.clear();
85190b57cec5SDimitry Andric }
85200b57cec5SDimitry Andric 
85210b57cec5SDimitry Andric void ASTReader::ReadLateParsedTemplates(
85220b57cec5SDimitry Andric     llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
85230b57cec5SDimitry Andric         &LPTMap) {
8524e8d8bef9SDimitry Andric   for (auto &LPT : LateParsedTemplates) {
8525e8d8bef9SDimitry Andric     ModuleFile *FMod = LPT.first;
8526e8d8bef9SDimitry Andric     RecordDataImpl &LateParsed = LPT.second;
8527e8d8bef9SDimitry Andric     for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
85280b57cec5SDimitry Andric          /* In loop */) {
8529e8d8bef9SDimitry Andric       FunctionDecl *FD =
8530e8d8bef9SDimitry Andric           cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
85310b57cec5SDimitry Andric 
8532a7dea167SDimitry Andric       auto LT = std::make_unique<LateParsedTemplate>();
8533e8d8bef9SDimitry Andric       LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
85340b57cec5SDimitry Andric 
85350b57cec5SDimitry Andric       ModuleFile *F = getOwningModuleFile(LT->D);
85360b57cec5SDimitry Andric       assert(F && "No module");
85370b57cec5SDimitry Andric 
8538e8d8bef9SDimitry Andric       unsigned TokN = LateParsed[Idx++];
85390b57cec5SDimitry Andric       LT->Toks.reserve(TokN);
85400b57cec5SDimitry Andric       for (unsigned T = 0; T < TokN; ++T)
8541e8d8bef9SDimitry Andric         LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
85420b57cec5SDimitry Andric 
85430b57cec5SDimitry Andric       LPTMap.insert(std::make_pair(FD, std::move(LT)));
85440b57cec5SDimitry Andric     }
8545e8d8bef9SDimitry Andric   }
854669ade1e0SDimitry Andric 
854769ade1e0SDimitry Andric   LateParsedTemplates.clear();
85480b57cec5SDimitry Andric }
85490b57cec5SDimitry Andric 
85500b57cec5SDimitry Andric void ASTReader::LoadSelector(Selector Sel) {
85510b57cec5SDimitry Andric   // It would be complicated to avoid reading the methods anyway. So don't.
85520b57cec5SDimitry Andric   ReadMethodPool(Sel);
85530b57cec5SDimitry Andric }
85540b57cec5SDimitry Andric 
85550b57cec5SDimitry Andric void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
85560b57cec5SDimitry Andric   assert(ID && "Non-zero identifier ID required");
85570b57cec5SDimitry Andric   assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
85580b57cec5SDimitry Andric   IdentifiersLoaded[ID - 1] = II;
85590b57cec5SDimitry Andric   if (DeserializationListener)
85600b57cec5SDimitry Andric     DeserializationListener->IdentifierRead(ID, II);
85610b57cec5SDimitry Andric }
85620b57cec5SDimitry Andric 
85630b57cec5SDimitry Andric /// Set the globally-visible declarations associated with the given
85640b57cec5SDimitry Andric /// identifier.
85650b57cec5SDimitry Andric ///
85660b57cec5SDimitry Andric /// If the AST reader is currently in a state where the given declaration IDs
85670b57cec5SDimitry Andric /// cannot safely be resolved, they are queued until it is safe to resolve
85680b57cec5SDimitry Andric /// them.
85690b57cec5SDimitry Andric ///
85700b57cec5SDimitry Andric /// \param II an IdentifierInfo that refers to one or more globally-visible
85710b57cec5SDimitry Andric /// declarations.
85720b57cec5SDimitry Andric ///
85730b57cec5SDimitry Andric /// \param DeclIDs the set of declaration IDs with the name @p II that are
85740b57cec5SDimitry Andric /// visible at global scope.
85750b57cec5SDimitry Andric ///
85760b57cec5SDimitry Andric /// \param Decls if non-null, this vector will be populated with the set of
85770b57cec5SDimitry Andric /// deserialized declarations. These declarations will not be pushed into
85780b57cec5SDimitry Andric /// scope.
85790b57cec5SDimitry Andric void
85800b57cec5SDimitry Andric ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
85810b57cec5SDimitry Andric                               const SmallVectorImpl<uint32_t> &DeclIDs,
85820b57cec5SDimitry Andric                                    SmallVectorImpl<Decl *> *Decls) {
85830b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing && !Decls) {
85840b57cec5SDimitry Andric     PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
85850b57cec5SDimitry Andric     return;
85860b57cec5SDimitry Andric   }
85870b57cec5SDimitry Andric 
85880b57cec5SDimitry Andric   for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
85890b57cec5SDimitry Andric     if (!SemaObj) {
85900b57cec5SDimitry Andric       // Queue this declaration so that it will be added to the
85910b57cec5SDimitry Andric       // translation unit scope and identifier's declaration chain
85920b57cec5SDimitry Andric       // once a Sema object is known.
85930b57cec5SDimitry Andric       PreloadedDeclIDs.push_back(DeclIDs[I]);
85940b57cec5SDimitry Andric       continue;
85950b57cec5SDimitry Andric     }
85960b57cec5SDimitry Andric 
85970b57cec5SDimitry Andric     NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
85980b57cec5SDimitry Andric 
85990b57cec5SDimitry Andric     // If we're simply supposed to record the declarations, do so now.
86000b57cec5SDimitry Andric     if (Decls) {
86010b57cec5SDimitry Andric       Decls->push_back(D);
86020b57cec5SDimitry Andric       continue;
86030b57cec5SDimitry Andric     }
86040b57cec5SDimitry Andric 
86050b57cec5SDimitry Andric     // Introduce this declaration into the translation-unit scope
86060b57cec5SDimitry Andric     // and add it to the declaration chain for this identifier, so
86070b57cec5SDimitry Andric     // that (unqualified) name lookup will find it.
86080b57cec5SDimitry Andric     pushExternalDeclIntoScope(D, II);
86090b57cec5SDimitry Andric   }
86100b57cec5SDimitry Andric }
86110b57cec5SDimitry Andric 
86120b57cec5SDimitry Andric IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
86130b57cec5SDimitry Andric   if (ID == 0)
86140b57cec5SDimitry Andric     return nullptr;
86150b57cec5SDimitry Andric 
86160b57cec5SDimitry Andric   if (IdentifiersLoaded.empty()) {
86170b57cec5SDimitry Andric     Error("no identifier table in AST file");
86180b57cec5SDimitry Andric     return nullptr;
86190b57cec5SDimitry Andric   }
86200b57cec5SDimitry Andric 
86210b57cec5SDimitry Andric   ID -= 1;
86220b57cec5SDimitry Andric   if (!IdentifiersLoaded[ID]) {
86230b57cec5SDimitry Andric     GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
86240b57cec5SDimitry Andric     assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
86250b57cec5SDimitry Andric     ModuleFile *M = I->second;
86260b57cec5SDimitry Andric     unsigned Index = ID - M->BaseIdentifierID;
8627fe6060f1SDimitry Andric     const unsigned char *Data =
8628fe6060f1SDimitry Andric         M->IdentifierTableData + M->IdentifierOffsets[Index];
86290b57cec5SDimitry Andric 
8630fe6060f1SDimitry Andric     ASTIdentifierLookupTrait Trait(*this, *M);
8631fe6060f1SDimitry Andric     auto KeyDataLen = Trait.ReadKeyDataLength(Data);
8632fe6060f1SDimitry Andric     auto Key = Trait.ReadKey(Data, KeyDataLen.first);
8633fe6060f1SDimitry Andric     auto &II = PP.getIdentifierTable().get(Key);
86340b57cec5SDimitry Andric     IdentifiersLoaded[ID] = &II;
86350b57cec5SDimitry Andric     markIdentifierFromAST(*this,  II);
86360b57cec5SDimitry Andric     if (DeserializationListener)
86370b57cec5SDimitry Andric       DeserializationListener->IdentifierRead(ID + 1, &II);
86380b57cec5SDimitry Andric   }
86390b57cec5SDimitry Andric 
86400b57cec5SDimitry Andric   return IdentifiersLoaded[ID];
86410b57cec5SDimitry Andric }
86420b57cec5SDimitry Andric 
86430b57cec5SDimitry Andric IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
86440b57cec5SDimitry Andric   return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
86450b57cec5SDimitry Andric }
86460b57cec5SDimitry Andric 
86470b57cec5SDimitry Andric IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
86480b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_IDENT_IDS)
86490b57cec5SDimitry Andric     return LocalID;
86500b57cec5SDimitry Andric 
86510b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
86520b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
86530b57cec5SDimitry Andric 
86540b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
86550b57cec5SDimitry Andric     = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
86560b57cec5SDimitry Andric   assert(I != M.IdentifierRemap.end()
86570b57cec5SDimitry Andric          && "Invalid index into identifier index remap");
86580b57cec5SDimitry Andric 
86590b57cec5SDimitry Andric   return LocalID + I->second;
86600b57cec5SDimitry Andric }
86610b57cec5SDimitry Andric 
86620b57cec5SDimitry Andric MacroInfo *ASTReader::getMacro(MacroID ID) {
86630b57cec5SDimitry Andric   if (ID == 0)
86640b57cec5SDimitry Andric     return nullptr;
86650b57cec5SDimitry Andric 
86660b57cec5SDimitry Andric   if (MacrosLoaded.empty()) {
86670b57cec5SDimitry Andric     Error("no macro table in AST file");
86680b57cec5SDimitry Andric     return nullptr;
86690b57cec5SDimitry Andric   }
86700b57cec5SDimitry Andric 
86710b57cec5SDimitry Andric   ID -= NUM_PREDEF_MACRO_IDS;
86720b57cec5SDimitry Andric   if (!MacrosLoaded[ID]) {
86730b57cec5SDimitry Andric     GlobalMacroMapType::iterator I
86740b57cec5SDimitry Andric       = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
86750b57cec5SDimitry Andric     assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
86760b57cec5SDimitry Andric     ModuleFile *M = I->second;
86770b57cec5SDimitry Andric     unsigned Index = ID - M->BaseMacroID;
86785ffd83dbSDimitry Andric     MacrosLoaded[ID] =
86795ffd83dbSDimitry Andric         ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
86800b57cec5SDimitry Andric 
86810b57cec5SDimitry Andric     if (DeserializationListener)
86820b57cec5SDimitry Andric       DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
86830b57cec5SDimitry Andric                                          MacrosLoaded[ID]);
86840b57cec5SDimitry Andric   }
86850b57cec5SDimitry Andric 
86860b57cec5SDimitry Andric   return MacrosLoaded[ID];
86870b57cec5SDimitry Andric }
86880b57cec5SDimitry Andric 
86890b57cec5SDimitry Andric MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
86900b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_MACRO_IDS)
86910b57cec5SDimitry Andric     return LocalID;
86920b57cec5SDimitry Andric 
86930b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
86940b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
86950b57cec5SDimitry Andric 
86960b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
86970b57cec5SDimitry Andric     = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
86980b57cec5SDimitry Andric   assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
86990b57cec5SDimitry Andric 
87000b57cec5SDimitry Andric   return LocalID + I->second;
87010b57cec5SDimitry Andric }
87020b57cec5SDimitry Andric 
87030b57cec5SDimitry Andric serialization::SubmoduleID
87040b57cec5SDimitry Andric ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
87050b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
87060b57cec5SDimitry Andric     return LocalID;
87070b57cec5SDimitry Andric 
87080b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
87090b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
87100b57cec5SDimitry Andric 
87110b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
87120b57cec5SDimitry Andric     = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
87130b57cec5SDimitry Andric   assert(I != M.SubmoduleRemap.end()
87140b57cec5SDimitry Andric          && "Invalid index into submodule index remap");
87150b57cec5SDimitry Andric 
87160b57cec5SDimitry Andric   return LocalID + I->second;
87170b57cec5SDimitry Andric }
87180b57cec5SDimitry Andric 
87190b57cec5SDimitry Andric Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
87200b57cec5SDimitry Andric   if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
87210b57cec5SDimitry Andric     assert(GlobalID == 0 && "Unhandled global submodule ID");
87220b57cec5SDimitry Andric     return nullptr;
87230b57cec5SDimitry Andric   }
87240b57cec5SDimitry Andric 
87250b57cec5SDimitry Andric   if (GlobalID > SubmodulesLoaded.size()) {
87260b57cec5SDimitry Andric     Error("submodule ID out of range in AST file");
87270b57cec5SDimitry Andric     return nullptr;
87280b57cec5SDimitry Andric   }
87290b57cec5SDimitry Andric 
87300b57cec5SDimitry Andric   return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
87310b57cec5SDimitry Andric }
87320b57cec5SDimitry Andric 
87330b57cec5SDimitry Andric Module *ASTReader::getModule(unsigned ID) {
87340b57cec5SDimitry Andric   return getSubmodule(ID);
87350b57cec5SDimitry Andric }
87360b57cec5SDimitry Andric 
87370b57cec5SDimitry Andric ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
87380b57cec5SDimitry Andric   if (ID & 1) {
87390b57cec5SDimitry Andric     // It's a module, look it up by submodule ID.
87400b57cec5SDimitry Andric     auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
87410b57cec5SDimitry Andric     return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
87420b57cec5SDimitry Andric   } else {
87430b57cec5SDimitry Andric     // It's a prefix (preamble, PCH, ...). Look it up by index.
87440b57cec5SDimitry Andric     unsigned IndexFromEnd = ID >> 1;
87450b57cec5SDimitry Andric     assert(IndexFromEnd && "got reference to unknown module file");
87460b57cec5SDimitry Andric     return getModuleManager().pch_modules().end()[-IndexFromEnd];
87470b57cec5SDimitry Andric   }
87480b57cec5SDimitry Andric }
87490b57cec5SDimitry Andric 
87500b57cec5SDimitry Andric unsigned ASTReader::getModuleFileID(ModuleFile *F) {
87510b57cec5SDimitry Andric   if (!F)
87520b57cec5SDimitry Andric     return 1;
87530b57cec5SDimitry Andric 
87540b57cec5SDimitry Andric   // For a file representing a module, use the submodule ID of the top-level
87550b57cec5SDimitry Andric   // module as the file ID. For any other kind of file, the number of such
87560b57cec5SDimitry Andric   // files loaded beforehand will be the same on reload.
87570b57cec5SDimitry Andric   // FIXME: Is this true even if we have an explicit module file and a PCH?
87580b57cec5SDimitry Andric   if (F->isModule())
87590b57cec5SDimitry Andric     return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
87600b57cec5SDimitry Andric 
87610b57cec5SDimitry Andric   auto PCHModules = getModuleManager().pch_modules();
87620b57cec5SDimitry Andric   auto I = llvm::find(PCHModules, F);
87630b57cec5SDimitry Andric   assert(I != PCHModules.end() && "emitting reference to unknown file");
87640b57cec5SDimitry Andric   return (I - PCHModules.end()) << 1;
87650b57cec5SDimitry Andric }
87660b57cec5SDimitry Andric 
8767*bdd1243dSDimitry Andric std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
87685ffd83dbSDimitry Andric   if (Module *M = getSubmodule(ID))
87695ffd83dbSDimitry Andric     return ASTSourceDescriptor(*M);
87700b57cec5SDimitry Andric 
87710b57cec5SDimitry Andric   // If there is only a single PCH, return it instead.
87720b57cec5SDimitry Andric   // Chained PCH are not supported.
87730b57cec5SDimitry Andric   const auto &PCHChain = ModuleMgr.pch_modules();
87740b57cec5SDimitry Andric   if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
87750b57cec5SDimitry Andric     ModuleFile &MF = ModuleMgr.getPrimaryModule();
87760b57cec5SDimitry Andric     StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
87770b57cec5SDimitry Andric     StringRef FileName = llvm::sys::path::filename(MF.FileName);
8778*bdd1243dSDimitry Andric     return ASTSourceDescriptor(ModuleName,
8779*bdd1243dSDimitry Andric                                llvm::sys::path::parent_path(MF.FileName),
8780*bdd1243dSDimitry Andric                                FileName, MF.Signature);
87810b57cec5SDimitry Andric   }
8782*bdd1243dSDimitry Andric   return std::nullopt;
87830b57cec5SDimitry Andric }
87840b57cec5SDimitry Andric 
87850b57cec5SDimitry Andric ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
87860b57cec5SDimitry Andric   auto I = DefinitionSource.find(FD);
87870b57cec5SDimitry Andric   if (I == DefinitionSource.end())
87880b57cec5SDimitry Andric     return EK_ReplyHazy;
87890b57cec5SDimitry Andric   return I->second ? EK_Never : EK_Always;
87900b57cec5SDimitry Andric }
87910b57cec5SDimitry Andric 
87920b57cec5SDimitry Andric Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
87930b57cec5SDimitry Andric   return DecodeSelector(getGlobalSelectorID(M, LocalID));
87940b57cec5SDimitry Andric }
87950b57cec5SDimitry Andric 
87960b57cec5SDimitry Andric Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
87970b57cec5SDimitry Andric   if (ID == 0)
87980b57cec5SDimitry Andric     return Selector();
87990b57cec5SDimitry Andric 
88000b57cec5SDimitry Andric   if (ID > SelectorsLoaded.size()) {
88010b57cec5SDimitry Andric     Error("selector ID out of range in AST file");
88020b57cec5SDimitry Andric     return Selector();
88030b57cec5SDimitry Andric   }
88040b57cec5SDimitry Andric 
88050b57cec5SDimitry Andric   if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
88060b57cec5SDimitry Andric     // Load this selector from the selector table.
88070b57cec5SDimitry Andric     GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
88080b57cec5SDimitry Andric     assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
88090b57cec5SDimitry Andric     ModuleFile &M = *I->second;
88100b57cec5SDimitry Andric     ASTSelectorLookupTrait Trait(*this, M);
88110b57cec5SDimitry Andric     unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
88120b57cec5SDimitry Andric     SelectorsLoaded[ID - 1] =
88130b57cec5SDimitry Andric       Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
88140b57cec5SDimitry Andric     if (DeserializationListener)
88150b57cec5SDimitry Andric       DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
88160b57cec5SDimitry Andric   }
88170b57cec5SDimitry Andric 
88180b57cec5SDimitry Andric   return SelectorsLoaded[ID - 1];
88190b57cec5SDimitry Andric }
88200b57cec5SDimitry Andric 
88210b57cec5SDimitry Andric Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
88220b57cec5SDimitry Andric   return DecodeSelector(ID);
88230b57cec5SDimitry Andric }
88240b57cec5SDimitry Andric 
88250b57cec5SDimitry Andric uint32_t ASTReader::GetNumExternalSelectors() {
88260b57cec5SDimitry Andric   // ID 0 (the null selector) is considered an external selector.
88270b57cec5SDimitry Andric   return getTotalNumSelectors() + 1;
88280b57cec5SDimitry Andric }
88290b57cec5SDimitry Andric 
88300b57cec5SDimitry Andric serialization::SelectorID
88310b57cec5SDimitry Andric ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
88320b57cec5SDimitry Andric   if (LocalID < NUM_PREDEF_SELECTOR_IDS)
88330b57cec5SDimitry Andric     return LocalID;
88340b57cec5SDimitry Andric 
88350b57cec5SDimitry Andric   if (!M.ModuleOffsetMap.empty())
88360b57cec5SDimitry Andric     ReadModuleOffsetMap(M);
88370b57cec5SDimitry Andric 
88380b57cec5SDimitry Andric   ContinuousRangeMap<uint32_t, int, 2>::iterator I
88390b57cec5SDimitry Andric     = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
88400b57cec5SDimitry Andric   assert(I != M.SelectorRemap.end()
88410b57cec5SDimitry Andric          && "Invalid index into selector index remap");
88420b57cec5SDimitry Andric 
88430b57cec5SDimitry Andric   return LocalID + I->second;
88440b57cec5SDimitry Andric }
88450b57cec5SDimitry Andric 
8846480093f4SDimitry Andric DeclarationNameLoc
8847480093f4SDimitry Andric ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
88480b57cec5SDimitry Andric   switch (Name.getNameKind()) {
88490b57cec5SDimitry Andric   case DeclarationName::CXXConstructorName:
88500b57cec5SDimitry Andric   case DeclarationName::CXXDestructorName:
88510b57cec5SDimitry Andric   case DeclarationName::CXXConversionFunctionName:
8852fe6060f1SDimitry Andric     return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
88530b57cec5SDimitry Andric 
88540b57cec5SDimitry Andric   case DeclarationName::CXXOperatorName:
8855fe6060f1SDimitry Andric     return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
88560b57cec5SDimitry Andric 
88570b57cec5SDimitry Andric   case DeclarationName::CXXLiteralOperatorName:
8858fe6060f1SDimitry Andric     return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
8859fe6060f1SDimitry Andric         readSourceLocation());
88600b57cec5SDimitry Andric 
88610b57cec5SDimitry Andric   case DeclarationName::Identifier:
88620b57cec5SDimitry Andric   case DeclarationName::ObjCZeroArgSelector:
88630b57cec5SDimitry Andric   case DeclarationName::ObjCOneArgSelector:
88640b57cec5SDimitry Andric   case DeclarationName::ObjCMultiArgSelector:
88650b57cec5SDimitry Andric   case DeclarationName::CXXUsingDirective:
88660b57cec5SDimitry Andric   case DeclarationName::CXXDeductionGuideName:
88670b57cec5SDimitry Andric     break;
88680b57cec5SDimitry Andric   }
8869fe6060f1SDimitry Andric   return DeclarationNameLoc();
88700b57cec5SDimitry Andric }
88710b57cec5SDimitry Andric 
8872480093f4SDimitry Andric DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8873480093f4SDimitry Andric   DeclarationNameInfo NameInfo;
8874480093f4SDimitry Andric   NameInfo.setName(readDeclarationName());
8875480093f4SDimitry Andric   NameInfo.setLoc(readSourceLocation());
8876480093f4SDimitry Andric   NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8877480093f4SDimitry Andric   return NameInfo;
88780b57cec5SDimitry Andric }
88790b57cec5SDimitry Andric 
8880480093f4SDimitry Andric void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8881480093f4SDimitry Andric   Info.QualifierLoc = readNestedNameSpecifierLoc();
8882480093f4SDimitry Andric   unsigned NumTPLists = readInt();
88830b57cec5SDimitry Andric   Info.NumTemplParamLists = NumTPLists;
88840b57cec5SDimitry Andric   if (NumTPLists) {
88850b57cec5SDimitry Andric     Info.TemplParamLists =
88860b57cec5SDimitry Andric         new (getContext()) TemplateParameterList *[NumTPLists];
88870b57cec5SDimitry Andric     for (unsigned i = 0; i != NumTPLists; ++i)
8888480093f4SDimitry Andric       Info.TemplParamLists[i] = readTemplateParameterList();
88890b57cec5SDimitry Andric   }
88900b57cec5SDimitry Andric }
88910b57cec5SDimitry Andric 
88920b57cec5SDimitry Andric TemplateParameterList *
8893480093f4SDimitry Andric ASTRecordReader::readTemplateParameterList() {
8894480093f4SDimitry Andric   SourceLocation TemplateLoc = readSourceLocation();
8895480093f4SDimitry Andric   SourceLocation LAngleLoc = readSourceLocation();
8896480093f4SDimitry Andric   SourceLocation RAngleLoc = readSourceLocation();
88970b57cec5SDimitry Andric 
8898480093f4SDimitry Andric   unsigned NumParams = readInt();
88990b57cec5SDimitry Andric   SmallVector<NamedDecl *, 16> Params;
89000b57cec5SDimitry Andric   Params.reserve(NumParams);
89010b57cec5SDimitry Andric   while (NumParams--)
8902480093f4SDimitry Andric     Params.push_back(readDeclAs<NamedDecl>());
89030b57cec5SDimitry Andric 
8904480093f4SDimitry Andric   bool HasRequiresClause = readBool();
8905480093f4SDimitry Andric   Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
8906a7dea167SDimitry Andric 
89070b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8908a7dea167SDimitry Andric       getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
89090b57cec5SDimitry Andric   return TemplateParams;
89100b57cec5SDimitry Andric }
89110b57cec5SDimitry Andric 
8912480093f4SDimitry Andric void ASTRecordReader::readTemplateArgumentList(
8913480093f4SDimitry Andric                         SmallVectorImpl<TemplateArgument> &TemplArgs,
8914480093f4SDimitry Andric                         bool Canonicalize) {
8915480093f4SDimitry Andric   unsigned NumTemplateArgs = readInt();
89160b57cec5SDimitry Andric   TemplArgs.reserve(NumTemplateArgs);
89170b57cec5SDimitry Andric   while (NumTemplateArgs--)
8918480093f4SDimitry Andric     TemplArgs.push_back(readTemplateArgument(Canonicalize));
89190b57cec5SDimitry Andric }
89200b57cec5SDimitry Andric 
89210b57cec5SDimitry Andric /// Read a UnresolvedSet structure.
8922480093f4SDimitry Andric void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8923480093f4SDimitry Andric   unsigned NumDecls = readInt();
89240b57cec5SDimitry Andric   Set.reserve(getContext(), NumDecls);
89250b57cec5SDimitry Andric   while (NumDecls--) {
8926480093f4SDimitry Andric     DeclID ID = readDeclID();
8927480093f4SDimitry Andric     AccessSpecifier AS = (AccessSpecifier) readInt();
89280b57cec5SDimitry Andric     Set.addLazyDecl(getContext(), ID, AS);
89290b57cec5SDimitry Andric   }
89300b57cec5SDimitry Andric }
89310b57cec5SDimitry Andric 
89320b57cec5SDimitry Andric CXXBaseSpecifier
8933480093f4SDimitry Andric ASTRecordReader::readCXXBaseSpecifier() {
8934480093f4SDimitry Andric   bool isVirtual = readBool();
8935480093f4SDimitry Andric   bool isBaseOfClass = readBool();
8936480093f4SDimitry Andric   AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8937480093f4SDimitry Andric   bool inheritConstructors = readBool();
8938480093f4SDimitry Andric   TypeSourceInfo *TInfo = readTypeSourceInfo();
8939480093f4SDimitry Andric   SourceRange Range = readSourceRange();
8940480093f4SDimitry Andric   SourceLocation EllipsisLoc = readSourceLocation();
89410b57cec5SDimitry Andric   CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
89420b57cec5SDimitry Andric                           EllipsisLoc);
89430b57cec5SDimitry Andric   Result.setInheritConstructors(inheritConstructors);
89440b57cec5SDimitry Andric   return Result;
89450b57cec5SDimitry Andric }
89460b57cec5SDimitry Andric 
89470b57cec5SDimitry Andric CXXCtorInitializer **
8948480093f4SDimitry Andric ASTRecordReader::readCXXCtorInitializers() {
89490b57cec5SDimitry Andric   ASTContext &Context = getContext();
8950480093f4SDimitry Andric   unsigned NumInitializers = readInt();
89510b57cec5SDimitry Andric   assert(NumInitializers && "wrote ctor initializers but have no inits");
89520b57cec5SDimitry Andric   auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
89530b57cec5SDimitry Andric   for (unsigned i = 0; i != NumInitializers; ++i) {
89540b57cec5SDimitry Andric     TypeSourceInfo *TInfo = nullptr;
89550b57cec5SDimitry Andric     bool IsBaseVirtual = false;
89560b57cec5SDimitry Andric     FieldDecl *Member = nullptr;
89570b57cec5SDimitry Andric     IndirectFieldDecl *IndirectMember = nullptr;
89580b57cec5SDimitry Andric 
8959480093f4SDimitry Andric     CtorInitializerType Type = (CtorInitializerType) readInt();
89600b57cec5SDimitry Andric     switch (Type) {
89610b57cec5SDimitry Andric     case CTOR_INITIALIZER_BASE:
8962480093f4SDimitry Andric       TInfo = readTypeSourceInfo();
8963480093f4SDimitry Andric       IsBaseVirtual = readBool();
89640b57cec5SDimitry Andric       break;
89650b57cec5SDimitry Andric 
89660b57cec5SDimitry Andric     case CTOR_INITIALIZER_DELEGATING:
8967480093f4SDimitry Andric       TInfo = readTypeSourceInfo();
89680b57cec5SDimitry Andric       break;
89690b57cec5SDimitry Andric 
89700b57cec5SDimitry Andric      case CTOR_INITIALIZER_MEMBER:
8971480093f4SDimitry Andric       Member = readDeclAs<FieldDecl>();
89720b57cec5SDimitry Andric       break;
89730b57cec5SDimitry Andric 
89740b57cec5SDimitry Andric      case CTOR_INITIALIZER_INDIRECT_MEMBER:
8975480093f4SDimitry Andric       IndirectMember = readDeclAs<IndirectFieldDecl>();
89760b57cec5SDimitry Andric       break;
89770b57cec5SDimitry Andric     }
89780b57cec5SDimitry Andric 
8979480093f4SDimitry Andric     SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8980480093f4SDimitry Andric     Expr *Init = readExpr();
8981480093f4SDimitry Andric     SourceLocation LParenLoc = readSourceLocation();
8982480093f4SDimitry Andric     SourceLocation RParenLoc = readSourceLocation();
89830b57cec5SDimitry Andric 
89840b57cec5SDimitry Andric     CXXCtorInitializer *BOMInit;
89850b57cec5SDimitry Andric     if (Type == CTOR_INITIALIZER_BASE)
89860b57cec5SDimitry Andric       BOMInit = new (Context)
89870b57cec5SDimitry Andric           CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
89880b57cec5SDimitry Andric                              RParenLoc, MemberOrEllipsisLoc);
89890b57cec5SDimitry Andric     else if (Type == CTOR_INITIALIZER_DELEGATING)
89900b57cec5SDimitry Andric       BOMInit = new (Context)
89910b57cec5SDimitry Andric           CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
89920b57cec5SDimitry Andric     else if (Member)
89930b57cec5SDimitry Andric       BOMInit = new (Context)
89940b57cec5SDimitry Andric           CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
89950b57cec5SDimitry Andric                              Init, RParenLoc);
89960b57cec5SDimitry Andric     else
89970b57cec5SDimitry Andric       BOMInit = new (Context)
89980b57cec5SDimitry Andric           CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
89990b57cec5SDimitry Andric                              LParenLoc, Init, RParenLoc);
90000b57cec5SDimitry Andric 
9001480093f4SDimitry Andric     if (/*IsWritten*/readBool()) {
9002480093f4SDimitry Andric       unsigned SourceOrder = readInt();
90030b57cec5SDimitry Andric       BOMInit->setSourceOrder(SourceOrder);
90040b57cec5SDimitry Andric     }
90050b57cec5SDimitry Andric 
90060b57cec5SDimitry Andric     CtorInitializers[i] = BOMInit;
90070b57cec5SDimitry Andric   }
90080b57cec5SDimitry Andric 
90090b57cec5SDimitry Andric   return CtorInitializers;
90100b57cec5SDimitry Andric }
90110b57cec5SDimitry Andric 
90120b57cec5SDimitry Andric NestedNameSpecifierLoc
9013480093f4SDimitry Andric ASTRecordReader::readNestedNameSpecifierLoc() {
90140b57cec5SDimitry Andric   ASTContext &Context = getContext();
9015480093f4SDimitry Andric   unsigned N = readInt();
90160b57cec5SDimitry Andric   NestedNameSpecifierLocBuilder Builder;
90170b57cec5SDimitry Andric   for (unsigned I = 0; I != N; ++I) {
9018480093f4SDimitry Andric     auto Kind = readNestedNameSpecifierKind();
90190b57cec5SDimitry Andric     switch (Kind) {
90200b57cec5SDimitry Andric     case NestedNameSpecifier::Identifier: {
9021480093f4SDimitry Andric       IdentifierInfo *II = readIdentifier();
9022480093f4SDimitry Andric       SourceRange Range = readSourceRange();
90230b57cec5SDimitry Andric       Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
90240b57cec5SDimitry Andric       break;
90250b57cec5SDimitry Andric     }
90260b57cec5SDimitry Andric 
90270b57cec5SDimitry Andric     case NestedNameSpecifier::Namespace: {
9028480093f4SDimitry Andric       NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
9029480093f4SDimitry Andric       SourceRange Range = readSourceRange();
90300b57cec5SDimitry Andric       Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
90310b57cec5SDimitry Andric       break;
90320b57cec5SDimitry Andric     }
90330b57cec5SDimitry Andric 
90340b57cec5SDimitry Andric     case NestedNameSpecifier::NamespaceAlias: {
9035480093f4SDimitry Andric       NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
9036480093f4SDimitry Andric       SourceRange Range = readSourceRange();
90370b57cec5SDimitry Andric       Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
90380b57cec5SDimitry Andric       break;
90390b57cec5SDimitry Andric     }
90400b57cec5SDimitry Andric 
90410b57cec5SDimitry Andric     case NestedNameSpecifier::TypeSpec:
90420b57cec5SDimitry Andric     case NestedNameSpecifier::TypeSpecWithTemplate: {
9043480093f4SDimitry Andric       bool Template = readBool();
9044480093f4SDimitry Andric       TypeSourceInfo *T = readTypeSourceInfo();
90450b57cec5SDimitry Andric       if (!T)
90460b57cec5SDimitry Andric         return NestedNameSpecifierLoc();
9047480093f4SDimitry Andric       SourceLocation ColonColonLoc = readSourceLocation();
90480b57cec5SDimitry Andric 
90490b57cec5SDimitry Andric       // FIXME: 'template' keyword location not saved anywhere, so we fake it.
90500b57cec5SDimitry Andric       Builder.Extend(Context,
90510b57cec5SDimitry Andric                      Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
90520b57cec5SDimitry Andric                      T->getTypeLoc(), ColonColonLoc);
90530b57cec5SDimitry Andric       break;
90540b57cec5SDimitry Andric     }
90550b57cec5SDimitry Andric 
90560b57cec5SDimitry Andric     case NestedNameSpecifier::Global: {
9057480093f4SDimitry Andric       SourceLocation ColonColonLoc = readSourceLocation();
90580b57cec5SDimitry Andric       Builder.MakeGlobal(Context, ColonColonLoc);
90590b57cec5SDimitry Andric       break;
90600b57cec5SDimitry Andric     }
90610b57cec5SDimitry Andric 
90620b57cec5SDimitry Andric     case NestedNameSpecifier::Super: {
9063480093f4SDimitry Andric       CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
9064480093f4SDimitry Andric       SourceRange Range = readSourceRange();
90650b57cec5SDimitry Andric       Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
90660b57cec5SDimitry Andric       break;
90670b57cec5SDimitry Andric     }
90680b57cec5SDimitry Andric     }
90690b57cec5SDimitry Andric   }
90700b57cec5SDimitry Andric 
90710b57cec5SDimitry Andric   return Builder.getWithLocInContext(Context);
90720b57cec5SDimitry Andric }
90730b57cec5SDimitry Andric 
907481ad6265SDimitry Andric SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
907581ad6265SDimitry Andric                                        unsigned &Idx, LocSeq *Seq) {
907681ad6265SDimitry Andric   SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
907781ad6265SDimitry Andric   SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
90780b57cec5SDimitry Andric   return SourceRange(beg, end);
90790b57cec5SDimitry Andric }
90800b57cec5SDimitry Andric 
90810b57cec5SDimitry Andric /// Read a floating-point value
9082480093f4SDimitry Andric llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
9083480093f4SDimitry Andric   return llvm::APFloat(Sem, readAPInt());
90840b57cec5SDimitry Andric }
90850b57cec5SDimitry Andric 
90860b57cec5SDimitry Andric // Read a string
90870b57cec5SDimitry Andric std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
90880b57cec5SDimitry Andric   unsigned Len = Record[Idx++];
90890b57cec5SDimitry Andric   std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
90900b57cec5SDimitry Andric   Idx += Len;
90910b57cec5SDimitry Andric   return Result;
90920b57cec5SDimitry Andric }
90930b57cec5SDimitry Andric 
90940b57cec5SDimitry Andric std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
90950b57cec5SDimitry Andric                                 unsigned &Idx) {
90960b57cec5SDimitry Andric   std::string Filename = ReadString(Record, Idx);
90970b57cec5SDimitry Andric   ResolveImportedPath(F, Filename);
90980b57cec5SDimitry Andric   return Filename;
90990b57cec5SDimitry Andric }
91000b57cec5SDimitry Andric 
91010b57cec5SDimitry Andric std::string ASTReader::ReadPath(StringRef BaseDirectory,
91020b57cec5SDimitry Andric                                 const RecordData &Record, unsigned &Idx) {
91030b57cec5SDimitry Andric   std::string Filename = ReadString(Record, Idx);
91040b57cec5SDimitry Andric   if (!BaseDirectory.empty())
91050b57cec5SDimitry Andric     ResolveImportedPath(Filename, BaseDirectory);
91060b57cec5SDimitry Andric   return Filename;
91070b57cec5SDimitry Andric }
91080b57cec5SDimitry Andric 
91090b57cec5SDimitry Andric VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
91100b57cec5SDimitry Andric                                          unsigned &Idx) {
91110b57cec5SDimitry Andric   unsigned Major = Record[Idx++];
91120b57cec5SDimitry Andric   unsigned Minor = Record[Idx++];
91130b57cec5SDimitry Andric   unsigned Subminor = Record[Idx++];
91140b57cec5SDimitry Andric   if (Minor == 0)
91150b57cec5SDimitry Andric     return VersionTuple(Major);
91160b57cec5SDimitry Andric   if (Subminor == 0)
91170b57cec5SDimitry Andric     return VersionTuple(Major, Minor - 1);
91180b57cec5SDimitry Andric   return VersionTuple(Major, Minor - 1, Subminor - 1);
91190b57cec5SDimitry Andric }
91200b57cec5SDimitry Andric 
91210b57cec5SDimitry Andric CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
91220b57cec5SDimitry Andric                                           const RecordData &Record,
91230b57cec5SDimitry Andric                                           unsigned &Idx) {
91240b57cec5SDimitry Andric   CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
91250b57cec5SDimitry Andric   return CXXTemporary::Create(getContext(), Decl);
91260b57cec5SDimitry Andric }
91270b57cec5SDimitry Andric 
91280b57cec5SDimitry Andric DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
91290b57cec5SDimitry Andric   return Diag(CurrentImportLoc, DiagID);
91300b57cec5SDimitry Andric }
91310b57cec5SDimitry Andric 
91320b57cec5SDimitry Andric DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
91330b57cec5SDimitry Andric   return Diags.Report(Loc, DiagID);
91340b57cec5SDimitry Andric }
91350b57cec5SDimitry Andric 
91360b57cec5SDimitry Andric /// Retrieve the identifier table associated with the
91370b57cec5SDimitry Andric /// preprocessor.
91380b57cec5SDimitry Andric IdentifierTable &ASTReader::getIdentifierTable() {
91390b57cec5SDimitry Andric   return PP.getIdentifierTable();
91400b57cec5SDimitry Andric }
91410b57cec5SDimitry Andric 
91420b57cec5SDimitry Andric /// Record that the given ID maps to the given switch-case
91430b57cec5SDimitry Andric /// statement.
91440b57cec5SDimitry Andric void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
91450b57cec5SDimitry Andric   assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
91460b57cec5SDimitry Andric          "Already have a SwitchCase with this ID");
91470b57cec5SDimitry Andric   (*CurrSwitchCaseStmts)[ID] = SC;
91480b57cec5SDimitry Andric }
91490b57cec5SDimitry Andric 
91500b57cec5SDimitry Andric /// Retrieve the switch-case statement with the given ID.
91510b57cec5SDimitry Andric SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
91520b57cec5SDimitry Andric   assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
91530b57cec5SDimitry Andric   return (*CurrSwitchCaseStmts)[ID];
91540b57cec5SDimitry Andric }
91550b57cec5SDimitry Andric 
91560b57cec5SDimitry Andric void ASTReader::ClearSwitchCaseIDs() {
91570b57cec5SDimitry Andric   CurrSwitchCaseStmts->clear();
91580b57cec5SDimitry Andric }
91590b57cec5SDimitry Andric 
91600b57cec5SDimitry Andric void ASTReader::ReadComments() {
91610b57cec5SDimitry Andric   ASTContext &Context = getContext();
91620b57cec5SDimitry Andric   std::vector<RawComment *> Comments;
91630b57cec5SDimitry Andric   for (SmallVectorImpl<std::pair<BitstreamCursor,
91640b57cec5SDimitry Andric                                  serialization::ModuleFile *>>::iterator
91650b57cec5SDimitry Andric        I = CommentsCursors.begin(),
91660b57cec5SDimitry Andric        E = CommentsCursors.end();
91670b57cec5SDimitry Andric        I != E; ++I) {
91680b57cec5SDimitry Andric     Comments.clear();
91690b57cec5SDimitry Andric     BitstreamCursor &Cursor = I->first;
91700b57cec5SDimitry Andric     serialization::ModuleFile &F = *I->second;
91710b57cec5SDimitry Andric     SavedStreamPosition SavedPosition(Cursor);
91720b57cec5SDimitry Andric 
91730b57cec5SDimitry Andric     RecordData Record;
91740b57cec5SDimitry Andric     while (true) {
91750b57cec5SDimitry Andric       Expected<llvm::BitstreamEntry> MaybeEntry =
91760b57cec5SDimitry Andric           Cursor.advanceSkippingSubblocks(
91770b57cec5SDimitry Andric               BitstreamCursor::AF_DontPopBlockAtEnd);
91780b57cec5SDimitry Andric       if (!MaybeEntry) {
91790b57cec5SDimitry Andric         Error(MaybeEntry.takeError());
91800b57cec5SDimitry Andric         return;
91810b57cec5SDimitry Andric       }
91820b57cec5SDimitry Andric       llvm::BitstreamEntry Entry = MaybeEntry.get();
91830b57cec5SDimitry Andric 
91840b57cec5SDimitry Andric       switch (Entry.Kind) {
91850b57cec5SDimitry Andric       case llvm::BitstreamEntry::SubBlock: // Handled for us already.
91860b57cec5SDimitry Andric       case llvm::BitstreamEntry::Error:
91870b57cec5SDimitry Andric         Error("malformed block record in AST file");
91880b57cec5SDimitry Andric         return;
91890b57cec5SDimitry Andric       case llvm::BitstreamEntry::EndBlock:
91900b57cec5SDimitry Andric         goto NextCursor;
91910b57cec5SDimitry Andric       case llvm::BitstreamEntry::Record:
91920b57cec5SDimitry Andric         // The interesting case.
91930b57cec5SDimitry Andric         break;
91940b57cec5SDimitry Andric       }
91950b57cec5SDimitry Andric 
91960b57cec5SDimitry Andric       // Read a record.
91970b57cec5SDimitry Andric       Record.clear();
91980b57cec5SDimitry Andric       Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
91990b57cec5SDimitry Andric       if (!MaybeComment) {
92000b57cec5SDimitry Andric         Error(MaybeComment.takeError());
92010b57cec5SDimitry Andric         return;
92020b57cec5SDimitry Andric       }
92030b57cec5SDimitry Andric       switch ((CommentRecordTypes)MaybeComment.get()) {
92040b57cec5SDimitry Andric       case COMMENTS_RAW_COMMENT: {
92050b57cec5SDimitry Andric         unsigned Idx = 0;
92060b57cec5SDimitry Andric         SourceRange SR = ReadSourceRange(F, Record, Idx);
92070b57cec5SDimitry Andric         RawComment::CommentKind Kind =
92080b57cec5SDimitry Andric             (RawComment::CommentKind) Record[Idx++];
92090b57cec5SDimitry Andric         bool IsTrailingComment = Record[Idx++];
92100b57cec5SDimitry Andric         bool IsAlmostTrailingComment = Record[Idx++];
92110b57cec5SDimitry Andric         Comments.push_back(new (Context) RawComment(
92120b57cec5SDimitry Andric             SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
92130b57cec5SDimitry Andric         break;
92140b57cec5SDimitry Andric       }
92150b57cec5SDimitry Andric       }
92160b57cec5SDimitry Andric     }
92170b57cec5SDimitry Andric   NextCursor:
9218a7dea167SDimitry Andric     llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9219a7dea167SDimitry Andric         FileToOffsetToComment;
9220a7dea167SDimitry Andric     for (RawComment *C : Comments) {
9221a7dea167SDimitry Andric       SourceLocation CommentLoc = C->getBeginLoc();
9222a7dea167SDimitry Andric       if (CommentLoc.isValid()) {
9223a7dea167SDimitry Andric         std::pair<FileID, unsigned> Loc =
9224a7dea167SDimitry Andric             SourceMgr.getDecomposedLoc(CommentLoc);
9225a7dea167SDimitry Andric         if (Loc.first.isValid())
9226a7dea167SDimitry Andric           Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9227a7dea167SDimitry Andric       }
9228a7dea167SDimitry Andric     }
92290b57cec5SDimitry Andric   }
92300b57cec5SDimitry Andric }
92310b57cec5SDimitry Andric 
92320b57cec5SDimitry Andric void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
92330b57cec5SDimitry Andric                                 bool IncludeSystem, bool Complain,
92340b57cec5SDimitry Andric                     llvm::function_ref<void(const serialization::InputFile &IF,
92350b57cec5SDimitry Andric                                             bool isSystem)> Visitor) {
92360b57cec5SDimitry Andric   unsigned NumUserInputs = MF.NumUserInputFiles;
92370b57cec5SDimitry Andric   unsigned NumInputs = MF.InputFilesLoaded.size();
92380b57cec5SDimitry Andric   assert(NumUserInputs <= NumInputs);
92390b57cec5SDimitry Andric   unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
92400b57cec5SDimitry Andric   for (unsigned I = 0; I < N; ++I) {
92410b57cec5SDimitry Andric     bool IsSystem = I >= NumUserInputs;
92420b57cec5SDimitry Andric     InputFile IF = getInputFile(MF, I+1, Complain);
92430b57cec5SDimitry Andric     Visitor(IF, IsSystem);
92440b57cec5SDimitry Andric   }
92450b57cec5SDimitry Andric }
92460b57cec5SDimitry Andric 
92470b57cec5SDimitry Andric void ASTReader::visitTopLevelModuleMaps(
92480b57cec5SDimitry Andric     serialization::ModuleFile &MF,
9249*bdd1243dSDimitry Andric     llvm::function_ref<void(FileEntryRef FE)> Visitor) {
92500b57cec5SDimitry Andric   unsigned NumInputs = MF.InputFilesLoaded.size();
92510b57cec5SDimitry Andric   for (unsigned I = 0; I < NumInputs; ++I) {
9252*bdd1243dSDimitry Andric     InputFileInfo IFI = getInputFileInfo(MF, I + 1);
92530b57cec5SDimitry Andric     if (IFI.TopLevelModuleMap)
9254e8d8bef9SDimitry Andric       if (auto FE = getInputFile(MF, I + 1).getFile())
9255*bdd1243dSDimitry Andric         Visitor(*FE);
92560b57cec5SDimitry Andric   }
92570b57cec5SDimitry Andric }
92580b57cec5SDimitry Andric 
92590b57cec5SDimitry Andric void ASTReader::finishPendingActions() {
92600b57cec5SDimitry Andric   while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
92610b57cec5SDimitry Andric          !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
92620b57cec5SDimitry Andric          !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
926381ad6265SDimitry Andric          !PendingUpdateRecords.empty() ||
926481ad6265SDimitry Andric          !PendingObjCExtensionIvarRedeclarations.empty()) {
92650b57cec5SDimitry Andric     // If any identifiers with corresponding top-level declarations have
92660b57cec5SDimitry Andric     // been loaded, load those declarations now.
92670b57cec5SDimitry Andric     using TopLevelDeclsMap =
92680b57cec5SDimitry Andric         llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
92690b57cec5SDimitry Andric     TopLevelDeclsMap TopLevelDecls;
92700b57cec5SDimitry Andric 
92710b57cec5SDimitry Andric     while (!PendingIdentifierInfos.empty()) {
92720b57cec5SDimitry Andric       IdentifierInfo *II = PendingIdentifierInfos.back().first;
92730b57cec5SDimitry Andric       SmallVector<uint32_t, 4> DeclIDs =
92740b57cec5SDimitry Andric           std::move(PendingIdentifierInfos.back().second);
92750b57cec5SDimitry Andric       PendingIdentifierInfos.pop_back();
92760b57cec5SDimitry Andric 
92770b57cec5SDimitry Andric       SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
92780b57cec5SDimitry Andric     }
92790b57cec5SDimitry Andric 
92800b57cec5SDimitry Andric     // Load each function type that we deferred loading because it was a
92810b57cec5SDimitry Andric     // deduced type that might refer to a local type declared within itself.
92820b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
92830b57cec5SDimitry Andric       auto *FD = PendingFunctionTypes[I].first;
92840b57cec5SDimitry Andric       FD->setType(GetType(PendingFunctionTypes[I].second));
92850b57cec5SDimitry Andric 
92860b57cec5SDimitry Andric       // If we gave a function a deduced return type, remember that we need to
92870b57cec5SDimitry Andric       // propagate that along the redeclaration chain.
92880b57cec5SDimitry Andric       auto *DT = FD->getReturnType()->getContainedDeducedType();
92890b57cec5SDimitry Andric       if (DT && DT->isDeduced())
92900b57cec5SDimitry Andric         PendingDeducedTypeUpdates.insert(
92910b57cec5SDimitry Andric             {FD->getCanonicalDecl(), FD->getReturnType()});
92920b57cec5SDimitry Andric     }
92930b57cec5SDimitry Andric     PendingFunctionTypes.clear();
92940b57cec5SDimitry Andric 
92950b57cec5SDimitry Andric     // For each decl chain that we wanted to complete while deserializing, mark
92960b57cec5SDimitry Andric     // it as "still needs to be completed".
92970b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
92980b57cec5SDimitry Andric       markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
92990b57cec5SDimitry Andric     }
93000b57cec5SDimitry Andric     PendingIncompleteDeclChains.clear();
93010b57cec5SDimitry Andric 
93020b57cec5SDimitry Andric     // Load pending declaration chains.
93030b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
93040b57cec5SDimitry Andric       loadPendingDeclChain(PendingDeclChains[I].first,
93050b57cec5SDimitry Andric                            PendingDeclChains[I].second);
93060b57cec5SDimitry Andric     PendingDeclChains.clear();
93070b57cec5SDimitry Andric 
93080b57cec5SDimitry Andric     // Make the most recent of the top-level declarations visible.
93090b57cec5SDimitry Andric     for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
93100b57cec5SDimitry Andric            TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
93110b57cec5SDimitry Andric       IdentifierInfo *II = TLD->first;
93120b57cec5SDimitry Andric       for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
93130b57cec5SDimitry Andric         pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
93140b57cec5SDimitry Andric       }
93150b57cec5SDimitry Andric     }
93160b57cec5SDimitry Andric 
93170b57cec5SDimitry Andric     // Load any pending macro definitions.
93180b57cec5SDimitry Andric     for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
93190b57cec5SDimitry Andric       IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
93200b57cec5SDimitry Andric       SmallVector<PendingMacroInfo, 2> GlobalIDs;
93210b57cec5SDimitry Andric       GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
93220b57cec5SDimitry Andric       // Initialize the macro history from chained-PCHs ahead of module imports.
93230b57cec5SDimitry Andric       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
93240b57cec5SDimitry Andric            ++IDIdx) {
93250b57cec5SDimitry Andric         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
93260b57cec5SDimitry Andric         if (!Info.M->isModule())
93270b57cec5SDimitry Andric           resolvePendingMacro(II, Info);
93280b57cec5SDimitry Andric       }
93290b57cec5SDimitry Andric       // Handle module imports.
93300b57cec5SDimitry Andric       for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
93310b57cec5SDimitry Andric            ++IDIdx) {
93320b57cec5SDimitry Andric         const PendingMacroInfo &Info = GlobalIDs[IDIdx];
93330b57cec5SDimitry Andric         if (Info.M->isModule())
93340b57cec5SDimitry Andric           resolvePendingMacro(II, Info);
93350b57cec5SDimitry Andric       }
93360b57cec5SDimitry Andric     }
93370b57cec5SDimitry Andric     PendingMacroIDs.clear();
93380b57cec5SDimitry Andric 
93390b57cec5SDimitry Andric     // Wire up the DeclContexts for Decls that we delayed setting until
93400b57cec5SDimitry Andric     // recursive loading is completed.
93410b57cec5SDimitry Andric     while (!PendingDeclContextInfos.empty()) {
93420b57cec5SDimitry Andric       PendingDeclContextInfo Info = PendingDeclContextInfos.front();
93430b57cec5SDimitry Andric       PendingDeclContextInfos.pop_front();
93440b57cec5SDimitry Andric       DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
93450b57cec5SDimitry Andric       DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
93460b57cec5SDimitry Andric       Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
93470b57cec5SDimitry Andric     }
93480b57cec5SDimitry Andric 
93490b57cec5SDimitry Andric     // Perform any pending declaration updates.
93500b57cec5SDimitry Andric     while (!PendingUpdateRecords.empty()) {
93510b57cec5SDimitry Andric       auto Update = PendingUpdateRecords.pop_back_val();
93520b57cec5SDimitry Andric       ReadingKindTracker ReadingKind(Read_Decl, *this);
93530b57cec5SDimitry Andric       loadDeclUpdateRecords(Update);
93540b57cec5SDimitry Andric     }
935581ad6265SDimitry Andric 
935681ad6265SDimitry Andric     while (!PendingObjCExtensionIvarRedeclarations.empty()) {
935781ad6265SDimitry Andric       auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
935881ad6265SDimitry Andric       auto DuplicateIvars =
935981ad6265SDimitry Andric           PendingObjCExtensionIvarRedeclarations.back().second;
936081ad6265SDimitry Andric       llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
936181ad6265SDimitry Andric       StructuralEquivalenceContext Ctx(
936281ad6265SDimitry Andric           ExtensionsPair.first->getASTContext(),
936381ad6265SDimitry Andric           ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
936481ad6265SDimitry Andric           StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
936581ad6265SDimitry Andric           /*Complain =*/false,
936681ad6265SDimitry Andric           /*ErrorOnTagTypeMismatch =*/true);
936781ad6265SDimitry Andric       if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
936881ad6265SDimitry Andric         // Merge redeclared ivars with their predecessors.
936981ad6265SDimitry Andric         for (auto IvarPair : DuplicateIvars) {
937081ad6265SDimitry Andric           ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
937181ad6265SDimitry Andric           // Change semantic DeclContext but keep the lexical one.
937281ad6265SDimitry Andric           Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
937381ad6265SDimitry Andric                                     Ivar->getLexicalDeclContext(),
937481ad6265SDimitry Andric                                     getContext());
937581ad6265SDimitry Andric           getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
937681ad6265SDimitry Andric         }
937781ad6265SDimitry Andric         // Invalidate duplicate extension and the cached ivar list.
937881ad6265SDimitry Andric         ExtensionsPair.first->setInvalidDecl();
937981ad6265SDimitry Andric         ExtensionsPair.second->getClassInterface()
938081ad6265SDimitry Andric             ->getDefinition()
938181ad6265SDimitry Andric             ->setIvarList(nullptr);
938281ad6265SDimitry Andric       } else {
938381ad6265SDimitry Andric         for (auto IvarPair : DuplicateIvars) {
938481ad6265SDimitry Andric           Diag(IvarPair.first->getLocation(),
938581ad6265SDimitry Andric                diag::err_duplicate_ivar_declaration)
938681ad6265SDimitry Andric               << IvarPair.first->getIdentifier();
938781ad6265SDimitry Andric           Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
938881ad6265SDimitry Andric         }
938981ad6265SDimitry Andric       }
939081ad6265SDimitry Andric       PendingObjCExtensionIvarRedeclarations.pop_back();
939181ad6265SDimitry Andric     }
93920b57cec5SDimitry Andric   }
93930b57cec5SDimitry Andric 
93940b57cec5SDimitry Andric   // At this point, all update records for loaded decls are in place, so any
93950b57cec5SDimitry Andric   // fake class definitions should have become real.
93960b57cec5SDimitry Andric   assert(PendingFakeDefinitionData.empty() &&
93970b57cec5SDimitry Andric          "faked up a class definition but never saw the real one");
93980b57cec5SDimitry Andric 
93990b57cec5SDimitry Andric   // If we deserialized any C++ or Objective-C class definitions, any
94000b57cec5SDimitry Andric   // Objective-C protocol definitions, or any redeclarable templates, make sure
94010b57cec5SDimitry Andric   // that all redeclarations point to the definitions. Note that this can only
94020b57cec5SDimitry Andric   // happen now, after the redeclaration chains have been fully wired.
94030b57cec5SDimitry Andric   for (Decl *D : PendingDefinitions) {
94040b57cec5SDimitry Andric     if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
94050b57cec5SDimitry Andric       if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
94060b57cec5SDimitry Andric         // Make sure that the TagType points at the definition.
94070b57cec5SDimitry Andric         const_cast<TagType*>(TagT)->decl = TD;
94080b57cec5SDimitry Andric       }
94090b57cec5SDimitry Andric 
94100b57cec5SDimitry Andric       if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
94110b57cec5SDimitry Andric         for (auto *R = getMostRecentExistingDecl(RD); R;
94120b57cec5SDimitry Andric              R = R->getPreviousDecl()) {
94130b57cec5SDimitry Andric           assert((R == D) ==
94140b57cec5SDimitry Andric                      cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
94150b57cec5SDimitry Andric                  "declaration thinks it's the definition but it isn't");
94160b57cec5SDimitry Andric           cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
94170b57cec5SDimitry Andric         }
94180b57cec5SDimitry Andric       }
94190b57cec5SDimitry Andric 
94200b57cec5SDimitry Andric       continue;
94210b57cec5SDimitry Andric     }
94220b57cec5SDimitry Andric 
94230b57cec5SDimitry Andric     if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
94240b57cec5SDimitry Andric       // Make sure that the ObjCInterfaceType points at the definition.
94250b57cec5SDimitry Andric       const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
94260b57cec5SDimitry Andric         ->Decl = ID;
94270b57cec5SDimitry Andric 
94280b57cec5SDimitry Andric       for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
94290b57cec5SDimitry Andric         cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
94300b57cec5SDimitry Andric 
94310b57cec5SDimitry Andric       continue;
94320b57cec5SDimitry Andric     }
94330b57cec5SDimitry Andric 
94340b57cec5SDimitry Andric     if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
94350b57cec5SDimitry Andric       for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
94360b57cec5SDimitry Andric         cast<ObjCProtocolDecl>(R)->Data = PD->Data;
94370b57cec5SDimitry Andric 
94380b57cec5SDimitry Andric       continue;
94390b57cec5SDimitry Andric     }
94400b57cec5SDimitry Andric 
94410b57cec5SDimitry Andric     auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
94420b57cec5SDimitry Andric     for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
94430b57cec5SDimitry Andric       cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
94440b57cec5SDimitry Andric   }
94450b57cec5SDimitry Andric   PendingDefinitions.clear();
94460b57cec5SDimitry Andric 
94470b57cec5SDimitry Andric   // Load the bodies of any functions or methods we've encountered. We do
94480b57cec5SDimitry Andric   // this now (delayed) so that we can be sure that the declaration chains
94490b57cec5SDimitry Andric   // have been fully wired up (hasBody relies on this).
94500b57cec5SDimitry Andric   // FIXME: We shouldn't require complete redeclaration chains here.
94510b57cec5SDimitry Andric   for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
94520b57cec5SDimitry Andric                                PBEnd = PendingBodies.end();
94530b57cec5SDimitry Andric        PB != PBEnd; ++PB) {
94540b57cec5SDimitry Andric     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
94550b57cec5SDimitry Andric       // For a function defined inline within a class template, force the
94560b57cec5SDimitry Andric       // canonical definition to be the one inside the canonical definition of
94570b57cec5SDimitry Andric       // the template. This ensures that we instantiate from a correct view
94580b57cec5SDimitry Andric       // of the template.
94590b57cec5SDimitry Andric       //
94600b57cec5SDimitry Andric       // Sadly we can't do this more generally: we can't be sure that all
94610b57cec5SDimitry Andric       // copies of an arbitrary class definition will have the same members
94620b57cec5SDimitry Andric       // defined (eg, some member functions may not be instantiated, and some
94630b57cec5SDimitry Andric       // special members may or may not have been implicitly defined).
94640b57cec5SDimitry Andric       if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
94650b57cec5SDimitry Andric         if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
94660b57cec5SDimitry Andric           continue;
94670b57cec5SDimitry Andric 
94680b57cec5SDimitry Andric       // FIXME: Check for =delete/=default?
94690b57cec5SDimitry Andric       // FIXME: Complain about ODR violations here?
94700b57cec5SDimitry Andric       const FunctionDecl *Defn = nullptr;
94710b57cec5SDimitry Andric       if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
94720b57cec5SDimitry Andric         FD->setLazyBody(PB->second);
94730b57cec5SDimitry Andric       } else {
94740b57cec5SDimitry Andric         auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
94750b57cec5SDimitry Andric         mergeDefinitionVisibility(NonConstDefn, FD);
94760b57cec5SDimitry Andric 
94770b57cec5SDimitry Andric         if (!FD->isLateTemplateParsed() &&
94780b57cec5SDimitry Andric             !NonConstDefn->isLateTemplateParsed() &&
94790b57cec5SDimitry Andric             FD->getODRHash() != NonConstDefn->getODRHash()) {
94800b57cec5SDimitry Andric           if (!isa<CXXMethodDecl>(FD)) {
94810b57cec5SDimitry Andric             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
94820b57cec5SDimitry Andric           } else if (FD->getLexicalParent()->isFileContext() &&
94830b57cec5SDimitry Andric                      NonConstDefn->getLexicalParent()->isFileContext()) {
94840b57cec5SDimitry Andric             // Only diagnose out-of-line method definitions.  If they are
94850b57cec5SDimitry Andric             // in class definitions, then an error will be generated when
94860b57cec5SDimitry Andric             // processing the class bodies.
94870b57cec5SDimitry Andric             PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
94880b57cec5SDimitry Andric           }
94890b57cec5SDimitry Andric         }
94900b57cec5SDimitry Andric       }
94910b57cec5SDimitry Andric       continue;
94920b57cec5SDimitry Andric     }
94930b57cec5SDimitry Andric 
94940b57cec5SDimitry Andric     ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
94950b57cec5SDimitry Andric     if (!getContext().getLangOpts().Modules || !MD->hasBody())
94960b57cec5SDimitry Andric       MD->setLazyBody(PB->second);
94970b57cec5SDimitry Andric   }
94980b57cec5SDimitry Andric   PendingBodies.clear();
94990b57cec5SDimitry Andric 
95000b57cec5SDimitry Andric   // Do some cleanup.
95010b57cec5SDimitry Andric   for (auto *ND : PendingMergedDefinitionsToDeduplicate)
95020b57cec5SDimitry Andric     getContext().deduplicateMergedDefinitonsFor(ND);
95030b57cec5SDimitry Andric   PendingMergedDefinitionsToDeduplicate.clear();
95040b57cec5SDimitry Andric }
95050b57cec5SDimitry Andric 
95060b57cec5SDimitry Andric void ASTReader::diagnoseOdrViolations() {
95070b57cec5SDimitry Andric   if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9508*bdd1243dSDimitry Andric       PendingRecordOdrMergeFailures.empty() &&
95090b57cec5SDimitry Andric       PendingFunctionOdrMergeFailures.empty() &&
9510*bdd1243dSDimitry Andric       PendingEnumOdrMergeFailures.empty() &&
9511*bdd1243dSDimitry Andric       PendingObjCInterfaceOdrMergeFailures.empty() &&
9512*bdd1243dSDimitry Andric       PendingObjCProtocolOdrMergeFailures.empty())
95130b57cec5SDimitry Andric     return;
95140b57cec5SDimitry Andric 
95150b57cec5SDimitry Andric   // Trigger the import of the full definition of each class that had any
95160b57cec5SDimitry Andric   // odr-merging problems, so we can produce better diagnostics for them.
95170b57cec5SDimitry Andric   // These updates may in turn find and diagnose some ODR failures, so take
95180b57cec5SDimitry Andric   // ownership of the set first.
95190b57cec5SDimitry Andric   auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
95200b57cec5SDimitry Andric   PendingOdrMergeFailures.clear();
95210b57cec5SDimitry Andric   for (auto &Merge : OdrMergeFailures) {
95220b57cec5SDimitry Andric     Merge.first->buildLookup();
95230b57cec5SDimitry Andric     Merge.first->decls_begin();
95240b57cec5SDimitry Andric     Merge.first->bases_begin();
95250b57cec5SDimitry Andric     Merge.first->vbases_begin();
95260b57cec5SDimitry Andric     for (auto &RecordPair : Merge.second) {
95270b57cec5SDimitry Andric       auto *RD = RecordPair.first;
95280b57cec5SDimitry Andric       RD->decls_begin();
95290b57cec5SDimitry Andric       RD->bases_begin();
95300b57cec5SDimitry Andric       RD->vbases_begin();
95310b57cec5SDimitry Andric     }
95320b57cec5SDimitry Andric   }
95330b57cec5SDimitry Andric 
9534*bdd1243dSDimitry Andric   // Trigger the import of the full definition of each record in C/ObjC.
9535*bdd1243dSDimitry Andric   auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
9536*bdd1243dSDimitry Andric   PendingRecordOdrMergeFailures.clear();
9537*bdd1243dSDimitry Andric   for (auto &Merge : RecordOdrMergeFailures) {
9538*bdd1243dSDimitry Andric     Merge.first->decls_begin();
9539*bdd1243dSDimitry Andric     for (auto &D : Merge.second)
9540*bdd1243dSDimitry Andric       D->decls_begin();
9541*bdd1243dSDimitry Andric   }
9542*bdd1243dSDimitry Andric 
9543*bdd1243dSDimitry Andric   // Trigger the import of the full interface definition.
9544*bdd1243dSDimitry Andric   auto ObjCInterfaceOdrMergeFailures =
9545*bdd1243dSDimitry Andric       std::move(PendingObjCInterfaceOdrMergeFailures);
9546*bdd1243dSDimitry Andric   PendingObjCInterfaceOdrMergeFailures.clear();
9547*bdd1243dSDimitry Andric   for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9548*bdd1243dSDimitry Andric     Merge.first->decls_begin();
9549*bdd1243dSDimitry Andric     for (auto &InterfacePair : Merge.second)
9550*bdd1243dSDimitry Andric       InterfacePair.first->decls_begin();
9551*bdd1243dSDimitry Andric   }
9552*bdd1243dSDimitry Andric 
95530b57cec5SDimitry Andric   // Trigger the import of functions.
95540b57cec5SDimitry Andric   auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
95550b57cec5SDimitry Andric   PendingFunctionOdrMergeFailures.clear();
95560b57cec5SDimitry Andric   for (auto &Merge : FunctionOdrMergeFailures) {
95570b57cec5SDimitry Andric     Merge.first->buildLookup();
95580b57cec5SDimitry Andric     Merge.first->decls_begin();
95590b57cec5SDimitry Andric     Merge.first->getBody();
95600b57cec5SDimitry Andric     for (auto &FD : Merge.second) {
95610b57cec5SDimitry Andric       FD->buildLookup();
95620b57cec5SDimitry Andric       FD->decls_begin();
95630b57cec5SDimitry Andric       FD->getBody();
95640b57cec5SDimitry Andric     }
95650b57cec5SDimitry Andric   }
95660b57cec5SDimitry Andric 
95670b57cec5SDimitry Andric   // Trigger the import of enums.
95680b57cec5SDimitry Andric   auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
95690b57cec5SDimitry Andric   PendingEnumOdrMergeFailures.clear();
95700b57cec5SDimitry Andric   for (auto &Merge : EnumOdrMergeFailures) {
95710b57cec5SDimitry Andric     Merge.first->decls_begin();
95720b57cec5SDimitry Andric     for (auto &Enum : Merge.second) {
95730b57cec5SDimitry Andric       Enum->decls_begin();
95740b57cec5SDimitry Andric     }
95750b57cec5SDimitry Andric   }
95760b57cec5SDimitry Andric 
9577*bdd1243dSDimitry Andric   // Trigger the import of the full protocol definition.
9578*bdd1243dSDimitry Andric   auto ObjCProtocolOdrMergeFailures =
9579*bdd1243dSDimitry Andric       std::move(PendingObjCProtocolOdrMergeFailures);
9580*bdd1243dSDimitry Andric   PendingObjCProtocolOdrMergeFailures.clear();
9581*bdd1243dSDimitry Andric   for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9582*bdd1243dSDimitry Andric     Merge.first->decls_begin();
9583*bdd1243dSDimitry Andric     for (auto &ProtocolPair : Merge.second)
9584*bdd1243dSDimitry Andric       ProtocolPair.first->decls_begin();
9585*bdd1243dSDimitry Andric   }
9586*bdd1243dSDimitry Andric 
95870b57cec5SDimitry Andric   // For each declaration from a merged context, check that the canonical
95880b57cec5SDimitry Andric   // definition of that context also contains a declaration of the same
95890b57cec5SDimitry Andric   // entity.
95900b57cec5SDimitry Andric   //
95910b57cec5SDimitry Andric   // Caution: this loop does things that might invalidate iterators into
95920b57cec5SDimitry Andric   // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
95930b57cec5SDimitry Andric   while (!PendingOdrMergeChecks.empty()) {
95940b57cec5SDimitry Andric     NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
95950b57cec5SDimitry Andric 
95960b57cec5SDimitry Andric     // FIXME: Skip over implicit declarations for now. This matters for things
95970b57cec5SDimitry Andric     // like implicitly-declared special member functions. This isn't entirely
95980b57cec5SDimitry Andric     // correct; we can end up with multiple unmerged declarations of the same
95990b57cec5SDimitry Andric     // implicit entity.
96000b57cec5SDimitry Andric     if (D->isImplicit())
96010b57cec5SDimitry Andric       continue;
96020b57cec5SDimitry Andric 
96030b57cec5SDimitry Andric     DeclContext *CanonDef = D->getDeclContext();
96040b57cec5SDimitry Andric 
96050b57cec5SDimitry Andric     bool Found = false;
96060b57cec5SDimitry Andric     const Decl *DCanon = D->getCanonicalDecl();
96070b57cec5SDimitry Andric 
9608*bdd1243dSDimitry Andric     for (auto *RI : D->redecls()) {
96090b57cec5SDimitry Andric       if (RI->getLexicalDeclContext() == CanonDef) {
96100b57cec5SDimitry Andric         Found = true;
96110b57cec5SDimitry Andric         break;
96120b57cec5SDimitry Andric       }
96130b57cec5SDimitry Andric     }
96140b57cec5SDimitry Andric     if (Found)
96150b57cec5SDimitry Andric       continue;
96160b57cec5SDimitry Andric 
96170b57cec5SDimitry Andric     // Quick check failed, time to do the slow thing. Note, we can't just
96180b57cec5SDimitry Andric     // look up the name of D in CanonDef here, because the member that is
96190b57cec5SDimitry Andric     // in CanonDef might not be found by name lookup (it might have been
96200b57cec5SDimitry Andric     // replaced by a more recent declaration in the lookup table), and we
96210b57cec5SDimitry Andric     // can't necessarily find it in the redeclaration chain because it might
96220b57cec5SDimitry Andric     // be merely mergeable, not redeclarable.
96230b57cec5SDimitry Andric     llvm::SmallVector<const NamedDecl*, 4> Candidates;
96240b57cec5SDimitry Andric     for (auto *CanonMember : CanonDef->decls()) {
96250b57cec5SDimitry Andric       if (CanonMember->getCanonicalDecl() == DCanon) {
96260b57cec5SDimitry Andric         // This can happen if the declaration is merely mergeable and not
96270b57cec5SDimitry Andric         // actually redeclarable (we looked for redeclarations earlier).
96280b57cec5SDimitry Andric         //
96290b57cec5SDimitry Andric         // FIXME: We should be able to detect this more efficiently, without
96300b57cec5SDimitry Andric         // pulling in all of the members of CanonDef.
96310b57cec5SDimitry Andric         Found = true;
96320b57cec5SDimitry Andric         break;
96330b57cec5SDimitry Andric       }
96340b57cec5SDimitry Andric       if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
96350b57cec5SDimitry Andric         if (ND->getDeclName() == D->getDeclName())
96360b57cec5SDimitry Andric           Candidates.push_back(ND);
96370b57cec5SDimitry Andric     }
96380b57cec5SDimitry Andric 
96390b57cec5SDimitry Andric     if (!Found) {
96400b57cec5SDimitry Andric       // The AST doesn't like TagDecls becoming invalid after they've been
96410b57cec5SDimitry Andric       // completed. We only really need to mark FieldDecls as invalid here.
96420b57cec5SDimitry Andric       if (!isa<TagDecl>(D))
96430b57cec5SDimitry Andric         D->setInvalidDecl();
96440b57cec5SDimitry Andric 
96450b57cec5SDimitry Andric       // Ensure we don't accidentally recursively enter deserialization while
96460b57cec5SDimitry Andric       // we're producing our diagnostic.
96470b57cec5SDimitry Andric       Deserializing RecursionGuard(this);
96480b57cec5SDimitry Andric 
96490b57cec5SDimitry Andric       std::string CanonDefModule =
9650*bdd1243dSDimitry Andric           ODRDiagsEmitter::getOwningModuleNameForDiagnostic(
9651*bdd1243dSDimitry Andric               cast<Decl>(CanonDef));
96520b57cec5SDimitry Andric       Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9653*bdd1243dSDimitry Andric         << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)
96540b57cec5SDimitry Andric         << CanonDef << CanonDefModule.empty() << CanonDefModule;
96550b57cec5SDimitry Andric 
96560b57cec5SDimitry Andric       if (Candidates.empty())
96570b57cec5SDimitry Andric         Diag(cast<Decl>(CanonDef)->getLocation(),
96580b57cec5SDimitry Andric              diag::note_module_odr_violation_no_possible_decls) << D;
96590b57cec5SDimitry Andric       else {
96600b57cec5SDimitry Andric         for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
96610b57cec5SDimitry Andric           Diag(Candidates[I]->getLocation(),
96620b57cec5SDimitry Andric                diag::note_module_odr_violation_possible_decl)
96630b57cec5SDimitry Andric             << Candidates[I];
96640b57cec5SDimitry Andric       }
96650b57cec5SDimitry Andric 
96660b57cec5SDimitry Andric       DiagnosedOdrMergeFailures.insert(CanonDef);
96670b57cec5SDimitry Andric     }
96680b57cec5SDimitry Andric   }
96690b57cec5SDimitry Andric 
9670*bdd1243dSDimitry Andric   if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
9671*bdd1243dSDimitry Andric       FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
9672*bdd1243dSDimitry Andric       ObjCInterfaceOdrMergeFailures.empty() &&
9673*bdd1243dSDimitry Andric       ObjCProtocolOdrMergeFailures.empty())
96740b57cec5SDimitry Andric     return;
96750b57cec5SDimitry Andric 
96760b57cec5SDimitry Andric   // Ensure we don't accidentally recursively enter deserialization while
96770b57cec5SDimitry Andric   // we're producing our diagnostics.
96780b57cec5SDimitry Andric   Deserializing RecursionGuard(this);
9679*bdd1243dSDimitry Andric   ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
9680*bdd1243dSDimitry Andric                                getPreprocessor().getLangOpts());
96815ffd83dbSDimitry Andric 
96825ffd83dbSDimitry Andric   // Issue any pending ODR-failure diagnostics.
96835ffd83dbSDimitry Andric   for (auto &Merge : OdrMergeFailures) {
96845ffd83dbSDimitry Andric     // If we've already pointed out a specific problem with this class, don't
96855ffd83dbSDimitry Andric     // bother issuing a general "something's different" diagnostic.
96865ffd83dbSDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
96875ffd83dbSDimitry Andric       continue;
96885ffd83dbSDimitry Andric 
96895ffd83dbSDimitry Andric     bool Diagnosed = false;
96905ffd83dbSDimitry Andric     CXXRecordDecl *FirstRecord = Merge.first;
96915ffd83dbSDimitry Andric     for (auto &RecordPair : Merge.second) {
9692*bdd1243dSDimitry Andric       if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
9693*bdd1243dSDimitry Andric                                         RecordPair.second)) {
96945ffd83dbSDimitry Andric         Diagnosed = true;
96955ffd83dbSDimitry Andric         break;
96965ffd83dbSDimitry Andric       }
96970b57cec5SDimitry Andric     }
96980b57cec5SDimitry Andric 
96990b57cec5SDimitry Andric     if (!Diagnosed) {
97000b57cec5SDimitry Andric       // All definitions are updates to the same declaration. This happens if a
97010b57cec5SDimitry Andric       // module instantiates the declaration of a class template specialization
97020b57cec5SDimitry Andric       // and two or more other modules instantiate its definition.
97030b57cec5SDimitry Andric       //
97040b57cec5SDimitry Andric       // FIXME: Indicate which modules had instantiations of this definition.
97050b57cec5SDimitry Andric       // FIXME: How can this even happen?
97060b57cec5SDimitry Andric       Diag(Merge.first->getLocation(),
97070b57cec5SDimitry Andric            diag::err_module_odr_violation_different_instantiations)
97080b57cec5SDimitry Andric           << Merge.first;
97090b57cec5SDimitry Andric     }
97100b57cec5SDimitry Andric   }
97110b57cec5SDimitry Andric 
9712*bdd1243dSDimitry Andric   // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
9713*bdd1243dSDimitry Andric   // that in C++ this is done as a part of CXXRecordDecl ODR checking.
9714*bdd1243dSDimitry Andric   for (auto &Merge : RecordOdrMergeFailures) {
9715*bdd1243dSDimitry Andric     // If we've already pointed out a specific problem with this class, don't
9716*bdd1243dSDimitry Andric     // bother issuing a general "something's different" diagnostic.
9717*bdd1243dSDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
97180b57cec5SDimitry Andric       continue;
97190b57cec5SDimitry Andric 
9720*bdd1243dSDimitry Andric     RecordDecl *FirstRecord = Merge.first;
9721*bdd1243dSDimitry Andric     bool Diagnosed = false;
9722*bdd1243dSDimitry Andric     for (auto *SecondRecord : Merge.second) {
9723*bdd1243dSDimitry Andric       if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
97240b57cec5SDimitry Andric         Diagnosed = true;
97250b57cec5SDimitry Andric         break;
97260b57cec5SDimitry Andric       }
9727*bdd1243dSDimitry Andric     }
9728*bdd1243dSDimitry Andric     (void)Diagnosed;
9729*bdd1243dSDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
97300b57cec5SDimitry Andric   }
97310b57cec5SDimitry Andric 
9732*bdd1243dSDimitry Andric   // Issue ODR failures diagnostics for functions.
9733*bdd1243dSDimitry Andric   for (auto &Merge : FunctionOdrMergeFailures) {
9734*bdd1243dSDimitry Andric     FunctionDecl *FirstFunction = Merge.first;
9735*bdd1243dSDimitry Andric     bool Diagnosed = false;
9736*bdd1243dSDimitry Andric     for (auto &SecondFunction : Merge.second) {
9737*bdd1243dSDimitry Andric       if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
97380b57cec5SDimitry Andric         Diagnosed = true;
97390b57cec5SDimitry Andric         break;
97400b57cec5SDimitry Andric       }
97410b57cec5SDimitry Andric     }
97420b57cec5SDimitry Andric     (void)Diagnosed;
97430b57cec5SDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
97440b57cec5SDimitry Andric   }
97450b57cec5SDimitry Andric 
97460b57cec5SDimitry Andric   // Issue ODR failures diagnostics for enums.
97470b57cec5SDimitry Andric   for (auto &Merge : EnumOdrMergeFailures) {
97480b57cec5SDimitry Andric     // If we've already pointed out a specific problem with this enum, don't
97490b57cec5SDimitry Andric     // bother issuing a general "something's different" diagnostic.
97500b57cec5SDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
97510b57cec5SDimitry Andric       continue;
97520b57cec5SDimitry Andric 
97530b57cec5SDimitry Andric     EnumDecl *FirstEnum = Merge.first;
97540b57cec5SDimitry Andric     bool Diagnosed = false;
97550b57cec5SDimitry Andric     for (auto &SecondEnum : Merge.second) {
9756*bdd1243dSDimitry Andric       if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
97570b57cec5SDimitry Andric         Diagnosed = true;
97580b57cec5SDimitry Andric         break;
97590b57cec5SDimitry Andric       }
97600b57cec5SDimitry Andric     }
9761*bdd1243dSDimitry Andric     (void)Diagnosed;
9762*bdd1243dSDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
97630b57cec5SDimitry Andric   }
97640b57cec5SDimitry Andric 
9765*bdd1243dSDimitry Andric   for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
9766*bdd1243dSDimitry Andric     // If we've already pointed out a specific problem with this interface,
9767*bdd1243dSDimitry Andric     // don't bother issuing a general "something's different" diagnostic.
9768*bdd1243dSDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9769*bdd1243dSDimitry Andric       continue;
9770*bdd1243dSDimitry Andric 
9771*bdd1243dSDimitry Andric     bool Diagnosed = false;
9772*bdd1243dSDimitry Andric     ObjCInterfaceDecl *FirstID = Merge.first;
9773*bdd1243dSDimitry Andric     for (auto &InterfacePair : Merge.second) {
9774*bdd1243dSDimitry Andric       if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
9775*bdd1243dSDimitry Andric                                         InterfacePair.second)) {
9776*bdd1243dSDimitry Andric         Diagnosed = true;
9777*bdd1243dSDimitry Andric         break;
9778*bdd1243dSDimitry Andric       }
9779*bdd1243dSDimitry Andric     }
9780*bdd1243dSDimitry Andric     (void)Diagnosed;
9781*bdd1243dSDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
9782*bdd1243dSDimitry Andric   }
9783*bdd1243dSDimitry Andric 
9784*bdd1243dSDimitry Andric   for (auto &Merge : ObjCProtocolOdrMergeFailures) {
9785*bdd1243dSDimitry Andric     // If we've already pointed out a specific problem with this protocol,
9786*bdd1243dSDimitry Andric     // don't bother issuing a general "something's different" diagnostic.
9787*bdd1243dSDimitry Andric     if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
9788*bdd1243dSDimitry Andric       continue;
9789*bdd1243dSDimitry Andric 
9790*bdd1243dSDimitry Andric     ObjCProtocolDecl *FirstProtocol = Merge.first;
9791*bdd1243dSDimitry Andric     bool Diagnosed = false;
9792*bdd1243dSDimitry Andric     for (auto &ProtocolPair : Merge.second) {
9793*bdd1243dSDimitry Andric       if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
9794*bdd1243dSDimitry Andric                                         ProtocolPair.second)) {
9795*bdd1243dSDimitry Andric         Diagnosed = true;
9796*bdd1243dSDimitry Andric         break;
9797*bdd1243dSDimitry Andric       }
9798*bdd1243dSDimitry Andric     }
97990b57cec5SDimitry Andric     (void)Diagnosed;
98000b57cec5SDimitry Andric     assert(Diagnosed && "Unable to emit ODR diagnostic.");
98010b57cec5SDimitry Andric   }
98020b57cec5SDimitry Andric }
98030b57cec5SDimitry Andric 
98040b57cec5SDimitry Andric void ASTReader::StartedDeserializing() {
98050b57cec5SDimitry Andric   if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
98060b57cec5SDimitry Andric     ReadTimer->startTimer();
98070b57cec5SDimitry Andric }
98080b57cec5SDimitry Andric 
98090b57cec5SDimitry Andric void ASTReader::FinishedDeserializing() {
98100b57cec5SDimitry Andric   assert(NumCurrentElementsDeserializing &&
98110b57cec5SDimitry Andric          "FinishedDeserializing not paired with StartedDeserializing");
98120b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing == 1) {
98130b57cec5SDimitry Andric     // We decrease NumCurrentElementsDeserializing only after pending actions
98140b57cec5SDimitry Andric     // are finished, to avoid recursively re-calling finishPendingActions().
98150b57cec5SDimitry Andric     finishPendingActions();
98160b57cec5SDimitry Andric   }
98170b57cec5SDimitry Andric   --NumCurrentElementsDeserializing;
98180b57cec5SDimitry Andric 
98190b57cec5SDimitry Andric   if (NumCurrentElementsDeserializing == 0) {
98200b57cec5SDimitry Andric     // Propagate exception specification and deduced type updates along
98210b57cec5SDimitry Andric     // redeclaration chains.
98220b57cec5SDimitry Andric     //
98230b57cec5SDimitry Andric     // We do this now rather than in finishPendingActions because we want to
98240b57cec5SDimitry Andric     // be able to walk the complete redeclaration chains of the updated decls.
98250b57cec5SDimitry Andric     while (!PendingExceptionSpecUpdates.empty() ||
98260b57cec5SDimitry Andric            !PendingDeducedTypeUpdates.empty()) {
98270b57cec5SDimitry Andric       auto ESUpdates = std::move(PendingExceptionSpecUpdates);
98280b57cec5SDimitry Andric       PendingExceptionSpecUpdates.clear();
98290b57cec5SDimitry Andric       for (auto Update : ESUpdates) {
98300b57cec5SDimitry Andric         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
98310b57cec5SDimitry Andric         auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
98320b57cec5SDimitry Andric         auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
98330b57cec5SDimitry Andric         if (auto *Listener = getContext().getASTMutationListener())
98340b57cec5SDimitry Andric           Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
98350b57cec5SDimitry Andric         for (auto *Redecl : Update.second->redecls())
98360b57cec5SDimitry Andric           getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
98370b57cec5SDimitry Andric       }
98380b57cec5SDimitry Andric 
98390b57cec5SDimitry Andric       auto DTUpdates = std::move(PendingDeducedTypeUpdates);
98400b57cec5SDimitry Andric       PendingDeducedTypeUpdates.clear();
98410b57cec5SDimitry Andric       for (auto Update : DTUpdates) {
98420b57cec5SDimitry Andric         ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
98430b57cec5SDimitry Andric         // FIXME: If the return type is already deduced, check that it matches.
98440b57cec5SDimitry Andric         getContext().adjustDeducedFunctionResultType(Update.first,
98450b57cec5SDimitry Andric                                                      Update.second);
98460b57cec5SDimitry Andric       }
98470b57cec5SDimitry Andric     }
98480b57cec5SDimitry Andric 
98490b57cec5SDimitry Andric     if (ReadTimer)
98500b57cec5SDimitry Andric       ReadTimer->stopTimer();
98510b57cec5SDimitry Andric 
98520b57cec5SDimitry Andric     diagnoseOdrViolations();
98530b57cec5SDimitry Andric 
98540b57cec5SDimitry Andric     // We are not in recursive loading, so it's safe to pass the "interesting"
98550b57cec5SDimitry Andric     // decls to the consumer.
98560b57cec5SDimitry Andric     if (Consumer)
98570b57cec5SDimitry Andric       PassInterestingDeclsToConsumer();
98580b57cec5SDimitry Andric   }
98590b57cec5SDimitry Andric }
98600b57cec5SDimitry Andric 
98610b57cec5SDimitry Andric void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
98620b57cec5SDimitry Andric   if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
98630b57cec5SDimitry Andric     // Remove any fake results before adding any real ones.
98640b57cec5SDimitry Andric     auto It = PendingFakeLookupResults.find(II);
98650b57cec5SDimitry Andric     if (It != PendingFakeLookupResults.end()) {
98660b57cec5SDimitry Andric       for (auto *ND : It->second)
98670b57cec5SDimitry Andric         SemaObj->IdResolver.RemoveDecl(ND);
98680b57cec5SDimitry Andric       // FIXME: this works around module+PCH performance issue.
98690b57cec5SDimitry Andric       // Rather than erase the result from the map, which is O(n), just clear
98700b57cec5SDimitry Andric       // the vector of NamedDecls.
98710b57cec5SDimitry Andric       It->second.clear();
98720b57cec5SDimitry Andric     }
98730b57cec5SDimitry Andric   }
98740b57cec5SDimitry Andric 
98750b57cec5SDimitry Andric   if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
98760b57cec5SDimitry Andric     SemaObj->TUScope->AddDecl(D);
98770b57cec5SDimitry Andric   } else if (SemaObj->TUScope) {
98780b57cec5SDimitry Andric     // Adding the decl to IdResolver may have failed because it was already in
98790b57cec5SDimitry Andric     // (even though it was not added in scope). If it is already in, make sure
98800b57cec5SDimitry Andric     // it gets in the scope as well.
98810b57cec5SDimitry Andric     if (std::find(SemaObj->IdResolver.begin(Name),
98820b57cec5SDimitry Andric                   SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
98830b57cec5SDimitry Andric       SemaObj->TUScope->AddDecl(D);
98840b57cec5SDimitry Andric   }
98850b57cec5SDimitry Andric }
98860b57cec5SDimitry Andric 
98870b57cec5SDimitry Andric ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
98880b57cec5SDimitry Andric                      ASTContext *Context,
98890b57cec5SDimitry Andric                      const PCHContainerReader &PCHContainerRdr,
98900b57cec5SDimitry Andric                      ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9891e8d8bef9SDimitry Andric                      StringRef isysroot,
9892e8d8bef9SDimitry Andric                      DisableValidationForModuleKind DisableValidationKind,
98930b57cec5SDimitry Andric                      bool AllowASTWithCompilerErrors,
98940b57cec5SDimitry Andric                      bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9895a7dea167SDimitry Andric                      bool ValidateASTInputFilesContent, bool UseGlobalIndex,
98960b57cec5SDimitry Andric                      std::unique_ptr<llvm::Timer> ReadTimer)
9897e8d8bef9SDimitry Andric     : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
98980b57cec5SDimitry Andric                    ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
98990b57cec5SDimitry Andric                    : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
99000b57cec5SDimitry Andric       SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
99010b57cec5SDimitry Andric       PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
99020b57cec5SDimitry Andric       ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
99030b57cec5SDimitry Andric                                      PCHContainerRdr, PP.getHeaderSearchInfo()),
99040b57cec5SDimitry Andric       DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
9905e8d8bef9SDimitry Andric       DisableValidationKind(DisableValidationKind),
99060b57cec5SDimitry Andric       AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
99070b57cec5SDimitry Andric       AllowConfigurationMismatch(AllowConfigurationMismatch),
99080b57cec5SDimitry Andric       ValidateSystemInputs(ValidateSystemInputs),
9909a7dea167SDimitry Andric       ValidateASTInputFilesContent(ValidateASTInputFilesContent),
99100b57cec5SDimitry Andric       UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
99110b57cec5SDimitry Andric   SourceMgr.setExternalSLocEntrySource(this);
99120b57cec5SDimitry Andric 
99130b57cec5SDimitry Andric   for (const auto &Ext : Extensions) {
99140b57cec5SDimitry Andric     auto BlockName = Ext->getExtensionMetadata().BlockName;
99150b57cec5SDimitry Andric     auto Known = ModuleFileExtensions.find(BlockName);
99160b57cec5SDimitry Andric     if (Known != ModuleFileExtensions.end()) {
99170b57cec5SDimitry Andric       Diags.Report(diag::warn_duplicate_module_file_extension)
99180b57cec5SDimitry Andric         << BlockName;
99190b57cec5SDimitry Andric       continue;
99200b57cec5SDimitry Andric     }
99210b57cec5SDimitry Andric 
99220b57cec5SDimitry Andric     ModuleFileExtensions.insert({BlockName, Ext});
99230b57cec5SDimitry Andric   }
99240b57cec5SDimitry Andric }
99250b57cec5SDimitry Andric 
99260b57cec5SDimitry Andric ASTReader::~ASTReader() {
99270b57cec5SDimitry Andric   if (OwnsDeserializationListener)
99280b57cec5SDimitry Andric     delete DeserializationListener;
99290b57cec5SDimitry Andric }
99300b57cec5SDimitry Andric 
99310b57cec5SDimitry Andric IdentifierResolver &ASTReader::getIdResolver() {
99320b57cec5SDimitry Andric   return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
99330b57cec5SDimitry Andric }
99340b57cec5SDimitry Andric 
99350b57cec5SDimitry Andric Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
99360b57cec5SDimitry Andric                                                unsigned AbbrevID) {
99370b57cec5SDimitry Andric   Idx = 0;
99380b57cec5SDimitry Andric   Record.clear();
99390b57cec5SDimitry Andric   return Cursor.readRecord(AbbrevID, Record);
99400b57cec5SDimitry Andric }
99410b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
99420b57cec5SDimitry Andric //// OMPClauseReader implementation
99430b57cec5SDimitry Andric ////===----------------------------------------------------------------------===//
99440b57cec5SDimitry Andric 
9945480093f4SDimitry Andric // This has to be in namespace clang because it's friended by all
9946480093f4SDimitry Andric // of the OMP clauses.
9947480093f4SDimitry Andric namespace clang {
9948480093f4SDimitry Andric 
9949480093f4SDimitry Andric class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
9950480093f4SDimitry Andric   ASTRecordReader &Record;
9951480093f4SDimitry Andric   ASTContext &Context;
9952480093f4SDimitry Andric 
9953480093f4SDimitry Andric public:
9954480093f4SDimitry Andric   OMPClauseReader(ASTRecordReader &Record)
9955480093f4SDimitry Andric       : Record(Record), Context(Record.getContext()) {}
9956e8d8bef9SDimitry Andric #define GEN_CLANG_CLAUSE_CLASS
9957e8d8bef9SDimitry Andric #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
9958e8d8bef9SDimitry Andric #include "llvm/Frontend/OpenMP/OMP.inc"
9959480093f4SDimitry Andric   OMPClause *readClause();
9960480093f4SDimitry Andric   void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
9961480093f4SDimitry Andric   void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
9962480093f4SDimitry Andric };
9963480093f4SDimitry Andric 
9964480093f4SDimitry Andric } // end namespace clang
9965480093f4SDimitry Andric 
9966480093f4SDimitry Andric OMPClause *ASTRecordReader::readOMPClause() {
9967480093f4SDimitry Andric   return OMPClauseReader(*this).readClause();
9968480093f4SDimitry Andric }
9969480093f4SDimitry Andric 
99700b57cec5SDimitry Andric OMPClause *OMPClauseReader::readClause() {
9971a7dea167SDimitry Andric   OMPClause *C = nullptr;
99725ffd83dbSDimitry Andric   switch (llvm::omp::Clause(Record.readInt())) {
99735ffd83dbSDimitry Andric   case llvm::omp::OMPC_if:
99740b57cec5SDimitry Andric     C = new (Context) OMPIfClause();
99750b57cec5SDimitry Andric     break;
99765ffd83dbSDimitry Andric   case llvm::omp::OMPC_final:
99770b57cec5SDimitry Andric     C = new (Context) OMPFinalClause();
99780b57cec5SDimitry Andric     break;
99795ffd83dbSDimitry Andric   case llvm::omp::OMPC_num_threads:
99800b57cec5SDimitry Andric     C = new (Context) OMPNumThreadsClause();
99810b57cec5SDimitry Andric     break;
99825ffd83dbSDimitry Andric   case llvm::omp::OMPC_safelen:
99830b57cec5SDimitry Andric     C = new (Context) OMPSafelenClause();
99840b57cec5SDimitry Andric     break;
99855ffd83dbSDimitry Andric   case llvm::omp::OMPC_simdlen:
99860b57cec5SDimitry Andric     C = new (Context) OMPSimdlenClause();
99870b57cec5SDimitry Andric     break;
9988fe6060f1SDimitry Andric   case llvm::omp::OMPC_sizes: {
9989fe6060f1SDimitry Andric     unsigned NumSizes = Record.readInt();
9990fe6060f1SDimitry Andric     C = OMPSizesClause::CreateEmpty(Context, NumSizes);
9991fe6060f1SDimitry Andric     break;
9992fe6060f1SDimitry Andric   }
9993fe6060f1SDimitry Andric   case llvm::omp::OMPC_full:
9994fe6060f1SDimitry Andric     C = OMPFullClause::CreateEmpty(Context);
9995fe6060f1SDimitry Andric     break;
9996fe6060f1SDimitry Andric   case llvm::omp::OMPC_partial:
9997fe6060f1SDimitry Andric     C = OMPPartialClause::CreateEmpty(Context);
9998fe6060f1SDimitry Andric     break;
99995ffd83dbSDimitry Andric   case llvm::omp::OMPC_allocator:
100000b57cec5SDimitry Andric     C = new (Context) OMPAllocatorClause();
100010b57cec5SDimitry Andric     break;
100025ffd83dbSDimitry Andric   case llvm::omp::OMPC_collapse:
100030b57cec5SDimitry Andric     C = new (Context) OMPCollapseClause();
100040b57cec5SDimitry Andric     break;
100055ffd83dbSDimitry Andric   case llvm::omp::OMPC_default:
100060b57cec5SDimitry Andric     C = new (Context) OMPDefaultClause();
100070b57cec5SDimitry Andric     break;
100085ffd83dbSDimitry Andric   case llvm::omp::OMPC_proc_bind:
100090b57cec5SDimitry Andric     C = new (Context) OMPProcBindClause();
100100b57cec5SDimitry Andric     break;
100115ffd83dbSDimitry Andric   case llvm::omp::OMPC_schedule:
100120b57cec5SDimitry Andric     C = new (Context) OMPScheduleClause();
100130b57cec5SDimitry Andric     break;
100145ffd83dbSDimitry Andric   case llvm::omp::OMPC_ordered:
100150b57cec5SDimitry Andric     C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
100160b57cec5SDimitry Andric     break;
100175ffd83dbSDimitry Andric   case llvm::omp::OMPC_nowait:
100180b57cec5SDimitry Andric     C = new (Context) OMPNowaitClause();
100190b57cec5SDimitry Andric     break;
100205ffd83dbSDimitry Andric   case llvm::omp::OMPC_untied:
100210b57cec5SDimitry Andric     C = new (Context) OMPUntiedClause();
100220b57cec5SDimitry Andric     break;
100235ffd83dbSDimitry Andric   case llvm::omp::OMPC_mergeable:
100240b57cec5SDimitry Andric     C = new (Context) OMPMergeableClause();
100250b57cec5SDimitry Andric     break;
100265ffd83dbSDimitry Andric   case llvm::omp::OMPC_read:
100270b57cec5SDimitry Andric     C = new (Context) OMPReadClause();
100280b57cec5SDimitry Andric     break;
100295ffd83dbSDimitry Andric   case llvm::omp::OMPC_write:
100300b57cec5SDimitry Andric     C = new (Context) OMPWriteClause();
100310b57cec5SDimitry Andric     break;
100325ffd83dbSDimitry Andric   case llvm::omp::OMPC_update:
100335ffd83dbSDimitry Andric     C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
100340b57cec5SDimitry Andric     break;
100355ffd83dbSDimitry Andric   case llvm::omp::OMPC_capture:
100360b57cec5SDimitry Andric     C = new (Context) OMPCaptureClause();
100370b57cec5SDimitry Andric     break;
100380eae32dcSDimitry Andric   case llvm::omp::OMPC_compare:
100390eae32dcSDimitry Andric     C = new (Context) OMPCompareClause();
100400eae32dcSDimitry Andric     break;
100415ffd83dbSDimitry Andric   case llvm::omp::OMPC_seq_cst:
100420b57cec5SDimitry Andric     C = new (Context) OMPSeqCstClause();
100430b57cec5SDimitry Andric     break;
100445ffd83dbSDimitry Andric   case llvm::omp::OMPC_acq_rel:
100455ffd83dbSDimitry Andric     C = new (Context) OMPAcqRelClause();
100465ffd83dbSDimitry Andric     break;
100475ffd83dbSDimitry Andric   case llvm::omp::OMPC_acquire:
100485ffd83dbSDimitry Andric     C = new (Context) OMPAcquireClause();
100495ffd83dbSDimitry Andric     break;
100505ffd83dbSDimitry Andric   case llvm::omp::OMPC_release:
100515ffd83dbSDimitry Andric     C = new (Context) OMPReleaseClause();
100525ffd83dbSDimitry Andric     break;
100535ffd83dbSDimitry Andric   case llvm::omp::OMPC_relaxed:
100545ffd83dbSDimitry Andric     C = new (Context) OMPRelaxedClause();
100555ffd83dbSDimitry Andric     break;
100565ffd83dbSDimitry Andric   case llvm::omp::OMPC_threads:
100570b57cec5SDimitry Andric     C = new (Context) OMPThreadsClause();
100580b57cec5SDimitry Andric     break;
100595ffd83dbSDimitry Andric   case llvm::omp::OMPC_simd:
100600b57cec5SDimitry Andric     C = new (Context) OMPSIMDClause();
100610b57cec5SDimitry Andric     break;
100625ffd83dbSDimitry Andric   case llvm::omp::OMPC_nogroup:
100630b57cec5SDimitry Andric     C = new (Context) OMPNogroupClause();
100640b57cec5SDimitry Andric     break;
100655ffd83dbSDimitry Andric   case llvm::omp::OMPC_unified_address:
100660b57cec5SDimitry Andric     C = new (Context) OMPUnifiedAddressClause();
100670b57cec5SDimitry Andric     break;
100685ffd83dbSDimitry Andric   case llvm::omp::OMPC_unified_shared_memory:
100690b57cec5SDimitry Andric     C = new (Context) OMPUnifiedSharedMemoryClause();
100700b57cec5SDimitry Andric     break;
100715ffd83dbSDimitry Andric   case llvm::omp::OMPC_reverse_offload:
100720b57cec5SDimitry Andric     C = new (Context) OMPReverseOffloadClause();
100730b57cec5SDimitry Andric     break;
100745ffd83dbSDimitry Andric   case llvm::omp::OMPC_dynamic_allocators:
100750b57cec5SDimitry Andric     C = new (Context) OMPDynamicAllocatorsClause();
100760b57cec5SDimitry Andric     break;
100775ffd83dbSDimitry Andric   case llvm::omp::OMPC_atomic_default_mem_order:
100780b57cec5SDimitry Andric     C = new (Context) OMPAtomicDefaultMemOrderClause();
100790b57cec5SDimitry Andric     break;
10080*bdd1243dSDimitry Andric   case llvm::omp::OMPC_at:
10081*bdd1243dSDimitry Andric     C = new (Context) OMPAtClause();
10082*bdd1243dSDimitry Andric     break;
10083*bdd1243dSDimitry Andric   case llvm::omp::OMPC_severity:
10084*bdd1243dSDimitry Andric     C = new (Context) OMPSeverityClause();
10085*bdd1243dSDimitry Andric     break;
10086*bdd1243dSDimitry Andric   case llvm::omp::OMPC_message:
10087*bdd1243dSDimitry Andric     C = new (Context) OMPMessageClause();
10088*bdd1243dSDimitry Andric     break;
100895ffd83dbSDimitry Andric   case llvm::omp::OMPC_private:
100900b57cec5SDimitry Andric     C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
100910b57cec5SDimitry Andric     break;
100925ffd83dbSDimitry Andric   case llvm::omp::OMPC_firstprivate:
100930b57cec5SDimitry Andric     C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
100940b57cec5SDimitry Andric     break;
100955ffd83dbSDimitry Andric   case llvm::omp::OMPC_lastprivate:
100960b57cec5SDimitry Andric     C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
100970b57cec5SDimitry Andric     break;
100985ffd83dbSDimitry Andric   case llvm::omp::OMPC_shared:
100990b57cec5SDimitry Andric     C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
101000b57cec5SDimitry Andric     break;
101015ffd83dbSDimitry Andric   case llvm::omp::OMPC_reduction: {
101025ffd83dbSDimitry Andric     unsigned N = Record.readInt();
101035ffd83dbSDimitry Andric     auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
101045ffd83dbSDimitry Andric     C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
101050b57cec5SDimitry Andric     break;
101065ffd83dbSDimitry Andric   }
101075ffd83dbSDimitry Andric   case llvm::omp::OMPC_task_reduction:
101080b57cec5SDimitry Andric     C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
101090b57cec5SDimitry Andric     break;
101105ffd83dbSDimitry Andric   case llvm::omp::OMPC_in_reduction:
101110b57cec5SDimitry Andric     C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
101120b57cec5SDimitry Andric     break;
101135ffd83dbSDimitry Andric   case llvm::omp::OMPC_linear:
101140b57cec5SDimitry Andric     C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
101150b57cec5SDimitry Andric     break;
101165ffd83dbSDimitry Andric   case llvm::omp::OMPC_aligned:
101170b57cec5SDimitry Andric     C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
101180b57cec5SDimitry Andric     break;
101195ffd83dbSDimitry Andric   case llvm::omp::OMPC_copyin:
101200b57cec5SDimitry Andric     C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
101210b57cec5SDimitry Andric     break;
101225ffd83dbSDimitry Andric   case llvm::omp::OMPC_copyprivate:
101230b57cec5SDimitry Andric     C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
101240b57cec5SDimitry Andric     break;
101255ffd83dbSDimitry Andric   case llvm::omp::OMPC_flush:
101260b57cec5SDimitry Andric     C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
101270b57cec5SDimitry Andric     break;
101285ffd83dbSDimitry Andric   case llvm::omp::OMPC_depobj:
101295ffd83dbSDimitry Andric     C = OMPDepobjClause::CreateEmpty(Context);
101305ffd83dbSDimitry Andric     break;
101315ffd83dbSDimitry Andric   case llvm::omp::OMPC_depend: {
101320b57cec5SDimitry Andric     unsigned NumVars = Record.readInt();
101330b57cec5SDimitry Andric     unsigned NumLoops = Record.readInt();
101340b57cec5SDimitry Andric     C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
101350b57cec5SDimitry Andric     break;
101360b57cec5SDimitry Andric   }
101375ffd83dbSDimitry Andric   case llvm::omp::OMPC_device:
101380b57cec5SDimitry Andric     C = new (Context) OMPDeviceClause();
101390b57cec5SDimitry Andric     break;
101405ffd83dbSDimitry Andric   case llvm::omp::OMPC_map: {
101410b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
101420b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
101430b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
101440b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
101450b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
101460b57cec5SDimitry Andric     C = OMPMapClause::CreateEmpty(Context, Sizes);
101470b57cec5SDimitry Andric     break;
101480b57cec5SDimitry Andric   }
101495ffd83dbSDimitry Andric   case llvm::omp::OMPC_num_teams:
101500b57cec5SDimitry Andric     C = new (Context) OMPNumTeamsClause();
101510b57cec5SDimitry Andric     break;
101525ffd83dbSDimitry Andric   case llvm::omp::OMPC_thread_limit:
101530b57cec5SDimitry Andric     C = new (Context) OMPThreadLimitClause();
101540b57cec5SDimitry Andric     break;
101555ffd83dbSDimitry Andric   case llvm::omp::OMPC_priority:
101560b57cec5SDimitry Andric     C = new (Context) OMPPriorityClause();
101570b57cec5SDimitry Andric     break;
101585ffd83dbSDimitry Andric   case llvm::omp::OMPC_grainsize:
101590b57cec5SDimitry Andric     C = new (Context) OMPGrainsizeClause();
101600b57cec5SDimitry Andric     break;
101615ffd83dbSDimitry Andric   case llvm::omp::OMPC_num_tasks:
101620b57cec5SDimitry Andric     C = new (Context) OMPNumTasksClause();
101630b57cec5SDimitry Andric     break;
101645ffd83dbSDimitry Andric   case llvm::omp::OMPC_hint:
101650b57cec5SDimitry Andric     C = new (Context) OMPHintClause();
101660b57cec5SDimitry Andric     break;
101675ffd83dbSDimitry Andric   case llvm::omp::OMPC_dist_schedule:
101680b57cec5SDimitry Andric     C = new (Context) OMPDistScheduleClause();
101690b57cec5SDimitry Andric     break;
101705ffd83dbSDimitry Andric   case llvm::omp::OMPC_defaultmap:
101710b57cec5SDimitry Andric     C = new (Context) OMPDefaultmapClause();
101720b57cec5SDimitry Andric     break;
101735ffd83dbSDimitry Andric   case llvm::omp::OMPC_to: {
101740b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
101750b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
101760b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
101770b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
101780b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
101790b57cec5SDimitry Andric     C = OMPToClause::CreateEmpty(Context, Sizes);
101800b57cec5SDimitry Andric     break;
101810b57cec5SDimitry Andric   }
101825ffd83dbSDimitry Andric   case llvm::omp::OMPC_from: {
101830b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
101840b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
101850b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
101860b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
101870b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
101880b57cec5SDimitry Andric     C = OMPFromClause::CreateEmpty(Context, Sizes);
101890b57cec5SDimitry Andric     break;
101900b57cec5SDimitry Andric   }
101915ffd83dbSDimitry Andric   case llvm::omp::OMPC_use_device_ptr: {
101920b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
101930b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
101940b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
101950b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
101960b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
101970b57cec5SDimitry Andric     C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
101980b57cec5SDimitry Andric     break;
101990b57cec5SDimitry Andric   }
102005ffd83dbSDimitry Andric   case llvm::omp::OMPC_use_device_addr: {
102015ffd83dbSDimitry Andric     OMPMappableExprListSizeTy Sizes;
102025ffd83dbSDimitry Andric     Sizes.NumVars = Record.readInt();
102035ffd83dbSDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
102045ffd83dbSDimitry Andric     Sizes.NumComponentLists = Record.readInt();
102055ffd83dbSDimitry Andric     Sizes.NumComponents = Record.readInt();
102065ffd83dbSDimitry Andric     C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
102075ffd83dbSDimitry Andric     break;
102085ffd83dbSDimitry Andric   }
102095ffd83dbSDimitry Andric   case llvm::omp::OMPC_is_device_ptr: {
102100b57cec5SDimitry Andric     OMPMappableExprListSizeTy Sizes;
102110b57cec5SDimitry Andric     Sizes.NumVars = Record.readInt();
102120b57cec5SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
102130b57cec5SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
102140b57cec5SDimitry Andric     Sizes.NumComponents = Record.readInt();
102150b57cec5SDimitry Andric     C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
102160b57cec5SDimitry Andric     break;
102170b57cec5SDimitry Andric   }
1021881ad6265SDimitry Andric   case llvm::omp::OMPC_has_device_addr: {
1021981ad6265SDimitry Andric     OMPMappableExprListSizeTy Sizes;
1022081ad6265SDimitry Andric     Sizes.NumVars = Record.readInt();
1022181ad6265SDimitry Andric     Sizes.NumUniqueDeclarations = Record.readInt();
1022281ad6265SDimitry Andric     Sizes.NumComponentLists = Record.readInt();
1022381ad6265SDimitry Andric     Sizes.NumComponents = Record.readInt();
1022481ad6265SDimitry Andric     C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
1022581ad6265SDimitry Andric     break;
1022681ad6265SDimitry Andric   }
102275ffd83dbSDimitry Andric   case llvm::omp::OMPC_allocate:
102280b57cec5SDimitry Andric     C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
102290b57cec5SDimitry Andric     break;
102305ffd83dbSDimitry Andric   case llvm::omp::OMPC_nontemporal:
10231480093f4SDimitry Andric     C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
10232480093f4SDimitry Andric     break;
102335ffd83dbSDimitry Andric   case llvm::omp::OMPC_inclusive:
102345ffd83dbSDimitry Andric     C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
102355ffd83dbSDimitry Andric     break;
102365ffd83dbSDimitry Andric   case llvm::omp::OMPC_exclusive:
102375ffd83dbSDimitry Andric     C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
102385ffd83dbSDimitry Andric     break;
102395ffd83dbSDimitry Andric   case llvm::omp::OMPC_order:
102405ffd83dbSDimitry Andric     C = new (Context) OMPOrderClause();
102415ffd83dbSDimitry Andric     break;
10242fe6060f1SDimitry Andric   case llvm::omp::OMPC_init:
10243fe6060f1SDimitry Andric     C = OMPInitClause::CreateEmpty(Context, Record.readInt());
10244fe6060f1SDimitry Andric     break;
10245fe6060f1SDimitry Andric   case llvm::omp::OMPC_use:
10246fe6060f1SDimitry Andric     C = new (Context) OMPUseClause();
10247fe6060f1SDimitry Andric     break;
102485ffd83dbSDimitry Andric   case llvm::omp::OMPC_destroy:
102495ffd83dbSDimitry Andric     C = new (Context) OMPDestroyClause();
102505ffd83dbSDimitry Andric     break;
10251fe6060f1SDimitry Andric   case llvm::omp::OMPC_novariants:
10252fe6060f1SDimitry Andric     C = new (Context) OMPNovariantsClause();
10253fe6060f1SDimitry Andric     break;
10254fe6060f1SDimitry Andric   case llvm::omp::OMPC_nocontext:
10255fe6060f1SDimitry Andric     C = new (Context) OMPNocontextClause();
10256fe6060f1SDimitry Andric     break;
102575ffd83dbSDimitry Andric   case llvm::omp::OMPC_detach:
102585ffd83dbSDimitry Andric     C = new (Context) OMPDetachClause();
102595ffd83dbSDimitry Andric     break;
102605ffd83dbSDimitry Andric   case llvm::omp::OMPC_uses_allocators:
102615ffd83dbSDimitry Andric     C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
102625ffd83dbSDimitry Andric     break;
102635ffd83dbSDimitry Andric   case llvm::omp::OMPC_affinity:
102645ffd83dbSDimitry Andric     C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
102655ffd83dbSDimitry Andric     break;
10266fe6060f1SDimitry Andric   case llvm::omp::OMPC_filter:
10267fe6060f1SDimitry Andric     C = new (Context) OMPFilterClause();
10268fe6060f1SDimitry Andric     break;
10269349cc55cSDimitry Andric   case llvm::omp::OMPC_bind:
10270349cc55cSDimitry Andric     C = OMPBindClause::CreateEmpty(Context);
10271349cc55cSDimitry Andric     break;
10272349cc55cSDimitry Andric   case llvm::omp::OMPC_align:
10273349cc55cSDimitry Andric     C = new (Context) OMPAlignClause();
10274349cc55cSDimitry Andric     break;
10275*bdd1243dSDimitry Andric   case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
10276*bdd1243dSDimitry Andric     C = new (Context) OMPXDynCGroupMemClause();
10277*bdd1243dSDimitry Andric     break;
102785ffd83dbSDimitry Andric #define OMP_CLAUSE_NO_CLASS(Enum, Str)                                         \
102795ffd83dbSDimitry Andric   case llvm::omp::Enum:                                                        \
102805ffd83dbSDimitry Andric     break;
102815ffd83dbSDimitry Andric #include "llvm/Frontend/OpenMP/OMPKinds.def"
102825ffd83dbSDimitry Andric   default:
102835ffd83dbSDimitry Andric     break;
102840b57cec5SDimitry Andric   }
10285a7dea167SDimitry Andric   assert(C && "Unknown OMPClause type");
10286a7dea167SDimitry Andric 
102870b57cec5SDimitry Andric   Visit(C);
102880b57cec5SDimitry Andric   C->setLocStart(Record.readSourceLocation());
102890b57cec5SDimitry Andric   C->setLocEnd(Record.readSourceLocation());
102900b57cec5SDimitry Andric 
102910b57cec5SDimitry Andric   return C;
102920b57cec5SDimitry Andric }
102930b57cec5SDimitry Andric 
102940b57cec5SDimitry Andric void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
102950b57cec5SDimitry Andric   C->setPreInitStmt(Record.readSubStmt(),
102960b57cec5SDimitry Andric                     static_cast<OpenMPDirectiveKind>(Record.readInt()));
102970b57cec5SDimitry Andric }
102980b57cec5SDimitry Andric 
102990b57cec5SDimitry Andric void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
103000b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
103010b57cec5SDimitry Andric   C->setPostUpdateExpr(Record.readSubExpr());
103020b57cec5SDimitry Andric }
103030b57cec5SDimitry Andric 
103040b57cec5SDimitry Andric void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
103050b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
103060b57cec5SDimitry Andric   C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
103070b57cec5SDimitry Andric   C->setNameModifierLoc(Record.readSourceLocation());
103080b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
103090b57cec5SDimitry Andric   C->setCondition(Record.readSubExpr());
103100b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103110b57cec5SDimitry Andric }
103120b57cec5SDimitry Andric 
103130b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
10314a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
103150b57cec5SDimitry Andric   C->setCondition(Record.readSubExpr());
103160b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103170b57cec5SDimitry Andric }
103180b57cec5SDimitry Andric 
103190b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
103200b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
103210b57cec5SDimitry Andric   C->setNumThreads(Record.readSubExpr());
103220b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103230b57cec5SDimitry Andric }
103240b57cec5SDimitry Andric 
103250b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
103260b57cec5SDimitry Andric   C->setSafelen(Record.readSubExpr());
103270b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103280b57cec5SDimitry Andric }
103290b57cec5SDimitry Andric 
103300b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
103310b57cec5SDimitry Andric   C->setSimdlen(Record.readSubExpr());
103320b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103330b57cec5SDimitry Andric }
103340b57cec5SDimitry Andric 
10335fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
10336fe6060f1SDimitry Andric   for (Expr *&E : C->getSizesRefs())
10337fe6060f1SDimitry Andric     E = Record.readSubExpr();
10338fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10339fe6060f1SDimitry Andric }
10340fe6060f1SDimitry Andric 
10341fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
10342fe6060f1SDimitry Andric 
10343fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
10344fe6060f1SDimitry Andric   C->setFactor(Record.readSubExpr());
10345fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10346fe6060f1SDimitry Andric }
10347fe6060f1SDimitry Andric 
103480b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
103490b57cec5SDimitry Andric   C->setAllocator(Record.readExpr());
103500b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103510b57cec5SDimitry Andric }
103520b57cec5SDimitry Andric 
103530b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
103540b57cec5SDimitry Andric   C->setNumForLoops(Record.readSubExpr());
103550b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103560b57cec5SDimitry Andric }
103570b57cec5SDimitry Andric 
103580b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
103595ffd83dbSDimitry Andric   C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
103600b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103610b57cec5SDimitry Andric   C->setDefaultKindKwLoc(Record.readSourceLocation());
103620b57cec5SDimitry Andric }
103630b57cec5SDimitry Andric 
103640b57cec5SDimitry Andric void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
10365480093f4SDimitry Andric   C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
103660b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103670b57cec5SDimitry Andric   C->setProcBindKindKwLoc(Record.readSourceLocation());
103680b57cec5SDimitry Andric }
103690b57cec5SDimitry Andric 
103700b57cec5SDimitry Andric void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
103710b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
103720b57cec5SDimitry Andric   C->setScheduleKind(
103730b57cec5SDimitry Andric        static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
103740b57cec5SDimitry Andric   C->setFirstScheduleModifier(
103750b57cec5SDimitry Andric       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
103760b57cec5SDimitry Andric   C->setSecondScheduleModifier(
103770b57cec5SDimitry Andric       static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
103780b57cec5SDimitry Andric   C->setChunkSize(Record.readSubExpr());
103790b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103800b57cec5SDimitry Andric   C->setFirstScheduleModifierLoc(Record.readSourceLocation());
103810b57cec5SDimitry Andric   C->setSecondScheduleModifierLoc(Record.readSourceLocation());
103820b57cec5SDimitry Andric   C->setScheduleKindLoc(Record.readSourceLocation());
103830b57cec5SDimitry Andric   C->setCommaLoc(Record.readSourceLocation());
103840b57cec5SDimitry Andric }
103850b57cec5SDimitry Andric 
103860b57cec5SDimitry Andric void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
103870b57cec5SDimitry Andric   C->setNumForLoops(Record.readSubExpr());
103880b57cec5SDimitry Andric   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
103890b57cec5SDimitry Andric     C->setLoopNumIterations(I, Record.readSubExpr());
103900b57cec5SDimitry Andric   for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
103910b57cec5SDimitry Andric     C->setLoopCounter(I, Record.readSubExpr());
103920b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103930b57cec5SDimitry Andric }
103940b57cec5SDimitry Andric 
103955ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
103965ffd83dbSDimitry Andric   C->setEventHandler(Record.readSubExpr());
103975ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
103985ffd83dbSDimitry Andric }
103995ffd83dbSDimitry Andric 
104000b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
104010b57cec5SDimitry Andric 
104020b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
104030b57cec5SDimitry Andric 
104040b57cec5SDimitry Andric void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
104050b57cec5SDimitry Andric 
104060b57cec5SDimitry Andric void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
104070b57cec5SDimitry Andric 
104080b57cec5SDimitry Andric void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
104090b57cec5SDimitry Andric 
104105ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
104115ffd83dbSDimitry Andric   if (C->isExtended()) {
104125ffd83dbSDimitry Andric     C->setLParenLoc(Record.readSourceLocation());
104135ffd83dbSDimitry Andric     C->setArgumentLoc(Record.readSourceLocation());
104145ffd83dbSDimitry Andric     C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
104155ffd83dbSDimitry Andric   }
104165ffd83dbSDimitry Andric }
104170b57cec5SDimitry Andric 
104180b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
104190b57cec5SDimitry Andric 
104200eae32dcSDimitry Andric void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
104210eae32dcSDimitry Andric 
104220b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
104230b57cec5SDimitry Andric 
104245ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
104255ffd83dbSDimitry Andric 
104265ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
104275ffd83dbSDimitry Andric 
104285ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
104295ffd83dbSDimitry Andric 
104305ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
104315ffd83dbSDimitry Andric 
104320b57cec5SDimitry Andric void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
104330b57cec5SDimitry Andric 
104340b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
104350b57cec5SDimitry Andric 
104360b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
104370b57cec5SDimitry Andric 
10438fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
10439fe6060f1SDimitry Andric   unsigned NumVars = C->varlist_size();
10440fe6060f1SDimitry Andric   SmallVector<Expr *, 16> Vars;
10441fe6060f1SDimitry Andric   Vars.reserve(NumVars);
10442fe6060f1SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
10443fe6060f1SDimitry Andric     Vars.push_back(Record.readSubExpr());
10444fe6060f1SDimitry Andric   C->setVarRefs(Vars);
10445fe6060f1SDimitry Andric   C->setIsTarget(Record.readBool());
10446fe6060f1SDimitry Andric   C->setIsTargetSync(Record.readBool());
10447fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10448fe6060f1SDimitry Andric   C->setVarLoc(Record.readSourceLocation());
10449fe6060f1SDimitry Andric }
10450fe6060f1SDimitry Andric 
10451fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
10452fe6060f1SDimitry Andric   C->setInteropVar(Record.readSubExpr());
10453fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10454fe6060f1SDimitry Andric   C->setVarLoc(Record.readSourceLocation());
10455fe6060f1SDimitry Andric }
10456fe6060f1SDimitry Andric 
10457fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
10458fe6060f1SDimitry Andric   C->setInteropVar(Record.readSubExpr());
10459fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10460fe6060f1SDimitry Andric   C->setVarLoc(Record.readSourceLocation());
10461fe6060f1SDimitry Andric }
10462fe6060f1SDimitry Andric 
10463fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
10464fe6060f1SDimitry Andric   VisitOMPClauseWithPreInit(C);
10465fe6060f1SDimitry Andric   C->setCondition(Record.readSubExpr());
10466fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10467fe6060f1SDimitry Andric }
10468fe6060f1SDimitry Andric 
10469fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
10470fe6060f1SDimitry Andric   VisitOMPClauseWithPreInit(C);
10471fe6060f1SDimitry Andric   C->setCondition(Record.readSubExpr());
10472fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10473fe6060f1SDimitry Andric }
104745ffd83dbSDimitry Andric 
104750b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
104760b57cec5SDimitry Andric 
104770b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
104780b57cec5SDimitry Andric     OMPUnifiedSharedMemoryClause *) {}
104790b57cec5SDimitry Andric 
104800b57cec5SDimitry Andric void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
104810b57cec5SDimitry Andric 
104820b57cec5SDimitry Andric void
104830b57cec5SDimitry Andric OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
104840b57cec5SDimitry Andric }
104850b57cec5SDimitry Andric 
104860b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
104870b57cec5SDimitry Andric     OMPAtomicDefaultMemOrderClause *C) {
104880b57cec5SDimitry Andric   C->setAtomicDefaultMemOrderKind(
104890b57cec5SDimitry Andric       static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
104900b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
104910b57cec5SDimitry Andric   C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
104920b57cec5SDimitry Andric }
104930b57cec5SDimitry Andric 
10494*bdd1243dSDimitry Andric void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
10495*bdd1243dSDimitry Andric   C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
10496*bdd1243dSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10497*bdd1243dSDimitry Andric   C->setAtKindKwLoc(Record.readSourceLocation());
10498*bdd1243dSDimitry Andric }
10499*bdd1243dSDimitry Andric 
10500*bdd1243dSDimitry Andric void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
10501*bdd1243dSDimitry Andric   C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
10502*bdd1243dSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10503*bdd1243dSDimitry Andric   C->setSeverityKindKwLoc(Record.readSourceLocation());
10504*bdd1243dSDimitry Andric }
10505*bdd1243dSDimitry Andric 
10506*bdd1243dSDimitry Andric void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
10507*bdd1243dSDimitry Andric   C->setMessageString(Record.readSubExpr());
10508*bdd1243dSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10509*bdd1243dSDimitry Andric }
10510*bdd1243dSDimitry Andric 
105110b57cec5SDimitry Andric void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
105120b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
105130b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
105140b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
105150b57cec5SDimitry Andric   Vars.reserve(NumVars);
105160b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105170b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105180b57cec5SDimitry Andric   C->setVarRefs(Vars);
105190b57cec5SDimitry Andric   Vars.clear();
105200b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105210b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105220b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
105230b57cec5SDimitry Andric }
105240b57cec5SDimitry Andric 
105250b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
105260b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
105270b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
105280b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
105290b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
105300b57cec5SDimitry Andric   Vars.reserve(NumVars);
105310b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105320b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105330b57cec5SDimitry Andric   C->setVarRefs(Vars);
105340b57cec5SDimitry Andric   Vars.clear();
105350b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105360b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105370b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
105380b57cec5SDimitry Andric   Vars.clear();
105390b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105400b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105410b57cec5SDimitry Andric   C->setInits(Vars);
105420b57cec5SDimitry Andric }
105430b57cec5SDimitry Andric 
105440b57cec5SDimitry Andric void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
105450b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
105460b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10547480093f4SDimitry Andric   C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
10548480093f4SDimitry Andric   C->setKindLoc(Record.readSourceLocation());
10549480093f4SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
105500b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
105510b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
105520b57cec5SDimitry Andric   Vars.reserve(NumVars);
105530b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105540b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105550b57cec5SDimitry Andric   C->setVarRefs(Vars);
105560b57cec5SDimitry Andric   Vars.clear();
105570b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105580b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105590b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
105600b57cec5SDimitry Andric   Vars.clear();
105610b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105620b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105630b57cec5SDimitry Andric   C->setSourceExprs(Vars);
105640b57cec5SDimitry Andric   Vars.clear();
105650b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105660b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105670b57cec5SDimitry Andric   C->setDestinationExprs(Vars);
105680b57cec5SDimitry Andric   Vars.clear();
105690b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105700b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105710b57cec5SDimitry Andric   C->setAssignmentOps(Vars);
105720b57cec5SDimitry Andric }
105730b57cec5SDimitry Andric 
105740b57cec5SDimitry Andric void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
105750b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
105760b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
105770b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
105780b57cec5SDimitry Andric   Vars.reserve(NumVars);
105790b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105800b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105810b57cec5SDimitry Andric   C->setVarRefs(Vars);
105820b57cec5SDimitry Andric }
105830b57cec5SDimitry Andric 
105840b57cec5SDimitry Andric void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
105850b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
105860b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
105875ffd83dbSDimitry Andric   C->setModifierLoc(Record.readSourceLocation());
105880b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
105890b57cec5SDimitry Andric   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10590480093f4SDimitry Andric   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
105910b57cec5SDimitry Andric   C->setQualifierLoc(NNSL);
105920b57cec5SDimitry Andric   C->setNameInfo(DNI);
105930b57cec5SDimitry Andric 
105940b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
105950b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
105960b57cec5SDimitry Andric   Vars.reserve(NumVars);
105970b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
105980b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
105990b57cec5SDimitry Andric   C->setVarRefs(Vars);
106000b57cec5SDimitry Andric   Vars.clear();
106010b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
106020b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106030b57cec5SDimitry Andric   C->setPrivates(Vars);
106040b57cec5SDimitry Andric   Vars.clear();
106050b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
106060b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106070b57cec5SDimitry Andric   C->setLHSExprs(Vars);
106080b57cec5SDimitry Andric   Vars.clear();
106090b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
106100b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106110b57cec5SDimitry Andric   C->setRHSExprs(Vars);
106120b57cec5SDimitry Andric   Vars.clear();
106130b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
106140b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106150b57cec5SDimitry Andric   C->setReductionOps(Vars);
106165ffd83dbSDimitry Andric   if (C->getModifier() == OMPC_REDUCTION_inscan) {
106175ffd83dbSDimitry Andric     Vars.clear();
106185ffd83dbSDimitry Andric     for (unsigned i = 0; i != NumVars; ++i)
106195ffd83dbSDimitry Andric       Vars.push_back(Record.readSubExpr());
106205ffd83dbSDimitry Andric     C->setInscanCopyOps(Vars);
106215ffd83dbSDimitry Andric     Vars.clear();
106225ffd83dbSDimitry Andric     for (unsigned i = 0; i != NumVars; ++i)
106235ffd83dbSDimitry Andric       Vars.push_back(Record.readSubExpr());
106245ffd83dbSDimitry Andric     C->setInscanCopyArrayTemps(Vars);
106255ffd83dbSDimitry Andric     Vars.clear();
106265ffd83dbSDimitry Andric     for (unsigned i = 0; i != NumVars; ++i)
106275ffd83dbSDimitry Andric       Vars.push_back(Record.readSubExpr());
106285ffd83dbSDimitry Andric     C->setInscanCopyArrayElems(Vars);
106295ffd83dbSDimitry Andric   }
106300b57cec5SDimitry Andric }
106310b57cec5SDimitry Andric 
106320b57cec5SDimitry Andric void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
106330b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
106340b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
106350b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
106360b57cec5SDimitry Andric   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10637480093f4SDimitry Andric   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
106380b57cec5SDimitry Andric   C->setQualifierLoc(NNSL);
106390b57cec5SDimitry Andric   C->setNameInfo(DNI);
106400b57cec5SDimitry Andric 
106410b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
106420b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
106430b57cec5SDimitry Andric   Vars.reserve(NumVars);
106440b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106450b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106460b57cec5SDimitry Andric   C->setVarRefs(Vars);
106470b57cec5SDimitry Andric   Vars.clear();
106480b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106490b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106500b57cec5SDimitry Andric   C->setPrivates(Vars);
106510b57cec5SDimitry Andric   Vars.clear();
106520b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106530b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106540b57cec5SDimitry Andric   C->setLHSExprs(Vars);
106550b57cec5SDimitry Andric   Vars.clear();
106560b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106570b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106580b57cec5SDimitry Andric   C->setRHSExprs(Vars);
106590b57cec5SDimitry Andric   Vars.clear();
106600b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106610b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106620b57cec5SDimitry Andric   C->setReductionOps(Vars);
106630b57cec5SDimitry Andric }
106640b57cec5SDimitry Andric 
106650b57cec5SDimitry Andric void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
106660b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
106670b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
106680b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
106690b57cec5SDimitry Andric   NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
10670480093f4SDimitry Andric   DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
106710b57cec5SDimitry Andric   C->setQualifierLoc(NNSL);
106720b57cec5SDimitry Andric   C->setNameInfo(DNI);
106730b57cec5SDimitry Andric 
106740b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
106750b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
106760b57cec5SDimitry Andric   Vars.reserve(NumVars);
106770b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106780b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106790b57cec5SDimitry Andric   C->setVarRefs(Vars);
106800b57cec5SDimitry Andric   Vars.clear();
106810b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106820b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106830b57cec5SDimitry Andric   C->setPrivates(Vars);
106840b57cec5SDimitry Andric   Vars.clear();
106850b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106860b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106870b57cec5SDimitry Andric   C->setLHSExprs(Vars);
106880b57cec5SDimitry Andric   Vars.clear();
106890b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106900b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106910b57cec5SDimitry Andric   C->setRHSExprs(Vars);
106920b57cec5SDimitry Andric   Vars.clear();
106930b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106940b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106950b57cec5SDimitry Andric   C->setReductionOps(Vars);
106960b57cec5SDimitry Andric   Vars.clear();
106970b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
106980b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
106990b57cec5SDimitry Andric   C->setTaskgroupDescriptors(Vars);
107000b57cec5SDimitry Andric }
107010b57cec5SDimitry Andric 
107020b57cec5SDimitry Andric void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
107030b57cec5SDimitry Andric   VisitOMPClauseWithPostUpdate(C);
107040b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
107050b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
107060b57cec5SDimitry Andric   C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
107070b57cec5SDimitry Andric   C->setModifierLoc(Record.readSourceLocation());
107080b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
107090b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
107100b57cec5SDimitry Andric   Vars.reserve(NumVars);
107110b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107120b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
107130b57cec5SDimitry Andric   C->setVarRefs(Vars);
107140b57cec5SDimitry Andric   Vars.clear();
107150b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107160b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
107170b57cec5SDimitry Andric   C->setPrivates(Vars);
107180b57cec5SDimitry Andric   Vars.clear();
107190b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107200b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
107210b57cec5SDimitry Andric   C->setInits(Vars);
107220b57cec5SDimitry Andric   Vars.clear();
107230b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107240b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
107250b57cec5SDimitry Andric   C->setUpdates(Vars);
107260b57cec5SDimitry Andric   Vars.clear();
107270b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107280b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
107290b57cec5SDimitry Andric   C->setFinals(Vars);
107300b57cec5SDimitry Andric   C->setStep(Record.readSubExpr());
107310b57cec5SDimitry Andric   C->setCalcStep(Record.readSubExpr());
10732a7dea167SDimitry Andric   Vars.clear();
10733a7dea167SDimitry Andric   for (unsigned I = 0; I != NumVars + 1; ++I)
10734a7dea167SDimitry Andric     Vars.push_back(Record.readSubExpr());
10735a7dea167SDimitry Andric   C->setUsedExprs(Vars);
107360b57cec5SDimitry Andric }
107370b57cec5SDimitry Andric 
107380b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
107390b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
107400b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
107410b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
107420b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
107430b57cec5SDimitry Andric   Vars.reserve(NumVars);
107440b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107450b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
107460b57cec5SDimitry Andric   C->setVarRefs(Vars);
107470b57cec5SDimitry Andric   C->setAlignment(Record.readSubExpr());
107480b57cec5SDimitry Andric }
107490b57cec5SDimitry Andric 
107500b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
107510b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
107520b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
107530b57cec5SDimitry Andric   SmallVector<Expr *, 16> Exprs;
107540b57cec5SDimitry Andric   Exprs.reserve(NumVars);
107550b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107560b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107570b57cec5SDimitry Andric   C->setVarRefs(Exprs);
107580b57cec5SDimitry Andric   Exprs.clear();
107590b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107600b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107610b57cec5SDimitry Andric   C->setSourceExprs(Exprs);
107620b57cec5SDimitry Andric   Exprs.clear();
107630b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107640b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107650b57cec5SDimitry Andric   C->setDestinationExprs(Exprs);
107660b57cec5SDimitry Andric   Exprs.clear();
107670b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107680b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107690b57cec5SDimitry Andric   C->setAssignmentOps(Exprs);
107700b57cec5SDimitry Andric }
107710b57cec5SDimitry Andric 
107720b57cec5SDimitry Andric void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
107730b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
107740b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
107750b57cec5SDimitry Andric   SmallVector<Expr *, 16> Exprs;
107760b57cec5SDimitry Andric   Exprs.reserve(NumVars);
107770b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107780b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107790b57cec5SDimitry Andric   C->setVarRefs(Exprs);
107800b57cec5SDimitry Andric   Exprs.clear();
107810b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107820b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107830b57cec5SDimitry Andric   C->setSourceExprs(Exprs);
107840b57cec5SDimitry Andric   Exprs.clear();
107850b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107860b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107870b57cec5SDimitry Andric   C->setDestinationExprs(Exprs);
107880b57cec5SDimitry Andric   Exprs.clear();
107890b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
107900b57cec5SDimitry Andric     Exprs.push_back(Record.readSubExpr());
107910b57cec5SDimitry Andric   C->setAssignmentOps(Exprs);
107920b57cec5SDimitry Andric }
107930b57cec5SDimitry Andric 
107940b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
107950b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
107960b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
107970b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
107980b57cec5SDimitry Andric   Vars.reserve(NumVars);
107990b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
108000b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
108010b57cec5SDimitry Andric   C->setVarRefs(Vars);
108020b57cec5SDimitry Andric }
108030b57cec5SDimitry Andric 
108045ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
108055ffd83dbSDimitry Andric   C->setDepobj(Record.readSubExpr());
108065ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
108075ffd83dbSDimitry Andric }
108085ffd83dbSDimitry Andric 
108090b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
108100b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
108115ffd83dbSDimitry Andric   C->setModifier(Record.readSubExpr());
108120b57cec5SDimitry Andric   C->setDependencyKind(
108130b57cec5SDimitry Andric       static_cast<OpenMPDependClauseKind>(Record.readInt()));
108140b57cec5SDimitry Andric   C->setDependencyLoc(Record.readSourceLocation());
108150b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
1081681ad6265SDimitry Andric   C->setOmpAllMemoryLoc(Record.readSourceLocation());
108170b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
108180b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
108190b57cec5SDimitry Andric   Vars.reserve(NumVars);
108200b57cec5SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
108210b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
108220b57cec5SDimitry Andric   C->setVarRefs(Vars);
108230b57cec5SDimitry Andric   for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
108240b57cec5SDimitry Andric     C->setLoopData(I, Record.readSubExpr());
108250b57cec5SDimitry Andric }
108260b57cec5SDimitry Andric 
108270b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
108280b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
108295ffd83dbSDimitry Andric   C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
108300b57cec5SDimitry Andric   C->setDevice(Record.readSubExpr());
108315ffd83dbSDimitry Andric   C->setModifierLoc(Record.readSourceLocation());
108320b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
108330b57cec5SDimitry Andric }
108340b57cec5SDimitry Andric 
108350b57cec5SDimitry Andric void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
108360b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10837*bdd1243dSDimitry Andric   bool HasIteratorModifier = false;
108385ffd83dbSDimitry Andric   for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
108390b57cec5SDimitry Andric     C->setMapTypeModifier(
108400b57cec5SDimitry Andric         I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
108410b57cec5SDimitry Andric     C->setMapTypeModifierLoc(I, Record.readSourceLocation());
10842*bdd1243dSDimitry Andric     if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
10843*bdd1243dSDimitry Andric       HasIteratorModifier = true;
108440b57cec5SDimitry Andric   }
108450b57cec5SDimitry Andric   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
10846480093f4SDimitry Andric   C->setMapperIdInfo(Record.readDeclarationNameInfo());
108470b57cec5SDimitry Andric   C->setMapType(
108480b57cec5SDimitry Andric      static_cast<OpenMPMapClauseKind>(Record.readInt()));
108490b57cec5SDimitry Andric   C->setMapLoc(Record.readSourceLocation());
108500b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
108510b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
108520b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
108530b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
108540b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
108550b57cec5SDimitry Andric 
108560b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
108570b57cec5SDimitry Andric   Vars.reserve(NumVars);
108580b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
108590b57cec5SDimitry Andric     Vars.push_back(Record.readExpr());
108600b57cec5SDimitry Andric   C->setVarRefs(Vars);
108610b57cec5SDimitry Andric 
108620b57cec5SDimitry Andric   SmallVector<Expr *, 16> UDMappers;
108630b57cec5SDimitry Andric   UDMappers.reserve(NumVars);
108640b57cec5SDimitry Andric   for (unsigned I = 0; I < NumVars; ++I)
108650b57cec5SDimitry Andric     UDMappers.push_back(Record.readExpr());
108660b57cec5SDimitry Andric   C->setUDMapperRefs(UDMappers);
108670b57cec5SDimitry Andric 
10868*bdd1243dSDimitry Andric   if (HasIteratorModifier)
10869*bdd1243dSDimitry Andric     C->setIteratorModifier(Record.readExpr());
10870*bdd1243dSDimitry Andric 
108710b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
108720b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
108730b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
108740b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
108750b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
108760b57cec5SDimitry Andric 
108770b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
108780b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
108790b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
108800b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
108810b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
108820b57cec5SDimitry Andric 
108830b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
108840b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
108850b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
108860b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
108870b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
108880b57cec5SDimitry Andric 
108890b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
108900b57cec5SDimitry Andric   Components.reserve(TotalComponents);
108910b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
10892e8d8bef9SDimitry Andric     Expr *AssociatedExprPr = Record.readExpr();
108930b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
10894e8d8bef9SDimitry Andric     Components.emplace_back(AssociatedExprPr, AssociatedDecl,
10895e8d8bef9SDimitry Andric                             /*IsNonContiguous=*/false);
108960b57cec5SDimitry Andric   }
108970b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
108980b57cec5SDimitry Andric }
108990b57cec5SDimitry Andric 
109000b57cec5SDimitry Andric void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
109010b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109020b57cec5SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
109030b57cec5SDimitry Andric   C->setAllocator(Record.readSubExpr());
109040b57cec5SDimitry Andric   unsigned NumVars = C->varlist_size();
109050b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
109060b57cec5SDimitry Andric   Vars.reserve(NumVars);
109070b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
109080b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
109090b57cec5SDimitry Andric   C->setVarRefs(Vars);
109100b57cec5SDimitry Andric }
109110b57cec5SDimitry Andric 
109120b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
109130b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
109140b57cec5SDimitry Andric   C->setNumTeams(Record.readSubExpr());
109150b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109160b57cec5SDimitry Andric }
109170b57cec5SDimitry Andric 
109180b57cec5SDimitry Andric void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
109190b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
109200b57cec5SDimitry Andric   C->setThreadLimit(Record.readSubExpr());
109210b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109220b57cec5SDimitry Andric }
109230b57cec5SDimitry Andric 
109240b57cec5SDimitry Andric void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
10925a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
109260b57cec5SDimitry Andric   C->setPriority(Record.readSubExpr());
109270b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109280b57cec5SDimitry Andric }
109290b57cec5SDimitry Andric 
109300b57cec5SDimitry Andric void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
10931a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
10932*bdd1243dSDimitry Andric   C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
109330b57cec5SDimitry Andric   C->setGrainsize(Record.readSubExpr());
10934*bdd1243dSDimitry Andric   C->setModifierLoc(Record.readSourceLocation());
109350b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109360b57cec5SDimitry Andric }
109370b57cec5SDimitry Andric 
109380b57cec5SDimitry Andric void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
10939a7dea167SDimitry Andric   VisitOMPClauseWithPreInit(C);
10940*bdd1243dSDimitry Andric   C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
109410b57cec5SDimitry Andric   C->setNumTasks(Record.readSubExpr());
10942*bdd1243dSDimitry Andric   C->setModifierLoc(Record.readSourceLocation());
109430b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109440b57cec5SDimitry Andric }
109450b57cec5SDimitry Andric 
109460b57cec5SDimitry Andric void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
109470b57cec5SDimitry Andric   C->setHint(Record.readSubExpr());
109480b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109490b57cec5SDimitry Andric }
109500b57cec5SDimitry Andric 
109510b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
109520b57cec5SDimitry Andric   VisitOMPClauseWithPreInit(C);
109530b57cec5SDimitry Andric   C->setDistScheduleKind(
109540b57cec5SDimitry Andric       static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
109550b57cec5SDimitry Andric   C->setChunkSize(Record.readSubExpr());
109560b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109570b57cec5SDimitry Andric   C->setDistScheduleKindLoc(Record.readSourceLocation());
109580b57cec5SDimitry Andric   C->setCommaLoc(Record.readSourceLocation());
109590b57cec5SDimitry Andric }
109600b57cec5SDimitry Andric 
109610b57cec5SDimitry Andric void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
109620b57cec5SDimitry Andric   C->setDefaultmapKind(
109630b57cec5SDimitry Andric        static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
109640b57cec5SDimitry Andric   C->setDefaultmapModifier(
109650b57cec5SDimitry Andric       static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
109660b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
109670b57cec5SDimitry Andric   C->setDefaultmapModifierLoc(Record.readSourceLocation());
109680b57cec5SDimitry Andric   C->setDefaultmapKindLoc(Record.readSourceLocation());
109690b57cec5SDimitry Andric }
109700b57cec5SDimitry Andric 
109710b57cec5SDimitry Andric void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
109720b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
10973e8d8bef9SDimitry Andric   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
10974e8d8bef9SDimitry Andric     C->setMotionModifier(
10975e8d8bef9SDimitry Andric         I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
10976e8d8bef9SDimitry Andric     C->setMotionModifierLoc(I, Record.readSourceLocation());
10977e8d8bef9SDimitry Andric   }
109780b57cec5SDimitry Andric   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
10979480093f4SDimitry Andric   C->setMapperIdInfo(Record.readDeclarationNameInfo());
10980e8d8bef9SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
109810b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
109820b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
109830b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
109840b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
109850b57cec5SDimitry Andric 
109860b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
109870b57cec5SDimitry Andric   Vars.reserve(NumVars);
109880b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
109890b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
109900b57cec5SDimitry Andric   C->setVarRefs(Vars);
109910b57cec5SDimitry Andric 
109920b57cec5SDimitry Andric   SmallVector<Expr *, 16> UDMappers;
109930b57cec5SDimitry Andric   UDMappers.reserve(NumVars);
109940b57cec5SDimitry Andric   for (unsigned I = 0; I < NumVars; ++I)
109950b57cec5SDimitry Andric     UDMappers.push_back(Record.readSubExpr());
109960b57cec5SDimitry Andric   C->setUDMapperRefs(UDMappers);
109970b57cec5SDimitry Andric 
109980b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
109990b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
110000b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
110010b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
110020b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
110030b57cec5SDimitry Andric 
110040b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
110050b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
110060b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
110070b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
110080b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
110090b57cec5SDimitry Andric 
110100b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
110110b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
110120b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
110130b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
110140b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
110150b57cec5SDimitry Andric 
110160b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
110170b57cec5SDimitry Andric   Components.reserve(TotalComponents);
110180b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
11019e8d8bef9SDimitry Andric     Expr *AssociatedExprPr = Record.readSubExpr();
11020e8d8bef9SDimitry Andric     bool IsNonContiguous = Record.readBool();
110210b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11022e8d8bef9SDimitry Andric     Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
110230b57cec5SDimitry Andric   }
110240b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
110250b57cec5SDimitry Andric }
110260b57cec5SDimitry Andric 
110270b57cec5SDimitry Andric void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
110280b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11029e8d8bef9SDimitry Andric   for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
11030e8d8bef9SDimitry Andric     C->setMotionModifier(
11031e8d8bef9SDimitry Andric         I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
11032e8d8bef9SDimitry Andric     C->setMotionModifierLoc(I, Record.readSourceLocation());
11033e8d8bef9SDimitry Andric   }
110340b57cec5SDimitry Andric   C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
11035480093f4SDimitry Andric   C->setMapperIdInfo(Record.readDeclarationNameInfo());
11036e8d8bef9SDimitry Andric   C->setColonLoc(Record.readSourceLocation());
110370b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
110380b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
110390b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
110400b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
110410b57cec5SDimitry Andric 
110420b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
110430b57cec5SDimitry Andric   Vars.reserve(NumVars);
110440b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
110450b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
110460b57cec5SDimitry Andric   C->setVarRefs(Vars);
110470b57cec5SDimitry Andric 
110480b57cec5SDimitry Andric   SmallVector<Expr *, 16> UDMappers;
110490b57cec5SDimitry Andric   UDMappers.reserve(NumVars);
110500b57cec5SDimitry Andric   for (unsigned I = 0; I < NumVars; ++I)
110510b57cec5SDimitry Andric     UDMappers.push_back(Record.readSubExpr());
110520b57cec5SDimitry Andric   C->setUDMapperRefs(UDMappers);
110530b57cec5SDimitry Andric 
110540b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
110550b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
110560b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
110570b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
110580b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
110590b57cec5SDimitry Andric 
110600b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
110610b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
110620b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
110630b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
110640b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
110650b57cec5SDimitry Andric 
110660b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
110670b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
110680b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
110690b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
110700b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
110710b57cec5SDimitry Andric 
110720b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
110730b57cec5SDimitry Andric   Components.reserve(TotalComponents);
110740b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
11075e8d8bef9SDimitry Andric     Expr *AssociatedExprPr = Record.readSubExpr();
11076e8d8bef9SDimitry Andric     bool IsNonContiguous = Record.readBool();
110770b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11078e8d8bef9SDimitry Andric     Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
110790b57cec5SDimitry Andric   }
110800b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
110810b57cec5SDimitry Andric }
110820b57cec5SDimitry Andric 
110830b57cec5SDimitry Andric void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
110840b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
110850b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
110860b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
110870b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
110880b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
110890b57cec5SDimitry Andric 
110900b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
110910b57cec5SDimitry Andric   Vars.reserve(NumVars);
110920b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
110930b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
110940b57cec5SDimitry Andric   C->setVarRefs(Vars);
110950b57cec5SDimitry Andric   Vars.clear();
110960b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
110970b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
110980b57cec5SDimitry Andric   C->setPrivateCopies(Vars);
110990b57cec5SDimitry Andric   Vars.clear();
111000b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
111010b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
111020b57cec5SDimitry Andric   C->setInits(Vars);
111030b57cec5SDimitry Andric 
111040b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
111050b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
111060b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
111070b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
111080b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
111090b57cec5SDimitry Andric 
111100b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
111110b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
111120b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
111130b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
111140b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
111150b57cec5SDimitry Andric 
111160b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
111170b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
111180b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
111190b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
111200b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
111210b57cec5SDimitry Andric 
111220b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
111230b57cec5SDimitry Andric   Components.reserve(TotalComponents);
111240b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
11125e8d8bef9SDimitry Andric     auto *AssociatedExprPr = Record.readSubExpr();
111260b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11127e8d8bef9SDimitry Andric     Components.emplace_back(AssociatedExprPr, AssociatedDecl,
11128e8d8bef9SDimitry Andric                             /*IsNonContiguous=*/false);
111290b57cec5SDimitry Andric   }
111300b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
111310b57cec5SDimitry Andric }
111320b57cec5SDimitry Andric 
111335ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
111345ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
111355ffd83dbSDimitry Andric   auto NumVars = C->varlist_size();
111365ffd83dbSDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
111375ffd83dbSDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
111385ffd83dbSDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
111395ffd83dbSDimitry Andric 
111405ffd83dbSDimitry Andric   SmallVector<Expr *, 16> Vars;
111415ffd83dbSDimitry Andric   Vars.reserve(NumVars);
111425ffd83dbSDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
111435ffd83dbSDimitry Andric     Vars.push_back(Record.readSubExpr());
111445ffd83dbSDimitry Andric   C->setVarRefs(Vars);
111455ffd83dbSDimitry Andric 
111465ffd83dbSDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
111475ffd83dbSDimitry Andric   Decls.reserve(UniqueDecls);
111485ffd83dbSDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
111495ffd83dbSDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
111505ffd83dbSDimitry Andric   C->setUniqueDecls(Decls);
111515ffd83dbSDimitry Andric 
111525ffd83dbSDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
111535ffd83dbSDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
111545ffd83dbSDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
111555ffd83dbSDimitry Andric     ListsPerDecl.push_back(Record.readInt());
111565ffd83dbSDimitry Andric   C->setDeclNumLists(ListsPerDecl);
111575ffd83dbSDimitry Andric 
111585ffd83dbSDimitry Andric   SmallVector<unsigned, 32> ListSizes;
111595ffd83dbSDimitry Andric   ListSizes.reserve(TotalLists);
111605ffd83dbSDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
111615ffd83dbSDimitry Andric     ListSizes.push_back(Record.readInt());
111625ffd83dbSDimitry Andric   C->setComponentListSizes(ListSizes);
111635ffd83dbSDimitry Andric 
111645ffd83dbSDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
111655ffd83dbSDimitry Andric   Components.reserve(TotalComponents);
111665ffd83dbSDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
111675ffd83dbSDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
111685ffd83dbSDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11169e8d8bef9SDimitry Andric     Components.emplace_back(AssociatedExpr, AssociatedDecl,
11170e8d8bef9SDimitry Andric                             /*IsNonContiguous*/ false);
111715ffd83dbSDimitry Andric   }
111725ffd83dbSDimitry Andric   C->setComponents(Components, ListSizes);
111735ffd83dbSDimitry Andric }
111745ffd83dbSDimitry Andric 
111750b57cec5SDimitry Andric void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
111760b57cec5SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
111770b57cec5SDimitry Andric   auto NumVars = C->varlist_size();
111780b57cec5SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
111790b57cec5SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
111800b57cec5SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
111810b57cec5SDimitry Andric 
111820b57cec5SDimitry Andric   SmallVector<Expr *, 16> Vars;
111830b57cec5SDimitry Andric   Vars.reserve(NumVars);
111840b57cec5SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
111850b57cec5SDimitry Andric     Vars.push_back(Record.readSubExpr());
111860b57cec5SDimitry Andric   C->setVarRefs(Vars);
111870b57cec5SDimitry Andric   Vars.clear();
111880b57cec5SDimitry Andric 
111890b57cec5SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
111900b57cec5SDimitry Andric   Decls.reserve(UniqueDecls);
111910b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
111920b57cec5SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
111930b57cec5SDimitry Andric   C->setUniqueDecls(Decls);
111940b57cec5SDimitry Andric 
111950b57cec5SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
111960b57cec5SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
111970b57cec5SDimitry Andric   for (unsigned i = 0; i < UniqueDecls; ++i)
111980b57cec5SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
111990b57cec5SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
112000b57cec5SDimitry Andric 
112010b57cec5SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
112020b57cec5SDimitry Andric   ListSizes.reserve(TotalLists);
112030b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
112040b57cec5SDimitry Andric     ListSizes.push_back(Record.readInt());
112050b57cec5SDimitry Andric   C->setComponentListSizes(ListSizes);
112060b57cec5SDimitry Andric 
112070b57cec5SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
112080b57cec5SDimitry Andric   Components.reserve(TotalComponents);
112090b57cec5SDimitry Andric   for (unsigned i = 0; i < TotalComponents; ++i) {
112100b57cec5SDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
112110b57cec5SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
11212e8d8bef9SDimitry Andric     Components.emplace_back(AssociatedExpr, AssociatedDecl,
11213e8d8bef9SDimitry Andric                             /*IsNonContiguous=*/false);
112140b57cec5SDimitry Andric   }
112150b57cec5SDimitry Andric   C->setComponents(Components, ListSizes);
112160b57cec5SDimitry Andric }
11217480093f4SDimitry Andric 
1121881ad6265SDimitry Andric void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
1121981ad6265SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
1122081ad6265SDimitry Andric   auto NumVars = C->varlist_size();
1122181ad6265SDimitry Andric   auto UniqueDecls = C->getUniqueDeclarationsNum();
1122281ad6265SDimitry Andric   auto TotalLists = C->getTotalComponentListNum();
1122381ad6265SDimitry Andric   auto TotalComponents = C->getTotalComponentsNum();
1122481ad6265SDimitry Andric 
1122581ad6265SDimitry Andric   SmallVector<Expr *, 16> Vars;
1122681ad6265SDimitry Andric   Vars.reserve(NumVars);
1122781ad6265SDimitry Andric   for (unsigned I = 0; I != NumVars; ++I)
1122881ad6265SDimitry Andric     Vars.push_back(Record.readSubExpr());
1122981ad6265SDimitry Andric   C->setVarRefs(Vars);
1123081ad6265SDimitry Andric   Vars.clear();
1123181ad6265SDimitry Andric 
1123281ad6265SDimitry Andric   SmallVector<ValueDecl *, 16> Decls;
1123381ad6265SDimitry Andric   Decls.reserve(UniqueDecls);
1123481ad6265SDimitry Andric   for (unsigned I = 0; I < UniqueDecls; ++I)
1123581ad6265SDimitry Andric     Decls.push_back(Record.readDeclAs<ValueDecl>());
1123681ad6265SDimitry Andric   C->setUniqueDecls(Decls);
1123781ad6265SDimitry Andric 
1123881ad6265SDimitry Andric   SmallVector<unsigned, 16> ListsPerDecl;
1123981ad6265SDimitry Andric   ListsPerDecl.reserve(UniqueDecls);
1124081ad6265SDimitry Andric   for (unsigned I = 0; I < UniqueDecls; ++I)
1124181ad6265SDimitry Andric     ListsPerDecl.push_back(Record.readInt());
1124281ad6265SDimitry Andric   C->setDeclNumLists(ListsPerDecl);
1124381ad6265SDimitry Andric 
1124481ad6265SDimitry Andric   SmallVector<unsigned, 32> ListSizes;
1124581ad6265SDimitry Andric   ListSizes.reserve(TotalLists);
1124681ad6265SDimitry Andric   for (unsigned i = 0; i < TotalLists; ++i)
1124781ad6265SDimitry Andric     ListSizes.push_back(Record.readInt());
1124881ad6265SDimitry Andric   C->setComponentListSizes(ListSizes);
1124981ad6265SDimitry Andric 
1125081ad6265SDimitry Andric   SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
1125181ad6265SDimitry Andric   Components.reserve(TotalComponents);
1125281ad6265SDimitry Andric   for (unsigned I = 0; I < TotalComponents; ++I) {
1125381ad6265SDimitry Andric     Expr *AssociatedExpr = Record.readSubExpr();
1125481ad6265SDimitry Andric     auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
1125581ad6265SDimitry Andric     Components.emplace_back(AssociatedExpr, AssociatedDecl,
1125681ad6265SDimitry Andric                             /*IsNonContiguous=*/false);
1125781ad6265SDimitry Andric   }
1125881ad6265SDimitry Andric   C->setComponents(Components, ListSizes);
1125981ad6265SDimitry Andric }
1126081ad6265SDimitry Andric 
11261480093f4SDimitry Andric void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
11262480093f4SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11263480093f4SDimitry Andric   unsigned NumVars = C->varlist_size();
11264480093f4SDimitry Andric   SmallVector<Expr *, 16> Vars;
11265480093f4SDimitry Andric   Vars.reserve(NumVars);
11266480093f4SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
11267480093f4SDimitry Andric     Vars.push_back(Record.readSubExpr());
11268480093f4SDimitry Andric   C->setVarRefs(Vars);
11269480093f4SDimitry Andric   Vars.clear();
11270480093f4SDimitry Andric   Vars.reserve(NumVars);
11271480093f4SDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
11272480093f4SDimitry Andric     Vars.push_back(Record.readSubExpr());
11273480093f4SDimitry Andric   C->setPrivateRefs(Vars);
11274480093f4SDimitry Andric }
112755ffd83dbSDimitry Andric 
112765ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
112775ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
112785ffd83dbSDimitry Andric   unsigned NumVars = C->varlist_size();
112795ffd83dbSDimitry Andric   SmallVector<Expr *, 16> Vars;
112805ffd83dbSDimitry Andric   Vars.reserve(NumVars);
112815ffd83dbSDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
112825ffd83dbSDimitry Andric     Vars.push_back(Record.readSubExpr());
112835ffd83dbSDimitry Andric   C->setVarRefs(Vars);
112845ffd83dbSDimitry Andric }
112855ffd83dbSDimitry Andric 
112865ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
112875ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
112885ffd83dbSDimitry Andric   unsigned NumVars = C->varlist_size();
112895ffd83dbSDimitry Andric   SmallVector<Expr *, 16> Vars;
112905ffd83dbSDimitry Andric   Vars.reserve(NumVars);
112915ffd83dbSDimitry Andric   for (unsigned i = 0; i != NumVars; ++i)
112925ffd83dbSDimitry Andric     Vars.push_back(Record.readSubExpr());
112935ffd83dbSDimitry Andric   C->setVarRefs(Vars);
112945ffd83dbSDimitry Andric }
112955ffd83dbSDimitry Andric 
112965ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
112975ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
112985ffd83dbSDimitry Andric   unsigned NumOfAllocators = C->getNumberOfAllocators();
112995ffd83dbSDimitry Andric   SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
113005ffd83dbSDimitry Andric   Data.reserve(NumOfAllocators);
113015ffd83dbSDimitry Andric   for (unsigned I = 0; I != NumOfAllocators; ++I) {
113025ffd83dbSDimitry Andric     OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
113035ffd83dbSDimitry Andric     D.Allocator = Record.readSubExpr();
113045ffd83dbSDimitry Andric     D.AllocatorTraits = Record.readSubExpr();
113055ffd83dbSDimitry Andric     D.LParenLoc = Record.readSourceLocation();
113065ffd83dbSDimitry Andric     D.RParenLoc = Record.readSourceLocation();
113075ffd83dbSDimitry Andric   }
113085ffd83dbSDimitry Andric   C->setAllocatorsData(Data);
113095ffd83dbSDimitry Andric }
113105ffd83dbSDimitry Andric 
113115ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
113125ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
113135ffd83dbSDimitry Andric   C->setModifier(Record.readSubExpr());
113145ffd83dbSDimitry Andric   C->setColonLoc(Record.readSourceLocation());
113155ffd83dbSDimitry Andric   unsigned NumOfLocators = C->varlist_size();
113165ffd83dbSDimitry Andric   SmallVector<Expr *, 4> Locators;
113175ffd83dbSDimitry Andric   Locators.reserve(NumOfLocators);
113185ffd83dbSDimitry Andric   for (unsigned I = 0; I != NumOfLocators; ++I)
113195ffd83dbSDimitry Andric     Locators.push_back(Record.readSubExpr());
113205ffd83dbSDimitry Andric   C->setVarRefs(Locators);
113215ffd83dbSDimitry Andric }
113225ffd83dbSDimitry Andric 
113235ffd83dbSDimitry Andric void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
113245ffd83dbSDimitry Andric   C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
11325*bdd1243dSDimitry Andric   C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
113265ffd83dbSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
113275ffd83dbSDimitry Andric   C->setKindKwLoc(Record.readSourceLocation());
11328*bdd1243dSDimitry Andric   C->setModifierKwLoc(Record.readSourceLocation());
113295ffd83dbSDimitry Andric }
113305ffd83dbSDimitry Andric 
11331fe6060f1SDimitry Andric void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
11332fe6060f1SDimitry Andric   VisitOMPClauseWithPreInit(C);
11333fe6060f1SDimitry Andric   C->setThreadID(Record.readSubExpr());
11334fe6060f1SDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11335fe6060f1SDimitry Andric }
11336fe6060f1SDimitry Andric 
11337349cc55cSDimitry Andric void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
11338349cc55cSDimitry Andric   C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
11339349cc55cSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11340349cc55cSDimitry Andric   C->setBindKindLoc(Record.readSourceLocation());
11341349cc55cSDimitry Andric }
11342349cc55cSDimitry Andric 
11343349cc55cSDimitry Andric void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
11344349cc55cSDimitry Andric   C->setAlignment(Record.readExpr());
11345349cc55cSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11346349cc55cSDimitry Andric }
11347349cc55cSDimitry Andric 
11348*bdd1243dSDimitry Andric void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
11349*bdd1243dSDimitry Andric   VisitOMPClauseWithPreInit(C);
11350*bdd1243dSDimitry Andric   C->setSize(Record.readSubExpr());
11351*bdd1243dSDimitry Andric   C->setLParenLoc(Record.readSourceLocation());
11352*bdd1243dSDimitry Andric }
11353*bdd1243dSDimitry Andric 
113545ffd83dbSDimitry Andric OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
113555ffd83dbSDimitry Andric   OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
113565ffd83dbSDimitry Andric   TI.Sets.resize(readUInt32());
113575ffd83dbSDimitry Andric   for (auto &Set : TI.Sets) {
113585ffd83dbSDimitry Andric     Set.Kind = readEnum<llvm::omp::TraitSet>();
113595ffd83dbSDimitry Andric     Set.Selectors.resize(readUInt32());
113605ffd83dbSDimitry Andric     for (auto &Selector : Set.Selectors) {
113615ffd83dbSDimitry Andric       Selector.Kind = readEnum<llvm::omp::TraitSelector>();
113625ffd83dbSDimitry Andric       Selector.ScoreOrCondition = nullptr;
113635ffd83dbSDimitry Andric       if (readBool())
113645ffd83dbSDimitry Andric         Selector.ScoreOrCondition = readExprRef();
113655ffd83dbSDimitry Andric       Selector.Properties.resize(readUInt32());
113665ffd83dbSDimitry Andric       for (auto &Property : Selector.Properties)
113675ffd83dbSDimitry Andric         Property.Kind = readEnum<llvm::omp::TraitProperty>();
113685ffd83dbSDimitry Andric     }
113695ffd83dbSDimitry Andric   }
113705ffd83dbSDimitry Andric   return &TI;
113715ffd83dbSDimitry Andric }
11372e8d8bef9SDimitry Andric 
11373e8d8bef9SDimitry Andric void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
11374e8d8bef9SDimitry Andric   if (!Data)
11375e8d8bef9SDimitry Andric     return;
11376e8d8bef9SDimitry Andric   if (Reader->ReadingKind == ASTReader::Read_Stmt) {
11377e8d8bef9SDimitry Andric     // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
11378e8d8bef9SDimitry Andric     skipInts(3);
11379e8d8bef9SDimitry Andric   }
11380e8d8bef9SDimitry Andric   SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
11381e8d8bef9SDimitry Andric   for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
11382e8d8bef9SDimitry Andric     Clauses[I] = readOMPClause();
11383e8d8bef9SDimitry Andric   Data->setClauses(Clauses);
11384e8d8bef9SDimitry Andric   if (Data->hasAssociatedStmt())
11385e8d8bef9SDimitry Andric     Data->setAssociatedStmt(readStmt());
11386e8d8bef9SDimitry Andric   for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
11387e8d8bef9SDimitry Andric     Data->getChildren()[I] = readStmt();
11388e8d8bef9SDimitry Andric }
11389