blob: 87987064b74745c4dc6a31d76286f9b251d05102 [file] [log] [blame]
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001//===- ASTReader.cpp - AST File Reader ------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Guy Benyei11169dd2012-12-18 14:30:41 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTReader class, which reads AST files.
10//
11//===----------------------------------------------------------------------===//
12
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013#include "clang/Basic/OpenMPKinds.h"
John McCallc2f18312019-12-14 03:01:28 -050014#include "clang/Serialization/ASTRecordReader.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000015#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
John McCalld505e572019-12-13 21:54:44 -050017#include "clang/AST/AbstractTypeReader.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000018#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000020#include "clang/AST/ASTMutationListener.h"
21#include "clang/AST/ASTUnresolvedSet.h"
22#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000023#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000025#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000026#include "clang/AST/DeclGroup.h"
27#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000029#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000032#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000033#include "clang/AST/NestedNameSpecifier.h"
John McCallc2f18312019-12-14 03:01:28 -050034#include "clang/AST/OpenMPClause.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000035#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000036#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000037#include "clang/AST/TemplateBase.h"
38#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000039#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000040#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000042#include "clang/AST/UnresolvedSet.h"
43#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000044#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000045#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000049#include "clang/Basic/IdentifierTable.h"
50#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000051#include "clang/Basic/LangOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000052#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000053#include "clang/Basic/ObjCRuntime.h"
54#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000055#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000057#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include "clang/Basic/SourceManager.h"
59#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Basic/TargetInfo.h"
62#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000063#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000064#include "clang/Basic/Version.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000065#include "clang/Lex/HeaderSearch.h"
66#include "clang/Lex/HeaderSearchOptions.h"
67#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000069#include "clang/Lex/PreprocessingRecord.h"
70#include "clang/Lex/Preprocessor.h"
71#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000072#include "clang/Lex/Token.h"
73#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000074#include "clang/Sema/Scope.h"
75#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000076#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000077#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000078#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000079#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000080#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000081#include "clang/Serialization/InMemoryModuleCache.h"
Duncan P. N. Exon Smithf7170d12019-11-21 18:49:05 -080082#include "clang/Serialization/ModuleFile.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000083#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000084#include "clang/Serialization/ModuleManager.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000085#include "clang/Serialization/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000086#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000087#include "llvm/ADT/APFloat.h"
88#include "llvm/ADT/APInt.h"
89#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000090#include "llvm/ADT/ArrayRef.h"
91#include "llvm/ADT/DenseMap.h"
Serge Pavlovc7ff5b32020-03-26 14:51:09 +070092#include "llvm/ADT/FloatingPointMode.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000093#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000094#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000095#include "llvm/ADT/IntrusiveRefCntPtr.h"
96#include "llvm/ADT/None.h"
97#include "llvm/ADT/Optional.h"
98#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000099#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000100#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000101#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000102#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +0000103#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000104#include "llvm/ADT/StringMap.h"
105#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000106#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000107#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000108#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000109#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000110#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000111#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000112#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000113#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000114#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000115#include "llvm/Support/ErrorHandling.h"
116#include "llvm/Support/FileSystem.h"
117#include "llvm/Support/MemoryBuffer.h"
118#include "llvm/Support/Path.h"
119#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000120#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000121#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000122#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000123#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000125#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000127#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000128#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000129#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000130#include <limits>
131#include <map>
132#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000133#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000134#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000135#include <tuple>
136#include <utility>
137#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000138
139using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000140using namespace clang::serialization;
141using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000142using llvm::BitstreamCursor;
Serge Pavlovc7ff5b32020-03-26 14:51:09 +0700143using llvm::RoundingMode;
Guy Benyei11169dd2012-12-18 14:30:41 +0000144
Ben Langmuircb69b572014-03-07 06:40:32 +0000145//===----------------------------------------------------------------------===//
146// ChainedASTReaderListener implementation
147//===----------------------------------------------------------------------===//
148
149bool
150ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
151 return First->ReadFullVersionInformation(FullVersion) ||
152 Second->ReadFullVersionInformation(FullVersion);
153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000154
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000155void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
156 First->ReadModuleName(ModuleName);
157 Second->ReadModuleName(ModuleName);
158}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000159
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000160void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
161 First->ReadModuleMapFile(ModuleMapPath);
162 Second->ReadModuleMapFile(ModuleMapPath);
163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000164
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000165bool
166ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
167 bool Complain,
168 bool AllowCompatibleDifferences) {
169 return First->ReadLanguageOptions(LangOpts, Complain,
170 AllowCompatibleDifferences) ||
171 Second->ReadLanguageOptions(LangOpts, Complain,
172 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000173}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000174
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000175bool ChainedASTReaderListener::ReadTargetOptions(
176 const TargetOptions &TargetOpts, bool Complain,
177 bool AllowCompatibleDifferences) {
178 return First->ReadTargetOptions(TargetOpts, Complain,
179 AllowCompatibleDifferences) ||
180 Second->ReadTargetOptions(TargetOpts, Complain,
181 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000182}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000183
Ben Langmuircb69b572014-03-07 06:40:32 +0000184bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000185 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000186 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
187 Second->ReadDiagnosticOptions(DiagOpts, Complain);
188}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000189
Ben Langmuircb69b572014-03-07 06:40:32 +0000190bool
191ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
192 bool Complain) {
193 return First->ReadFileSystemOptions(FSOpts, Complain) ||
194 Second->ReadFileSystemOptions(FSOpts, Complain);
195}
196
197bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000198 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
199 bool Complain) {
200 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
201 Complain) ||
202 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
203 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000204}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000205
Ben Langmuircb69b572014-03-07 06:40:32 +0000206bool ChainedASTReaderListener::ReadPreprocessorOptions(
207 const PreprocessorOptions &PPOpts, bool Complain,
208 std::string &SuggestedPredefines) {
209 return First->ReadPreprocessorOptions(PPOpts, Complain,
210 SuggestedPredefines) ||
211 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
212}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000213
Ben Langmuircb69b572014-03-07 06:40:32 +0000214void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
215 unsigned Value) {
216 First->ReadCounter(M, Value);
217 Second->ReadCounter(M, Value);
218}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000219
Ben Langmuircb69b572014-03-07 06:40:32 +0000220bool ChainedASTReaderListener::needsInputFileVisitation() {
221 return First->needsInputFileVisitation() ||
222 Second->needsInputFileVisitation();
223}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000224
Ben Langmuircb69b572014-03-07 06:40:32 +0000225bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
226 return First->needsSystemInputFileVisitation() ||
227 Second->needsSystemInputFileVisitation();
228}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000229
Richard Smith216a3bd2015-08-13 17:57:10 +0000230void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
231 ModuleKind Kind) {
232 First->visitModuleFile(Filename, Kind);
233 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000234}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000235
Ben Langmuircb69b572014-03-07 06:40:32 +0000236bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000237 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000238 bool isOverridden,
239 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000240 bool Continue = false;
241 if (First->needsInputFileVisitation() &&
242 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000243 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
244 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000245 if (Second->needsInputFileVisitation() &&
246 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000247 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
248 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000249 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000250}
251
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000252void ChainedASTReaderListener::readModuleFileExtension(
253 const ModuleFileExtensionMetadata &Metadata) {
254 First->readModuleFileExtension(Metadata);
255 Second->readModuleFileExtension(Metadata);
256}
257
Guy Benyei11169dd2012-12-18 14:30:41 +0000258//===----------------------------------------------------------------------===//
259// PCH validator implementation
260//===----------------------------------------------------------------------===//
261
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000262ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000264/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000265/// language options.
266///
267/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000268/// \param AllowCompatibleDifferences If true, differences between compatible
269/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000270///
271/// \returns true if the languagae options mis-match, false otherwise.
272static bool checkLanguageOptions(const LangOptions &LangOpts,
273 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000274 DiagnosticsEngine *Diags,
275 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000276#define LANGOPT(Name, Bits, Default, Description) \
277 if (ExistingLangOpts.Name != LangOpts.Name) { \
278 if (Diags) \
279 Diags->Report(diag::err_pch_langopt_mismatch) \
280 << Description << LangOpts.Name << ExistingLangOpts.Name; \
281 return true; \
282 }
283
284#define VALUE_LANGOPT(Name, Bits, Default, Description) \
285 if (ExistingLangOpts.Name != LangOpts.Name) { \
286 if (Diags) \
287 Diags->Report(diag::err_pch_langopt_value_mismatch) \
288 << Description; \
289 return true; \
290 }
291
292#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
293 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
294 if (Diags) \
295 Diags->Report(diag::err_pch_langopt_value_mismatch) \
296 << Description; \
297 return true; \
298 }
299
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000300#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
301 if (!AllowCompatibleDifferences) \
302 LANGOPT(Name, Bits, Default, Description)
303
304#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
305 if (!AllowCompatibleDifferences) \
306 ENUM_LANGOPT(Name, Bits, Default, Description)
307
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000308#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
309 if (!AllowCompatibleDifferences) \
310 VALUE_LANGOPT(Name, Bits, Default, Description)
311
Guy Benyei11169dd2012-12-18 14:30:41 +0000312#define BENIGN_LANGOPT(Name, Bits, Default, Description)
313#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000314#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000315#include "clang/Basic/LangOptions.def"
316
Ben Langmuircd98cb72015-06-23 18:20:18 +0000317 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
318 if (Diags)
319 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
320 return true;
321 }
322
Guy Benyei11169dd2012-12-18 14:30:41 +0000323 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
324 if (Diags)
325 Diags->Report(diag::err_pch_langopt_value_mismatch)
326 << "target Objective-C runtime";
327 return true;
328 }
329
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000330 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
331 LangOpts.CommentOpts.BlockCommandNames) {
332 if (Diags)
333 Diags->Report(diag::err_pch_langopt_value_mismatch)
334 << "block command names";
335 return true;
336 }
337
Vedant Kumar85a83c22017-06-01 20:01:01 +0000338 // Sanitizer feature mismatches are treated as compatible differences. If
339 // compatible differences aren't allowed, we still only want to check for
340 // mismatches of non-modular sanitizers (the only ones which can affect AST
341 // generation).
342 if (!AllowCompatibleDifferences) {
343 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
344 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
345 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
346 ExistingSanitizers.clear(ModularSanitizers);
347 ImportedSanitizers.clear(ModularSanitizers);
348 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
349 const std::string Flag = "-fsanitize=";
350 if (Diags) {
351#define SANITIZER(NAME, ID) \
352 { \
353 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
354 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
355 if (InExistingModule != InImportedModule) \
356 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
357 << InExistingModule << (Flag + NAME); \
358 }
359#include "clang/Basic/Sanitizers.def"
360 }
361 return true;
362 }
363 }
364
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 return false;
366}
367
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000368/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000369/// target options.
370///
371/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
372///
373/// \returns true if the target options mis-match, false otherwise.
374static bool checkTargetOptions(const TargetOptions &TargetOpts,
375 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000376 DiagnosticsEngine *Diags,
377 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000378#define CHECK_TARGET_OPT(Field, Name) \
379 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
380 if (Diags) \
381 Diags->Report(diag::err_pch_targetopt_mismatch) \
382 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
383 return true; \
384 }
385
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000386 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000387 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000388 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000389
390 // We can tolerate different CPUs in many cases, notably when one CPU
391 // supports a strict superset of another. When allowing compatible
392 // differences skip this check.
393 if (!AllowCompatibleDifferences)
394 CHECK_TARGET_OPT(CPU, "target CPU");
395
Guy Benyei11169dd2012-12-18 14:30:41 +0000396#undef CHECK_TARGET_OPT
397
398 // Compare feature sets.
399 SmallVector<StringRef, 4> ExistingFeatures(
400 ExistingTargetOpts.FeaturesAsWritten.begin(),
401 ExistingTargetOpts.FeaturesAsWritten.end());
402 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
403 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000404 llvm::sort(ExistingFeatures);
405 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000406
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000407 // We compute the set difference in both directions explicitly so that we can
408 // diagnose the differences differently.
409 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
410 std::set_difference(
411 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
412 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
413 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
414 ExistingFeatures.begin(), ExistingFeatures.end(),
415 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000417 // If we are allowing compatible differences and the read feature set is
418 // a strict subset of the existing feature set, there is nothing to diagnose.
419 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
420 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000421
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000422 if (Diags) {
423 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000425 << /* is-existing-feature */ false << Feature;
426 for (StringRef Feature : UnmatchedExistingFeatures)
427 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
428 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000429 }
430
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000431 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000432}
433
434bool
435PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000436 bool Complain,
437 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000438 const LangOptions &ExistingLangOpts = PP.getLangOpts();
439 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000440 Complain ? &Reader.Diags : nullptr,
441 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000442}
443
444bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000445 bool Complain,
446 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000447 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
448 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000449 Complain ? &Reader.Diags : nullptr,
450 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000451}
452
453namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000454
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000455using MacroDefinitionsMap =
456 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
457using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000458
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000459} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000460
Ben Langmuirb92de022014-04-29 16:25:26 +0000461static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
462 DiagnosticsEngine &Diags,
463 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000464 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000465
466 // Check current mappings for new -Werror mappings, and the stored mappings
467 // for cases that were explicitly mapped to *not* be errors that are now
468 // errors because of options like -Werror.
469 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
470
Vedant Kumar48b4f762018-04-14 01:40:48 +0000471 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000472 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
473 diag::kind DiagID = DiagIDMappingPair.first;
474 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
475 if (CurLevel < DiagnosticsEngine::Error)
476 continue; // not significant
477 Level StoredLevel =
478 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
479 if (StoredLevel < DiagnosticsEngine::Error) {
480 if (Complain)
481 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
482 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
483 return true;
484 }
485 }
486 }
487
488 return false;
489}
490
Alp Tokerac4e8e52014-06-22 21:58:33 +0000491static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
492 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
493 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
494 return true;
495 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000496}
497
498static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
499 DiagnosticsEngine &Diags,
500 bool IsSystem, bool Complain) {
501 // Top-level options
502 if (IsSystem) {
503 if (Diags.getSuppressSystemWarnings())
504 return false;
505 // If -Wsystem-headers was not enabled before, be conservative
506 if (StoredDiags.getSuppressSystemWarnings()) {
507 if (Complain)
508 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
509 return true;
510 }
511 }
512
513 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
514 if (Complain)
515 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
516 return true;
517 }
518
519 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
520 !StoredDiags.getEnableAllWarnings()) {
521 if (Complain)
522 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
523 return true;
524 }
525
526 if (isExtHandlingFromDiagsError(Diags) &&
527 !isExtHandlingFromDiagsError(StoredDiags)) {
528 if (Complain)
529 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
530 return true;
531 }
532
533 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
534}
535
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000536/// Return the top import module if it is implicit, nullptr otherwise.
537static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
538 Preprocessor &PP) {
539 // If the original import came from a file explicitly generated by the user,
540 // don't check the diagnostic mappings.
541 // FIXME: currently this is approximated by checking whether this is not a
542 // module import of an implicitly-loaded module file.
543 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
544 // the transitive closure of its imports, since unrelated modules cannot be
545 // imported until after this module finishes validation.
546 ModuleFile *TopImport = &*ModuleMgr.rbegin();
547 while (!TopImport->ImportedBy.empty())
548 TopImport = TopImport->ImportedBy[0];
549 if (TopImport->Kind != MK_ImplicitModule)
550 return nullptr;
551
552 StringRef ModuleName = TopImport->ModuleName;
553 assert(!ModuleName.empty() && "diagnostic options read before module name");
554
555 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
556 assert(M && "missing module");
557 return M;
558}
559
Ben Langmuirb92de022014-04-29 16:25:26 +0000560bool PCHValidator::ReadDiagnosticOptions(
561 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
562 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
563 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
564 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000565 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000566 // This should never fail, because we would have processed these options
567 // before writing them to an ASTFile.
568 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
569
570 ModuleManager &ModuleMgr = Reader.getModuleManager();
571 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
572
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000573 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
574 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000575 return false;
576
Ben Langmuirb92de022014-04-29 16:25:26 +0000577 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
578 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000579 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
580 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000581}
582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000583/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000584/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000585static void
586collectMacroDefinitions(const PreprocessorOptions &PPOpts,
587 MacroDefinitionsMap &Macros,
588 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000589 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
590 StringRef Macro = PPOpts.Macros[I].first;
591 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000592
593 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
594 StringRef MacroName = MacroPair.first;
595 StringRef MacroBody = MacroPair.second;
596
597 // For an #undef'd macro, we only care about the name.
598 if (IsUndef) {
599 if (MacroNames && !Macros.count(MacroName))
600 MacroNames->push_back(MacroName);
601
602 Macros[MacroName] = std::make_pair("", true);
603 continue;
604 }
605
606 // For a #define'd macro, figure out the actual definition.
607 if (MacroName.size() == Macro.size())
608 MacroBody = "1";
609 else {
610 // Note: GCC drops anything following an end-of-line character.
611 StringRef::size_type End = MacroBody.find_first_of("\n\r");
612 MacroBody = MacroBody.substr(0, End);
613 }
614
615 if (MacroNames && !Macros.count(MacroName))
616 MacroNames->push_back(MacroName);
617 Macros[MacroName] = std::make_pair(MacroBody, false);
618 }
619}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000622/// against the preprocessor options in an existing preprocessor.
623///
624/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000625/// \param Validate If true, validate preprocessor options. If false, allow
626/// macros defined by \p ExistingPPOpts to override those defined by
627/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000628static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
629 const PreprocessorOptions &ExistingPPOpts,
630 DiagnosticsEngine *Diags,
631 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000632 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000633 const LangOptions &LangOpts,
634 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000635 // Check macro definitions.
636 MacroDefinitionsMap ASTFileMacros;
637 collectMacroDefinitions(PPOpts, ASTFileMacros);
638 MacroDefinitionsMap ExistingMacros;
639 SmallVector<StringRef, 4> ExistingMacroNames;
640 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
641
Vedant Kumar48b4f762018-04-14 01:40:48 +0000642 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000643 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000644 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
646
647 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000648 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
649 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000650 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 // FIXME: Check whether this identifier was referenced anywhere in the
652 // AST file. If so, we should reject the AST file. Unfortunately, this
653 // information isn't in the control block. What shall we do about it?
654
655 if (Existing.second) {
656 SuggestedPredefines += "#undef ";
657 SuggestedPredefines += MacroName.str();
658 SuggestedPredefines += '\n';
659 } else {
660 SuggestedPredefines += "#define ";
661 SuggestedPredefines += MacroName.str();
662 SuggestedPredefines += ' ';
663 SuggestedPredefines += Existing.first.str();
664 SuggestedPredefines += '\n';
665 }
666 continue;
667 }
668
669 // If the macro was defined in one but undef'd in the other, we have a
670 // conflict.
671 if (Existing.second != Known->second.second) {
672 if (Diags) {
673 Diags->Report(diag::err_pch_macro_def_undef)
674 << MacroName << Known->second.second;
675 }
676 return true;
677 }
678
679 // If the macro was #undef'd in both, or if the macro bodies are identical,
680 // it's fine.
681 if (Existing.second || Existing.first == Known->second.first)
682 continue;
683
684 // The macro bodies differ; complain.
685 if (Diags) {
686 Diags->Report(diag::err_pch_macro_def_conflict)
687 << MacroName << Known->second.first << Existing.first;
688 }
689 return true;
690 }
691
692 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000693 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000694 if (Diags) {
695 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
696 }
697 return true;
698 }
699
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000700 // Detailed record is important since it is used for the module cache hash.
701 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000702 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000703 if (Diags) {
704 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
705 }
706 return true;
707 }
708
Guy Benyei11169dd2012-12-18 14:30:41 +0000709 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000710 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
711 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000712
713 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
714 !ExistingPPOpts.PCHThroughHeader.empty()) {
715 // In case the through header is an include, we must add all the includes
716 // to the predefines so the start point can be determined.
717 SuggestedPredefines += "#include \"";
718 SuggestedPredefines += File;
719 SuggestedPredefines += "\"\n";
720 continue;
721 }
722
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 if (File == ExistingPPOpts.ImplicitPCHInclude)
724 continue;
725
726 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
727 != PPOpts.Includes.end())
728 continue;
729
730 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000731 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 SuggestedPredefines += "\"\n";
733 }
734
Vedant Kumar48b4f762018-04-14 01:40:48 +0000735 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
736 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000737 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
738 File)
739 != PPOpts.MacroIncludes.end())
740 continue;
741
742 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000743 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 SuggestedPredefines += "\"\n##\n";
745 }
746
747 return false;
748}
749
750bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
751 bool Complain,
752 std::string &SuggestedPredefines) {
753 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
754
755 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000756 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000758 SuggestedPredefines,
759 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000760}
761
Yaxun Liu43712e02016-09-07 18:40:20 +0000762bool SimpleASTReaderListener::ReadPreprocessorOptions(
763 const PreprocessorOptions &PPOpts,
764 bool Complain,
765 std::string &SuggestedPredefines) {
766 return checkPreprocessorOptions(PPOpts,
767 PP.getPreprocessorOpts(),
768 nullptr,
769 PP.getFileManager(),
770 SuggestedPredefines,
771 PP.getLangOpts(),
772 false);
773}
774
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000775/// Check the header search options deserialized from the control block
776/// against the header search options in an existing preprocessor.
777///
778/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
779static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
780 StringRef SpecificModuleCachePath,
781 StringRef ExistingModuleCachePath,
782 DiagnosticsEngine *Diags,
783 const LangOptions &LangOpts) {
784 if (LangOpts.Modules) {
785 if (SpecificModuleCachePath != ExistingModuleCachePath) {
786 if (Diags)
787 Diags->Report(diag::err_pch_modulecache_mismatch)
788 << SpecificModuleCachePath << ExistingModuleCachePath;
789 return true;
790 }
791 }
792
793 return false;
794}
795
796bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
797 StringRef SpecificModuleCachePath,
798 bool Complain) {
799 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
800 PP.getHeaderSearchInfo().getModuleCachePath(),
801 Complain ? &Reader.Diags : nullptr,
802 PP.getLangOpts());
803}
804
Guy Benyei11169dd2012-12-18 14:30:41 +0000805void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
806 PP.setCounterValue(Value);
807}
808
809//===----------------------------------------------------------------------===//
810// AST reader implementation
811//===----------------------------------------------------------------------===//
812
Nico Weber824285e2014-05-08 04:26:47 +0000813void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
814 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000815 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000816 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000817}
818
Guy Benyei11169dd2012-12-18 14:30:41 +0000819unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
820 return serialization::ComputeHash(Sel);
821}
822
Guy Benyei11169dd2012-12-18 14:30:41 +0000823std::pair<unsigned, unsigned>
824ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000826
Justin Bogner57ba0b22014-03-28 22:03:24 +0000827 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
828 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000829 return std::make_pair(KeyLen, DataLen);
830}
831
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000832ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000833ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000834 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000835
Guy Benyei11169dd2012-12-18 14:30:41 +0000836 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000837 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
838 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
839 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 if (N == 0)
841 return SelTable.getNullarySelector(FirstII);
842 else if (N == 1)
843 return SelTable.getUnarySelector(FirstII);
844
845 SmallVector<IdentifierInfo *, 16> Args;
846 Args.push_back(FirstII);
847 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000848 Args.push_back(Reader.getLocalIdentifier(
849 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000850
851 return SelTable.getSelector(N, Args.data());
852}
853
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000854ASTSelectorLookupTrait::data_type
855ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000856 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000857 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000858
859 data_type Result;
860
Justin Bogner57ba0b22014-03-28 22:03:24 +0000861 Result.ID = Reader.getGlobalSelectorID(
862 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000863 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
864 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
865 Result.InstanceBits = FullInstanceBits & 0x3;
866 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
867 Result.FactoryBits = FullFactoryBits & 0x3;
868 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
869 unsigned NumInstanceMethods = FullInstanceBits >> 3;
870 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000871
872 // Load instance methods
873 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000874 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000875 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000876 Result.Instance.push_back(Method);
877 }
878
879 // Load factory methods
880 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000881 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000882 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 Result.Factory.push_back(Method);
884 }
885
886 return Result;
887}
888
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000890 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000891}
892
893std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000894ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000895 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000896
Justin Bogner57ba0b22014-03-28 22:03:24 +0000897 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
898 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 return std::make_pair(KeyLen, DataLen);
900}
901
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000902ASTIdentifierLookupTraitBase::internal_key_type
903ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000905 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000906}
907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000908/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000909static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
910 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000911 return II.hadMacroDefinition() ||
912 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000913 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000914 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000915 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000916 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000917}
918
Richard Smith76c2f2c2015-07-17 20:09:43 +0000919static bool readBit(unsigned &Bits) {
920 bool Value = Bits & 0x1;
921 Bits >>= 1;
922 return Value;
923}
924
Richard Smith79bf9202015-08-24 03:33:22 +0000925IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
926 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000927
Richard Smith79bf9202015-08-24 03:33:22 +0000928 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
929 return Reader.getGlobalIdentifierID(F, RawID >> 1);
930}
931
Richard Smitheb4b58f62016-02-05 01:40:54 +0000932static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
933 if (!II.isFromAST()) {
934 II.setIsFromAST();
935 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
936 if (isInterestingIdentifier(Reader, II, IsModule))
937 II.setChangedSinceDeserialization();
938 }
939}
940
Guy Benyei11169dd2012-12-18 14:30:41 +0000941IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
942 const unsigned char* d,
943 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000945
Justin Bogner57ba0b22014-03-28 22:03:24 +0000946 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000947 bool IsInteresting = RawID & 0x01;
948
949 // Wipe out the "is interesting" bit.
950 RawID = RawID >> 1;
951
Richard Smith76c2f2c2015-07-17 20:09:43 +0000952 // Build the IdentifierInfo and link the identifier ID with it.
953 IdentifierInfo *II = KnownII;
954 if (!II) {
955 II = &Reader.getIdentifierTable().getOwn(k);
956 KnownII = II;
957 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000958 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000959 Reader.markIdentifierUpToDate(II);
960
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
962 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000963 // For uninteresting identifiers, there's nothing else to do. Just notify
964 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000966 return II;
967 }
968
Justin Bogner57ba0b22014-03-28 22:03:24 +0000969 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
970 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000971 bool CPlusPlusOperatorKeyword = readBit(Bits);
972 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000973 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000974 bool Poisoned = readBit(Bits);
975 bool ExtensionToken = readBit(Bits);
976 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000977
978 assert(Bits == 0 && "Extra bits in the identifier?");
979 DataLen -= 8;
980
Guy Benyei11169dd2012-12-18 14:30:41 +0000981 // Set or check the various bits in the IdentifierInfo structure.
982 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000983 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000984 II->revertTokenIDToIdentifier();
985 if (!F.isModule())
986 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
987 else if (HasRevertedBuiltin && II->getBuiltinID()) {
988 II->revertBuiltin();
989 assert((II->hasRevertedBuiltin() ||
990 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
991 "Incorrect ObjC keyword or builtin ID");
992 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 assert(II->isExtensionToken() == ExtensionToken &&
994 "Incorrect extension token flag");
995 (void)ExtensionToken;
996 if (Poisoned)
997 II->setIsPoisoned(true);
998 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
999 "Incorrect C++ operator keyword flag");
1000 (void)CPlusPlusOperatorKeyword;
1001
1002 // If this identifier is a macro, deserialize the macro
1003 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +00001004 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001005 uint32_t MacroDirectivesOffset =
1006 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001007 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001008
Richard Smithd7329392015-04-21 21:46:32 +00001009 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 }
1011
1012 Reader.SetIdentifierInfo(ID, II);
1013
1014 // Read all of the declarations visible at global scope with this
1015 // name.
1016 if (DataLen > 0) {
1017 SmallVector<uint32_t, 4> DeclIDs;
1018 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001019 DeclIDs.push_back(Reader.getGlobalDeclID(
1020 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1022 }
1023
1024 return II;
1025}
1026
Richard Smitha06c7e62015-08-26 23:55:49 +00001027DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1028 : Kind(Name.getNameKind()) {
1029 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 case DeclarationName::ObjCZeroArgSelector:
1034 case DeclarationName::ObjCOneArgSelector:
1035 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001036 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 break;
1038 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001039 Data = Name.getCXXOverloadedOperator();
1040 break;
1041 case DeclarationName::CXXLiteralOperatorName:
1042 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1043 break;
Richard Smith35845152017-02-07 01:37:30 +00001044 case DeclarationName::CXXDeductionGuideName:
1045 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1046 ->getDeclName().getAsIdentifierInfo();
1047 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001048 case DeclarationName::CXXConstructorName:
1049 case DeclarationName::CXXDestructorName:
1050 case DeclarationName::CXXConversionFunctionName:
1051 case DeclarationName::CXXUsingDirective:
1052 Data = 0;
1053 break;
1054 }
1055}
1056
1057unsigned DeclarationNameKey::getHash() const {
1058 llvm::FoldingSetNodeID ID;
1059 ID.AddInteger(Kind);
1060
1061 switch (Kind) {
1062 case DeclarationName::Identifier:
1063 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001064 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001065 ID.AddString(((IdentifierInfo*)Data)->getName());
1066 break;
1067 case DeclarationName::ObjCZeroArgSelector:
1068 case DeclarationName::ObjCOneArgSelector:
1069 case DeclarationName::ObjCMultiArgSelector:
1070 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1071 break;
1072 case DeclarationName::CXXOperatorName:
1073 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001074 break;
1075 case DeclarationName::CXXConstructorName:
1076 case DeclarationName::CXXDestructorName:
1077 case DeclarationName::CXXConversionFunctionName:
1078 case DeclarationName::CXXUsingDirective:
1079 break;
1080 }
1081
1082 return ID.ComputeHash();
1083}
1084
Richard Smithd88a7f12015-09-01 20:35:42 +00001085ModuleFile *
1086ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1087 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001088
Richard Smithd88a7f12015-09-01 20:35:42 +00001089 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1090 return Reader.getLocalModuleFile(F, ModuleFileID);
1091}
1092
Guy Benyei11169dd2012-12-18 14:30:41 +00001093std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001094ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001095 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001096
Justin Bogner57ba0b22014-03-28 22:03:24 +00001097 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1098 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 return std::make_pair(KeyLen, DataLen);
1100}
1101
Richard Smitha06c7e62015-08-26 23:55:49 +00001102ASTDeclContextNameLookupTrait::internal_key_type
1103ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001104 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001105
Vedant Kumar48b4f762018-04-14 01:40:48 +00001106 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001107 uint64_t Data;
1108 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001110 case DeclarationName::CXXLiteralOperatorName:
1111 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001112 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001113 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001114 break;
1115 case DeclarationName::ObjCZeroArgSelector:
1116 case DeclarationName::ObjCOneArgSelector:
1117 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001118 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001119 (uint64_t)Reader.getLocalSelector(
1120 F, endian::readNext<uint32_t, little, unaligned>(
1121 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 break;
1123 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001124 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001125 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001126 case DeclarationName::CXXConstructorName:
1127 case DeclarationName::CXXDestructorName:
1128 case DeclarationName::CXXConversionFunctionName:
1129 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001130 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 break;
1132 }
1133
Richard Smitha06c7e62015-08-26 23:55:49 +00001134 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001135}
1136
Richard Smithd88a7f12015-09-01 20:35:42 +00001137void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1138 const unsigned char *d,
1139 unsigned DataLen,
1140 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001141 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001142
Richard Smithd88a7f12015-09-01 20:35:42 +00001143 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1144 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1145 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1146 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001147}
1148
Richard Smith0f4e2c42015-08-06 04:23:48 +00001149bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1150 BitstreamCursor &Cursor,
1151 uint64_t Offset,
1152 DeclContext *DC) {
1153 assert(Offset != 0);
1154
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001156 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1157 Error(std::move(Err));
1158 return true;
1159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001160
Richard Smith0f4e2c42015-08-06 04:23:48 +00001161 RecordData Record;
1162 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001163 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1164 if (!MaybeCode) {
1165 Error(MaybeCode.takeError());
1166 return true;
1167 }
1168 unsigned Code = MaybeCode.get();
1169
1170 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1171 if (!MaybeRecCode) {
1172 Error(MaybeRecCode.takeError());
1173 return true;
1174 }
1175 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001176 if (RecCode != DECL_CONTEXT_LEXICAL) {
1177 Error("Expected lexical block");
1178 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 }
1180
Richard Smith82f8fcd2015-08-06 22:07:25 +00001181 assert(!isa<TranslationUnitDecl>(DC) &&
1182 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001183 // If we are handling a C++ class template instantiation, we can see multiple
1184 // lexical updates for the same record. It's important that we select only one
1185 // of them, so that field numbering works properly. Just pick the first one we
1186 // see.
1187 auto &Lex = LexicalDecls[DC];
1188 if (!Lex.first) {
1189 Lex = std::make_pair(
1190 &M, llvm::makeArrayRef(
1191 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1192 Blob.data()),
1193 Blob.size() / 4));
1194 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001195 DC->setHasExternalLexicalStorage(true);
1196 return false;
1197}
Guy Benyei11169dd2012-12-18 14:30:41 +00001198
Richard Smith0f4e2c42015-08-06 04:23:48 +00001199bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1200 BitstreamCursor &Cursor,
1201 uint64_t Offset,
1202 DeclID ID) {
1203 assert(Offset != 0);
1204
1205 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001206 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1207 Error(std::move(Err));
1208 return true;
1209 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001210
1211 RecordData Record;
1212 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001213 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1214 if (!MaybeCode) {
1215 Error(MaybeCode.takeError());
1216 return true;
1217 }
1218 unsigned Code = MaybeCode.get();
1219
1220 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1221 if (!MaybeRecCode) {
1222 Error(MaybeRecCode.takeError());
1223 return true;
1224 }
1225 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001226 if (RecCode != DECL_CONTEXT_VISIBLE) {
1227 Error("Expected visible lookup table block");
1228 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001229 }
1230
Richard Smith0f4e2c42015-08-06 04:23:48 +00001231 // We can't safely determine the primary context yet, so delay attaching the
1232 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001233 auto *Data = (const unsigned char*)Blob.data();
1234 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001235 return false;
1236}
1237
Richard Smith37a93df2017-02-18 00:32:02 +00001238void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001240 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001241 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001242 Diag(diag::note_module_cache_path)
1243 << PP.getHeaderSearchInfo().getModuleCachePath();
1244 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001245}
1246
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001247void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1248 StringRef Arg3) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001249 if (Diags.isDiagnosticInFlight())
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001250 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 else
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001252 Diag(DiagID) << Arg1 << Arg2 << Arg3;
Guy Benyei11169dd2012-12-18 14:30:41 +00001253}
1254
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001255void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1256 unsigned Select) const {
1257 if (!Diags.isDiagnosticInFlight())
1258 Diag(DiagID) << Arg1 << Arg2 << Select;
1259}
1260
JF Bastien0e828952019-06-26 19:50:12 +00001261void ASTReader::Error(llvm::Error &&Err) const {
1262 Error(toString(std::move(Err)));
1263}
1264
Guy Benyei11169dd2012-12-18 14:30:41 +00001265//===----------------------------------------------------------------------===//
1266// Source Manager Deserialization
1267//===----------------------------------------------------------------------===//
1268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001269/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001270/// \returns true if there was an error.
1271bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001272 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001273 unsigned Idx = 0;
1274 LineTableInfo &LineTable = SourceMgr.getLineTable();
1275
1276 // Parse the file names
1277 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001278 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001279 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001281 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001282 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1283 }
Richard Smith63078492015-09-01 07:41:55 +00001284 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001285
1286 // Parse the line entries
1287 std::vector<LineEntry> Entries;
1288 while (Idx < Record.size()) {
1289 int FID = Record[Idx++];
1290 assert(FID >= 0 && "Serialized line entries for non-local file.");
1291 // Remap FileID from 1-based old view.
1292 FID += F.SLocEntryBaseID - 1;
1293
1294 // Extract the line entries
1295 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001296 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001297 Entries.clear();
1298 Entries.reserve(NumEntries);
1299 for (unsigned I = 0; I != NumEntries; ++I) {
1300 unsigned FileOffset = Record[Idx++];
1301 unsigned LineNo = Record[Idx++];
1302 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001303 SrcMgr::CharacteristicKind FileKind
1304 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 unsigned IncludeOffset = Record[Idx++];
1306 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1307 FileKind, IncludeOffset));
1308 }
1309 LineTable.AddEntry(FileID::get(FID), Entries);
1310 }
1311
1312 return false;
1313}
1314
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001315/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001316bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1317 using namespace SrcMgr;
1318
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001319 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001320
1321 // Set the source-location entry cursor to the current position in
1322 // the stream. This cursor will be used to read the contents of the
1323 // source manager block initially, and then lazily read
1324 // source-location entries as needed.
1325 SLocEntryCursor = F.Stream;
1326
1327 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001328 if (llvm::Error Err = F.Stream.SkipBlock()) {
1329 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 return true;
1331 }
1332
1333 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001334 if (llvm::Error Err =
1335 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1336 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 return true;
1338 }
1339
1340 RecordData Record;
1341 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001342 Expected<llvm::BitstreamEntry> MaybeE =
1343 SLocEntryCursor.advanceSkippingSubblocks();
1344 if (!MaybeE) {
1345 Error(MaybeE.takeError());
1346 return true;
1347 }
1348 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001349
Chris Lattnere7b154b2013-01-19 21:39:22 +00001350 switch (E.Kind) {
1351 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1352 case llvm::BitstreamEntry::Error:
1353 Error("malformed block record in AST file");
1354 return true;
1355 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001356 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001357 case llvm::BitstreamEntry::Record:
1358 // The interesting case.
1359 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001363 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001364 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001365 Expected<unsigned> MaybeRecord =
1366 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1367 if (!MaybeRecord) {
1368 Error(MaybeRecord.takeError());
1369 return true;
1370 }
1371 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001372 default: // Default behavior: ignore.
1373 break;
1374
1375 case SM_SLOC_FILE_ENTRY:
1376 case SM_SLOC_BUFFER_ENTRY:
1377 case SM_SLOC_EXPANSION_ENTRY:
1378 // Once we hit one of the source location entries, we're done.
1379 return false;
1380 }
1381 }
1382}
1383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001384/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001385/// and the PCH file was moved from its original location, try to resolve the
1386/// file by assuming that header+PCH were moved together and the header is in
1387/// the same place relative to the PCH.
1388static std::string
1389resolveFileRelativeToOriginalDir(const std::string &Filename,
1390 const std::string &OriginalDir,
1391 const std::string &CurrDir) {
1392 assert(OriginalDir != CurrDir &&
1393 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001394
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001396
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 SmallString<128> filePath(Filename);
1398 fs::make_absolute(filePath);
1399 assert(path::is_absolute(OriginalDir));
1400 SmallString<128> currPCHPath(CurrDir);
1401
1402 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1403 fileDirE = path::end(path::parent_path(filePath));
1404 path::const_iterator origDirI = path::begin(OriginalDir),
1405 origDirE = path::end(OriginalDir);
1406 // Skip the common path components from filePath and OriginalDir.
1407 while (fileDirI != fileDirE && origDirI != origDirE &&
1408 *fileDirI == *origDirI) {
1409 ++fileDirI;
1410 ++origDirI;
1411 }
1412 for (; origDirI != origDirE; ++origDirI)
1413 path::append(currPCHPath, "..");
1414 path::append(currPCHPath, fileDirI, fileDirE);
1415 path::append(currPCHPath, path::filename(Filename));
Benjamin Krameradcd0262020-01-28 20:23:46 +01001416 return std::string(currPCHPath.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001417}
1418
1419bool ASTReader::ReadSLocEntry(int ID) {
1420 if (ID == 0)
1421 return false;
1422
1423 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1424 Error("source location entry ID out-of-range for AST file");
1425 return true;
1426 }
1427
Richard Smithaada85c2016-02-06 02:06:43 +00001428 // Local helper to read the (possibly-compressed) buffer data following the
1429 // entry record.
1430 auto ReadBuffer = [this](
1431 BitstreamCursor &SLocEntryCursor,
1432 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1433 RecordData Record;
1434 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001435 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1436 if (!MaybeCode) {
1437 Error(MaybeCode.takeError());
1438 return nullptr;
1439 }
1440 unsigned Code = MaybeCode.get();
1441
1442 Expected<unsigned> MaybeRecCode =
1443 SLocEntryCursor.readRecord(Code, Record, &Blob);
1444 if (!MaybeRecCode) {
1445 Error(MaybeRecCode.takeError());
1446 return nullptr;
1447 }
1448 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001449
1450 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001451 if (!llvm::zlib::isAvailable()) {
1452 Error("zlib is not available");
1453 return nullptr;
1454 }
Richard Smithaada85c2016-02-06 02:06:43 +00001455 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001456 if (llvm::Error E =
1457 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1458 Error("could not decompress embedded file contents: " +
1459 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001460 return nullptr;
1461 }
1462 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1463 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1464 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1465 } else {
1466 Error("AST record has invalid code");
1467 return nullptr;
1468 }
1469 };
1470
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001472 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
Dmitry Polukhina7afb212020-04-16 09:24:46 -07001473 F->SLocEntryOffsetsBase +
JF Bastien0e828952019-06-26 19:50:12 +00001474 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1475 Error(std::move(Err));
1476 return true;
1477 }
1478
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001479 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 unsigned BaseOffset = F->SLocEntryBaseOffset;
1481
1482 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001483 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1484 if (!MaybeEntry) {
1485 Error(MaybeEntry.takeError());
1486 return true;
1487 }
1488 llvm::BitstreamEntry Entry = MaybeEntry.get();
1489
Chris Lattnere7b154b2013-01-19 21:39:22 +00001490 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001491 Error("incorrectly-formatted source location entry in AST file");
1492 return true;
1493 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001494
Guy Benyei11169dd2012-12-18 14:30:41 +00001495 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001496 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001497 Expected<unsigned> MaybeSLOC =
1498 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1499 if (!MaybeSLOC) {
1500 Error(MaybeSLOC.takeError());
1501 return true;
1502 }
1503 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001504 default:
1505 Error("incorrectly-formatted source location entry in AST file");
1506 return true;
1507
1508 case SM_SLOC_FILE_ENTRY: {
1509 // We will detect whether a file changed and return 'Failure' for it, but
1510 // we will also try to fail gracefully by setting up the SLocEntry.
1511 unsigned InputID = Record[4];
1512 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001513 const FileEntry *File = IF.getFile();
1514 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001515
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001516 // Note that we only check if a File was returned. If it was out-of-date
1517 // we have complained but we will continue creating a FileID to recover
1518 // gracefully.
1519 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 return true;
1521
1522 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1523 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1524 // This is the module's main file.
1525 IncludeLoc = getImportLocation(F);
1526 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001527 SrcMgr::CharacteristicKind
1528 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001529 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001530 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1531 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001532 SrcMgr::FileInfo &FileInfo =
1533 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 FileInfo.NumCreatedFIDs = Record[5];
1535 if (Record[3])
1536 FileInfo.setHasLineDirectives();
1537
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001539 if (NumFileDecls && ContextObj) {
Roman Lebedevbf4f1e02019-10-10 12:22:42 +00001540 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1542 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1543 NumFileDecls));
1544 }
Richard Smithaada85c2016-02-06 02:06:43 +00001545
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001547 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001549 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1550 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001551 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1552 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001554 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 }
1556
1557 break;
1558 }
1559
1560 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001561 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001563 SrcMgr::CharacteristicKind
1564 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001566 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001567 IncludeLoc = getImportLocation(F);
1568 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001569
Richard Smithaada85c2016-02-06 02:06:43 +00001570 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1571 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001573 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001574 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 break;
1576 }
1577
1578 case SM_SLOC_EXPANSION_ENTRY: {
1579 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1580 SourceMgr.createExpansionLoc(SpellingLoc,
1581 ReadSourceLocation(*F, Record[2]),
1582 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001583 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001584 Record[4],
1585 ID,
1586 BaseOffset + Record[0]);
1587 break;
1588 }
1589 }
1590
1591 return false;
1592}
1593
1594std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1595 if (ID == 0)
1596 return std::make_pair(SourceLocation(), "");
1597
1598 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1599 Error("source location entry ID out-of-range for AST file");
1600 return std::make_pair(SourceLocation(), "");
1601 }
1602
1603 // Find which module file this entry lands in.
1604 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001605 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 return std::make_pair(SourceLocation(), "");
1607
1608 // FIXME: Can we map this down to a particular submodule? That would be
1609 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001610 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001611}
1612
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001613/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001614SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1615 if (F->ImportLoc.isValid())
1616 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001617
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 // Otherwise we have a PCH. It's considered to be "imported" at the first
1619 // location of its includer.
1620 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001621 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001622 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001623 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001625 return F->ImportedBy[0]->FirstLoc;
1626}
1627
JF Bastien0e828952019-06-26 19:50:12 +00001628/// Enter a subblock of the specified BlockID with the specified cursor. Read
1629/// the abbreviations that are at the top of the block and then leave the cursor
1630/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001631bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001632 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1633 // FIXME this drops errors on the floor.
1634 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001635 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001636 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001637
1638 while (true) {
1639 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001640 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1641 if (!MaybeCode) {
1642 // FIXME this drops errors on the floor.
1643 consumeError(MaybeCode.takeError());
1644 return true;
1645 }
1646 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001647
1648 // We expect all abbrevs to be at the start of the block.
1649 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001650 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1651 // FIXME this drops errors on the floor.
1652 consumeError(std::move(Err));
1653 return true;
1654 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 return false;
1656 }
JF Bastien0e828952019-06-26 19:50:12 +00001657 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1658 // FIXME this drops errors on the floor.
1659 consumeError(std::move(Err));
1660 return true;
1661 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001662 }
1663}
1664
Richard Smithe40f2ba2013-08-07 21:41:30 +00001665Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001666 unsigned &Idx) {
1667 Token Tok;
1668 Tok.startToken();
1669 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1670 Tok.setLength(Record[Idx++]);
1671 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1672 Tok.setIdentifierInfo(II);
1673 Tok.setKind((tok::TokenKind)Record[Idx++]);
1674 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1675 return Tok;
1676}
1677
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001678MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001679 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001680
1681 // Keep track of where we are in the stream, then jump back there
1682 // after reading this macro.
1683 SavedStreamPosition SavedPosition(Stream);
1684
JF Bastien0e828952019-06-26 19:50:12 +00001685 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1686 // FIXME this drops errors on the floor.
1687 consumeError(std::move(Err));
1688 return nullptr;
1689 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001691 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001692 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001693
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001695 // Advance to the next record, but if we get to the end of the block, don't
1696 // pop it (removing all the abbreviations from the cursor) since we want to
1697 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001698 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001699 Expected<llvm::BitstreamEntry> MaybeEntry =
1700 Stream.advanceSkippingSubblocks(Flags);
1701 if (!MaybeEntry) {
1702 Error(MaybeEntry.takeError());
1703 return Macro;
1704 }
1705 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001706
Chris Lattnerefa77172013-01-20 00:00:22 +00001707 switch (Entry.Kind) {
1708 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1709 case llvm::BitstreamEntry::Error:
1710 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001711 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001712 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001713 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001714 case llvm::BitstreamEntry::Record:
1715 // The interesting case.
1716 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001717 }
1718
1719 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001721 PreprocessorRecordTypes RecType;
1722 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1723 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1724 else {
1725 Error(MaybeRecType.takeError());
1726 return Macro;
1727 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001728 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001729 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001730 case PP_MACRO_DIRECTIVE_HISTORY:
1731 return Macro;
1732
Guy Benyei11169dd2012-12-18 14:30:41 +00001733 case PP_MACRO_OBJECT_LIKE:
1734 case PP_MACRO_FUNCTION_LIKE: {
1735 // If we already have a macro, that means that we've hit the end
1736 // of the definition of the macro we were looking for. We're
1737 // done.
1738 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001739 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001740
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001741 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001743 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001744 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001745 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001746 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001747
Guy Benyei11169dd2012-12-18 14:30:41 +00001748 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1749 // Decode function-like macro info.
1750 bool isC99VarArgs = Record[NextIndex++];
1751 bool isGNUVarArgs = Record[NextIndex++];
1752 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001753 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 unsigned NumArgs = Record[NextIndex++];
1755 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001756 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001757
1758 // Install function-like macro info.
1759 MI->setIsFunctionLike();
1760 if (isC99VarArgs) MI->setIsC99Varargs();
1761 if (isGNUVarArgs) MI->setIsGNUVarargs();
1762 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001763 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 }
1765
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 // Remember that we saw this macro last so that we add the tokens that
1767 // form its body to it.
1768 Macro = MI;
1769
1770 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1771 Record[NextIndex]) {
1772 // We have a macro definition. Register the association
1773 PreprocessedEntityID
1774 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1775 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001776 PreprocessingRecord::PPEntityID PPID =
1777 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001778 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001779 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001780 if (PPDef)
1781 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001782 }
1783
1784 ++NumMacrosRead;
1785 break;
1786 }
1787
1788 case PP_TOKEN: {
1789 // If we see a TOKEN before a PP_MACRO_*, then the file is
1790 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001791 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001792
John McCallf413f5e2013-05-03 00:10:13 +00001793 unsigned Idx = 0;
1794 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 Macro->AddTokenToBody(Tok);
1796 break;
1797 }
1798 }
1799 }
1800}
1801
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001802PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001803ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1804 unsigned LocalID) const {
1805 if (!M.ModuleOffsetMap.empty())
1806 ReadModuleOffsetMap(M);
1807
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001808 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001810 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001812
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 return LocalID + I->second;
1814}
1815
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001816unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1817 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001818}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001819
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001820HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001821HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001822 internal_key_type ikey = {FE->getSize(),
1823 M.HasTimestamps ? FE->getModificationTime() : 0,
1824 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001825 return ikey;
1826}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001827
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001828bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001829 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 return false;
1831
Mehdi Amini004b9c72016-10-10 22:52:47 +00001832 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001833 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001834
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001836 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001837 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001838 if (!Key.Imported) {
1839 if (auto File = FileMgr.getFile(Key.Filename))
1840 return *File;
1841 return nullptr;
1842 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001843
Benjamin Krameradcd0262020-01-28 20:23:46 +01001844 std::string Resolved = std::string(Key.Filename);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001845 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001846 if (auto File = FileMgr.getFile(Resolved))
1847 return *File;
1848 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001849 };
1850
1851 const FileEntry *FEA = GetFile(a);
1852 const FileEntry *FEB = GetFile(b);
1853 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001854}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001855
Guy Benyei11169dd2012-12-18 14:30:41 +00001856std::pair<unsigned, unsigned>
1857HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001858 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001859
Vedant Kumar48b4f762018-04-14 01:40:48 +00001860 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1861 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001862 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001863}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001864
1865HeaderFileInfoTrait::internal_key_type
1866HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001867 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001868
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001869 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001870 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1871 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001872 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001873 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001874 return ikey;
1875}
1876
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001877HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001878HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001880 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001881
1882 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001883 HeaderFileInfo HFI;
1884 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001885 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001886 HFI.isImport |= (Flags >> 5) & 0x01;
1887 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1888 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001890 // FIXME: Find a better way to handle this. Maybe just store a
1891 // "has been included" flag?
1892 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1893 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001894 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1895 M, endian::readNext<uint32_t, little, unaligned>(d));
1896 if (unsigned FrameworkOffset =
1897 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001898 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001899 // since 0 is used as an indicator for "no framework name".
1900 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1901 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1902 }
Richard Smith386bb072015-08-18 23:42:23 +00001903
1904 assert((End - d) % 4 == 0 &&
1905 "Wrong data length in HeaderFileInfo deserialization");
1906 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001907 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001908 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1909 LocalSMID >>= 2;
1910
1911 // This header is part of a module. Associate it with the module to enable
1912 // implicit module import.
1913 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1914 Module *Mod = Reader.getSubmodule(GlobalSMID);
1915 FileManager &FileMgr = Reader.getFileManager();
1916 ModuleMap &ModMap =
1917 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1918
Benjamin Krameradcd0262020-01-28 20:23:46 +01001919 std::string Filename = std::string(key.Filename);
Richard Smith386bb072015-08-18 23:42:23 +00001920 if (key.Imported)
1921 Reader.ResolveImportedPath(M, Filename);
1922 // FIXME: This is not always the right filename-as-written, but we're not
1923 // going to use this information to rebuild the module, so it doesn't make
1924 // a lot of difference.
Benjamin Krameradcd0262020-01-28 20:23:46 +01001925 Module::Header H = {std::string(key.Filename), *FileMgr.getFile(Filename)};
Richard Smithd8879c82015-08-24 21:59:32 +00001926 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1927 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001928 }
1929
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 // This HeaderFileInfo was externally loaded.
1931 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001932 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001933 return HFI;
1934}
1935
Dmitry Polukhina7afb212020-04-16 09:24:46 -07001936void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
1937 uint32_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001938 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1939 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001940}
1941
1942void ASTReader::ReadDefinedMacros() {
1943 // Note that we are loading defined macros.
1944 Deserializing Macros(this);
1945
Vedant Kumar48b4f762018-04-14 01:40:48 +00001946 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001947 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001948
1949 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001950 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 continue;
1952
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001953 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001954 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1955 Error(std::move(Err));
1956 return;
1957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001958
1959 RecordData Record;
1960 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001961 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1962 if (!MaybeE) {
1963 Error(MaybeE.takeError());
1964 return;
1965 }
1966 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001967
Chris Lattnere7b154b2013-01-19 21:39:22 +00001968 switch (E.Kind) {
1969 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1970 case llvm::BitstreamEntry::Error:
1971 Error("malformed block record in AST file");
1972 return;
1973 case llvm::BitstreamEntry::EndBlock:
1974 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001975
JF Bastien0e828952019-06-26 19:50:12 +00001976 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001977 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001978 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1979 if (!MaybeRecord) {
1980 Error(MaybeRecord.takeError());
1981 return;
1982 }
1983 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001984 default: // Default behavior: ignore.
1985 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001986
Chris Lattnere7b154b2013-01-19 21:39:22 +00001987 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001988 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001989 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001990 if (II->isOutOfDate())
1991 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001992 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001993 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001994
Chris Lattnere7b154b2013-01-19 21:39:22 +00001995 case PP_TOKEN:
1996 // Ignore tokens.
1997 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001998 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 break;
2000 }
JF Bastien0e828952019-06-26 19:50:12 +00002001 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002003 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00002004 }
2005}
2006
2007namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002008
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002009 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 class IdentifierLookupVisitor {
2011 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002012 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002013 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002014 unsigned &NumIdentifierLookups;
2015 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002016 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002017
Guy Benyei11169dd2012-12-18 14:30:41 +00002018 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002019 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2020 unsigned &NumIdentifierLookups,
2021 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002022 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2023 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002024 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002025 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002026
2027 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002029 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002030 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002031
Vedant Kumar48b4f762018-04-14 01:40:48 +00002032 ASTIdentifierLookupTable *IdTable
2033 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 if (!IdTable)
2035 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002036
2037 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002038 Found);
2039 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002040 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002041 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002042 if (Pos == IdTable->end())
2043 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002044
Guy Benyei11169dd2012-12-18 14:30:41 +00002045 // Dereferencing the iterator has the effect of building the
2046 // IdentifierInfo node and populating it with the various
2047 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002048 ++NumIdentifierLookupHits;
2049 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002050 return true;
2051 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002052
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002053 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002054 // files.
2055 IdentifierInfo *getIdentifierInfo() const { return Found; }
2056 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002057
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002058} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002059
2060void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2061 // Note that we are loading an identifier.
2062 Deserializing AnIdentifier(this);
2063
2064 unsigned PriorGeneration = 0;
2065 if (getContext().getLangOpts().Modules)
2066 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002067
2068 // If there is a global index, look there first to determine which modules
2069 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002070 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002071 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002072 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002073 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2074 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002075 }
2076 }
2077
Douglas Gregor7211ac12013-01-25 23:32:03 +00002078 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002079 NumIdentifierLookups,
2080 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002081 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002082 markIdentifierUpToDate(&II);
2083}
2084
2085void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2086 if (!II)
2087 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002088
Guy Benyei11169dd2012-12-18 14:30:41 +00002089 II->setOutOfDate(false);
2090
2091 // Update the generation for this identifier.
2092 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002093 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002094}
2095
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002096void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2097 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002098 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002099
2100 BitstreamCursor &Cursor = M.MacroCursor;
2101 SavedStreamPosition SavedPosition(Cursor);
Dmitry Polukhina7afb212020-04-16 09:24:46 -07002102 if (llvm::Error Err =
2103 Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
JF Bastien0e828952019-06-26 19:50:12 +00002104 Error(std::move(Err));
2105 return;
2106 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002107
Richard Smith713369b2015-04-23 20:40:50 +00002108 struct ModuleMacroRecord {
2109 SubmoduleID SubModID;
2110 MacroInfo *MI;
2111 SmallVector<SubmoduleID, 8> Overrides;
2112 };
2113 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002114
Richard Smithd7329392015-04-21 21:46:32 +00002115 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2116 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2117 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002118 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002119 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002120 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002121 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002122 if (!MaybeEntry) {
2123 Error(MaybeEntry.takeError());
2124 return;
2125 }
2126 llvm::BitstreamEntry Entry = MaybeEntry.get();
2127
Richard Smithd7329392015-04-21 21:46:32 +00002128 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2129 Error("malformed block record in AST file");
2130 return;
2131 }
2132
2133 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002134 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2135 if (!MaybePP) {
2136 Error(MaybePP.takeError());
2137 return;
2138 }
2139 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002140 case PP_MACRO_DIRECTIVE_HISTORY:
2141 break;
2142
2143 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002144 ModuleMacros.push_back(ModuleMacroRecord());
2145 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002146 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2147 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002148 for (int I = 2, N = Record.size(); I != N; ++I)
2149 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002150 continue;
2151 }
2152
2153 default:
2154 Error("malformed block record in AST file");
2155 return;
2156 }
2157
2158 // We found the macro directive history; that's the last record
2159 // for this macro.
2160 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002161 }
2162
Richard Smithd7329392015-04-21 21:46:32 +00002163 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002164 {
2165 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002166 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002167 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002168 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002169 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002170 Module *Mod = getSubmodule(ModID);
2171 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002172 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002173 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002174 }
2175
2176 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002177 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002178 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002179 }
2180 }
2181
2182 // Don't read the directive history for a module; we don't have anywhere
2183 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002184 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002185 return;
2186
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002187 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002188 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002189 unsigned Idx = 0, N = Record.size();
2190 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002191 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002192 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002193 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002194 switch (K) {
2195 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002196 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002197 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002198 break;
2199 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002200 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002201 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002202 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002203 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002204 bool isPublic = Record[Idx++];
2205 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2206 break;
2207 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002208
2209 if (!Latest)
2210 Latest = MD;
2211 if (Earliest)
2212 Earliest->setPrevious(MD);
2213 Earliest = MD;
2214 }
2215
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002216 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002217 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002218}
2219
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002220ASTReader::InputFileInfo
2221ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002222 // Go find this input file.
2223 BitstreamCursor &Cursor = F.InputFilesCursor;
2224 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002225 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2226 // FIXME this drops errors on the floor.
2227 consumeError(std::move(Err));
2228 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002229
JF Bastien0e828952019-06-26 19:50:12 +00002230 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2231 if (!MaybeCode) {
2232 // FIXME this drops errors on the floor.
2233 consumeError(MaybeCode.takeError());
2234 }
2235 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002236 RecordData Record;
2237 StringRef Blob;
2238
JF Bastien0e828952019-06-26 19:50:12 +00002239 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2240 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2241 "invalid record type for input file");
2242 else {
2243 // FIXME this drops errors on the floor.
2244 consumeError(Maybe.takeError());
2245 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002246
2247 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002248 InputFileInfo R;
2249 R.StoredSize = static_cast<off_t>(Record[1]);
2250 R.StoredTime = static_cast<time_t>(Record[2]);
2251 R.Overridden = static_cast<bool>(Record[3]);
2252 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002253 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002254 R.Filename = std::string(Blob);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002255 ResolveImportedPath(F, R.Filename);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002256
2257 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2258 if (!MaybeEntry) // FIXME this drops errors on the floor.
2259 consumeError(MaybeEntry.takeError());
2260 llvm::BitstreamEntry Entry = MaybeEntry.get();
2261 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2262 "expected record type for input file hash");
2263
2264 Record.clear();
2265 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2266 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2267 "invalid record type for input file hash");
2268 else {
2269 // FIXME this drops errors on the floor.
2270 consumeError(Maybe.takeError());
2271 }
2272 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2273 static_cast<uint64_t>(Record[0]);
Hans Wennborg73945142014-03-14 17:45:06 +00002274 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002275}
2276
Manman Renc8c94152016-10-21 23:35:03 +00002277static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002278InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002279 // If this ID is bogus, just return an empty input file.
2280 if (ID == 0 || ID > F.InputFilesLoaded.size())
2281 return InputFile();
2282
2283 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002284 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 return F.InputFilesLoaded[ID-1];
2286
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002287 if (F.InputFilesLoaded[ID-1].isNotFound())
2288 return InputFile();
2289
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002291 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002293 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2294 // FIXME this drops errors on the floor.
2295 consumeError(std::move(Err));
2296 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002297
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002298 InputFileInfo FI = readInputFileInfo(F, ID);
2299 off_t StoredSize = FI.StoredSize;
2300 time_t StoredTime = FI.StoredTime;
2301 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002302 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002303 StringRef Filename = FI.Filename;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002304 uint64_t StoredContentHash = FI.ContentHash;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002305
Harlan Haskins8d323d12019-08-01 21:31:56 +00002306 const FileEntry *File = nullptr;
2307 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2308 File = *FE;
2309
Ben Langmuir198c1682014-03-07 07:27:49 +00002310 // If we didn't find the file, resolve it relative to the
2311 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002312 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2313 F.OriginalDir != F.BaseDirectory) {
2314 std::string Resolved = resolveFileRelativeToOriginalDir(
Benjamin Krameradcd0262020-01-28 20:23:46 +01002315 std::string(Filename), F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002316 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002317 if (auto FE = FileMgr.getFile(Resolved))
2318 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002319 }
2320
2321 // For an overridden file, create a virtual file with the stored
2322 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002323 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002324 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002325
Craig Toppera13603a2014-05-22 05:54:18 +00002326 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002327 if (Complain) {
2328 std::string ErrorStr = "could not find file '";
2329 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002330 ErrorStr += "' referenced by AST file '";
2331 ErrorStr += F.FileName;
2332 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002333 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002334 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002335 // Record that we didn't find the file.
2336 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2337 return InputFile();
2338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002339
Ben Langmuir198c1682014-03-07 07:27:49 +00002340 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002341 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002342 // can lead to problems when lexing using the source locations from the
2343 // PCH.
2344 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002345 // FIXME: Reject if the overrides are different.
2346 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002347 if (Complain)
2348 Error(diag::err_fe_pch_file_overridden, Filename);
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25 +00002349
2350 // After emitting the diagnostic, bypass the overriding file to recover
2351 // (this creates a separate FileEntry).
2352 File = SM.bypassFileContentsOverride(*File);
2353 if (!File) {
2354 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2355 return InputFile();
2356 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002357 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002358
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002359 enum ModificationType {
2360 Size,
2361 ModTime,
2362 Content,
2363 None,
2364 };
2365 auto HasInputFileChanged = [&]() {
2366 if (StoredSize != File->getSize())
2367 return ModificationType::Size;
2368 if (!DisableValidation && StoredTime &&
2369 StoredTime != File->getModificationTime()) {
2370 // In case the modification time changes but not the content,
2371 // accept the cached file as legit.
2372 if (ValidateASTInputFilesContent &&
2373 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2374 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2375 if (!MemBuffOrError) {
2376 if (!Complain)
2377 return ModificationType::ModTime;
2378 std::string ErrorStr = "could not get buffer for file '";
2379 ErrorStr += File->getName();
2380 ErrorStr += "'";
2381 Error(ErrorStr);
2382 return ModificationType::ModTime;
2383 }
Eric Christopher3be91692019-10-14 23:14:24 +00002384
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002385 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2386 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2387 return ModificationType::None;
2388 return ModificationType::Content;
2389 }
2390 return ModificationType::ModTime;
2391 }
2392 return ModificationType::None;
2393 };
2394
2395 bool IsOutOfDate = false;
2396 auto FileChange = HasInputFileChanged();
Ben Langmuir198c1682014-03-07 07:27:49 +00002397 // For an overridden file, there is nothing to validate.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002398 if (!Overridden && FileChange != ModificationType::None) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002399 if (Complain) {
2400 // Build a list of the PCH imports that got us here (in reverse).
2401 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002402 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002403 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002404
Ben Langmuir198c1682014-03-07 07:27:49 +00002405 // The top-level PCH is stale.
2406 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002407 unsigned DiagnosticKind =
2408 moduleKindForDiagnostic(ImportStack.back()->Kind);
Manman Renc8c94152016-10-21 23:35:03 +00002409 if (DiagnosticKind == 0)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002410 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2411 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002412 else if (DiagnosticKind == 1)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002413 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2414 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002415 else
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002416 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2417 (unsigned)FileChange);
Ben Langmuire82630d2014-01-17 00:19:09 +00002418
Ben Langmuir198c1682014-03-07 07:27:49 +00002419 // Print the import stack.
2420 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2421 Diag(diag::note_pch_required_by)
2422 << Filename << ImportStack[0]->FileName;
2423 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002424 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002425 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002426 }
2427
Ben Langmuir198c1682014-03-07 07:27:49 +00002428 if (!Diags.isDiagnosticInFlight())
2429 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 }
2431
Ben Langmuir198c1682014-03-07 07:27:49 +00002432 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002433 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002434 // FIXME: If the file is overridden and we've already opened it,
2435 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002436
Richard Smitha8cfffa2015-11-26 02:04:16 +00002437 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002438
2439 // Note that we've loaded this input file.
2440 F.InputFilesLoaded[ID-1] = IF;
2441 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002442}
2443
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002444/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002445/// is not an absolute path, add the system or module root to the beginning of
2446/// the file name.
2447void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2448 // Resolve relative to the base directory, if we have one.
2449 if (!M.BaseDirectory.empty())
2450 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002451}
2452
Richard Smith7ed1bc92014-12-05 22:42:13 +00002453void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002454 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2455 return;
2456
Richard Smith7ed1bc92014-12-05 22:42:13 +00002457 SmallString<128> Buffer;
2458 llvm::sys::path::append(Buffer, Prefix, Filename);
2459 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002460}
2461
Richard Smith0f99d6a2015-08-09 08:48:41 +00002462static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2463 switch (ARR) {
2464 case ASTReader::Failure: return true;
2465 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2466 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2467 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2468 case ASTReader::ConfigurationMismatch:
2469 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2470 case ASTReader::HadErrors: return true;
2471 case ASTReader::Success: return false;
2472 }
2473
2474 llvm_unreachable("unknown ASTReadResult");
2475}
2476
Richard Smith0516b182015-09-08 19:40:14 +00002477ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2478 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2479 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002480 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002481 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2482 // FIXME this drops errors on the floor.
2483 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002484 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002485 }
Richard Smith0516b182015-09-08 19:40:14 +00002486
2487 // Read all of the records in the options block.
2488 RecordData Record;
2489 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002490 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002491 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2492 if (!MaybeEntry) {
2493 // FIXME this drops errors on the floor.
2494 consumeError(MaybeEntry.takeError());
2495 return Failure;
2496 }
2497 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002498
Richard Smith0516b182015-09-08 19:40:14 +00002499 switch (Entry.Kind) {
2500 case llvm::BitstreamEntry::Error:
2501 case llvm::BitstreamEntry::SubBlock:
2502 return Failure;
2503
2504 case llvm::BitstreamEntry::EndBlock:
2505 return Result;
2506
2507 case llvm::BitstreamEntry::Record:
2508 // The interesting case.
2509 break;
2510 }
2511
2512 // Read and process a record.
2513 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002514 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2515 if (!MaybeRecordType) {
2516 // FIXME this drops errors on the floor.
2517 consumeError(MaybeRecordType.takeError());
2518 return Failure;
2519 }
2520 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002521 case LANGUAGE_OPTIONS: {
2522 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2523 if (ParseLanguageOptions(Record, Complain, Listener,
2524 AllowCompatibleConfigurationMismatch))
2525 Result = ConfigurationMismatch;
2526 break;
2527 }
2528
2529 case TARGET_OPTIONS: {
2530 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2531 if (ParseTargetOptions(Record, Complain, Listener,
2532 AllowCompatibleConfigurationMismatch))
2533 Result = ConfigurationMismatch;
2534 break;
2535 }
2536
Richard Smith0516b182015-09-08 19:40:14 +00002537 case FILE_SYSTEM_OPTIONS: {
2538 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2539 if (!AllowCompatibleConfigurationMismatch &&
2540 ParseFileSystemOptions(Record, Complain, Listener))
2541 Result = ConfigurationMismatch;
2542 break;
2543 }
2544
2545 case HEADER_SEARCH_OPTIONS: {
2546 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2547 if (!AllowCompatibleConfigurationMismatch &&
2548 ParseHeaderSearchOptions(Record, Complain, Listener))
2549 Result = ConfigurationMismatch;
2550 break;
2551 }
2552
2553 case PREPROCESSOR_OPTIONS:
2554 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2555 if (!AllowCompatibleConfigurationMismatch &&
2556 ParsePreprocessorOptions(Record, Complain, Listener,
2557 SuggestedPredefines))
2558 Result = ConfigurationMismatch;
2559 break;
2560 }
2561 }
2562}
2563
Guy Benyei11169dd2012-12-18 14:30:41 +00002564ASTReader::ASTReadResult
2565ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002566 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002567 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002568 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002569 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002570
JF Bastien0e828952019-06-26 19:50:12 +00002571 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2572 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 return Failure;
2574 }
2575
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002576 // Lambda to read the unhashed control block the first time it's called.
2577 //
2578 // For PCM files, the unhashed control block cannot be read until after the
2579 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2580 // need to look ahead before reading the IMPORTS record. For consistency,
2581 // this block is always read somehow (see BitstreamEntry::EndBlock).
2582 bool HasReadUnhashedControlBlock = false;
2583 auto readUnhashedControlBlockOnce = [&]() {
2584 if (!HasReadUnhashedControlBlock) {
2585 HasReadUnhashedControlBlock = true;
2586 if (ASTReadResult Result =
2587 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2588 return Result;
2589 }
2590 return Success;
2591 };
2592
Guy Benyei11169dd2012-12-18 14:30:41 +00002593 // Read all of the records and blocks in the control block.
2594 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002595 unsigned NumInputs = 0;
2596 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002597 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002598 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002599 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2600 if (!MaybeEntry) {
2601 Error(MaybeEntry.takeError());
2602 return Failure;
2603 }
2604 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002605
Chris Lattnere7b154b2013-01-19 21:39:22 +00002606 switch (Entry.Kind) {
2607 case llvm::BitstreamEntry::Error:
2608 Error("malformed block record in AST file");
2609 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002610 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002611 // Validate the module before returning. This call catches an AST with
2612 // no module name and no imports.
2613 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2614 return Result;
2615
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002616 // Validate input files.
2617 const HeaderSearchOptions &HSOpts =
2618 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002619
Richard Smitha1825302014-10-23 22:18:29 +00002620 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002621 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2622 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002623 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2624 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002626
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002627 // If we are reading a module, we will create a verification timestamp,
2628 // so we verify all input files. Otherwise, verify only user input
2629 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002630
2631 unsigned N = NumUserInputs;
2632 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002633 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002634 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002635 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002636 N = NumInputs;
2637
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002638 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002639 InputFile IF = getInputFile(F, I+1, Complain);
2640 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002642 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002644
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002645 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002646 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002647
Ben Langmuircb69b572014-03-07 06:40:32 +00002648 if (Listener && Listener->needsInputFileVisitation()) {
2649 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2650 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002651 for (unsigned I = 0; I < N; ++I) {
2652 bool IsSystem = I >= NumUserInputs;
2653 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002654 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002655 F.Kind == MK_ExplicitModule ||
2656 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002657 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002658 }
2659
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002660 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002661 }
2662
Chris Lattnere7b154b2013-01-19 21:39:22 +00002663 case llvm::BitstreamEntry::SubBlock:
2664 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 case INPUT_FILES_BLOCK_ID:
2666 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002667 if (llvm::Error Err = Stream.SkipBlock()) {
2668 Error(std::move(Err));
2669 return Failure;
2670 }
2671 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 Error("malformed block record in AST file");
2673 return Failure;
2674 }
2675 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002676
2677 case OPTIONS_BLOCK_ID:
2678 // If we're reading the first module for this group, check its options
2679 // are compatible with ours. For modules it imports, no further checking
2680 // is required, because we checked them when we built it.
2681 if (Listener && !ImportedBy) {
2682 // Should we allow the configuration of the module file to differ from
2683 // the configuration of the current translation unit in a compatible
2684 // way?
2685 //
2686 // FIXME: Allow this for files explicitly specified with -include-pch.
2687 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002688 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002689
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002690 ASTReadResult Result =
2691 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2692 AllowCompatibleConfigurationMismatch, *Listener,
2693 SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002694 if (Result == Failure) {
2695 Error("malformed block record in AST file");
2696 return Result;
2697 }
2698
Richard Smith8a308ec2015-11-05 00:54:55 +00002699 if (DisableValidation ||
2700 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2701 Result = Success;
2702
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002703 // If we can't load the module, exit early since we likely
2704 // will rebuild the module anyway. The stream may be in the
2705 // middle of a block.
2706 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002707 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002708 } else if (llvm::Error Err = Stream.SkipBlock()) {
2709 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002710 return Failure;
2711 }
2712 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002713
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 default:
JF Bastien0e828952019-06-26 19:50:12 +00002715 if (llvm::Error Err = Stream.SkipBlock()) {
2716 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002717 return Failure;
2718 }
2719 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002721
Chris Lattnere7b154b2013-01-19 21:39:22 +00002722 case llvm::BitstreamEntry::Record:
2723 // The interesting case.
2724 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 }
2726
2727 // Read and process a record.
2728 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002730 Expected<unsigned> MaybeRecordType =
2731 Stream.readRecord(Entry.ID, Record, &Blob);
2732 if (!MaybeRecordType) {
2733 Error(MaybeRecordType.takeError());
2734 return Failure;
2735 }
2736 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 case METADATA: {
2738 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2739 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002740 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2741 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 return VersionMismatch;
2743 }
2744
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002745 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002746 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2747 Diag(diag::err_pch_with_compiler_errors);
2748 return HadErrors;
2749 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002750 if (hasErrors) {
2751 Diags.ErrorOccurred = true;
2752 Diags.UncompilableErrorOccurred = true;
2753 Diags.UnrecoverableErrorOccurred = true;
2754 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002755
2756 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002757 // Relative paths in a relocatable PCH are relative to our sysroot.
2758 if (F.RelocatablePCH)
2759 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002760
Richard Smithe75ee0f2015-08-17 07:13:32 +00002761 F.HasTimestamps = Record[5];
2762
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002763 F.PCHHasObjectFile = Record[6];
2764
Guy Benyei11169dd2012-12-18 14:30:41 +00002765 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002766 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2768 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002769 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 return VersionMismatch;
2771 }
2772 break;
2773 }
2774
2775 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002776 // Validate the AST before processing any imports (otherwise, untangling
2777 // them can be error-prone and expensive). A module will have a name and
2778 // will already have been validated, but this catches the PCH case.
2779 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2780 return Result;
2781
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002782 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 unsigned Idx = 0, N = Record.size();
2784 while (Idx < N) {
2785 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002786 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 // The import location will be the local one for now; we will adjust
2788 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002789 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002791 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002792 off_t StoredSize = (off_t)Record[Idx++];
2793 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002794 ASTFileSignature StoredSignature = {
2795 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2796 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2797 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002798
2799 std::string ImportedName = ReadString(Record, Idx);
2800 std::string ImportedFile;
2801
2802 // For prebuilt and explicit modules first consult the file map for
2803 // an override. Note that here we don't search prebuilt module
2804 // directories, only the explicit name to file mappings. Also, we will
2805 // still verify the size/signature making sure it is essentially the
2806 // same file but perhaps in a different location.
2807 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2808 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2809 ImportedName, /*FileMapOnly*/ true);
2810
2811 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002812 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2813 // ModuleCache as when writing.
2814 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002815 else
2816 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002817
Richard Smith0f99d6a2015-08-09 08:48:41 +00002818 // If our client can't cope with us being out of date, we can't cope with
2819 // our dependency being missing.
2820 unsigned Capabilities = ClientLoadCapabilities;
2821 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2822 Capabilities &= ~ARR_Missing;
2823
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002825 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2826 Loaded, StoredSize, StoredModTime,
2827 StoredSignature, Capabilities);
2828
2829 // If we diagnosed a problem, produce a backtrace.
2830 if (isDiagnosedResult(Result, Capabilities))
2831 Diag(diag::note_module_file_imported_by)
2832 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2833
2834 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 case Failure: return Failure;
2836 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002837 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 case OutOfDate: return OutOfDate;
2839 case VersionMismatch: return VersionMismatch;
2840 case ConfigurationMismatch: return ConfigurationMismatch;
2841 case HadErrors: return HadErrors;
2842 case Success: break;
2843 }
2844 }
2845 break;
2846 }
2847
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 case ORIGINAL_FILE:
2849 F.OriginalSourceFileID = FileID::get(Record[0]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002850 F.ActualOriginalSourceFileName = std::string(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002852 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 break;
2854
2855 case ORIGINAL_FILE_ID:
2856 F.OriginalSourceFileID = FileID::get(Record[0]);
2857 break;
2858
2859 case ORIGINAL_PCH_DIR:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002860 F.OriginalDir = std::string(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 break;
2862
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002863 case MODULE_NAME:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002864 F.ModuleName = std::string(Blob);
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002865 Diag(diag::remark_module_import)
2866 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2867 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002868 if (Listener)
2869 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002870
2871 // Validate the AST as soon as we have a name so we can exit early on
2872 // failure.
2873 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2874 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002875
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002876 break;
2877
Richard Smith223d3f22014-12-06 03:21:08 +00002878 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002879 // Save the BaseDirectory as written in the PCM for computing the module
2880 // filename for the ModuleCache.
2881 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002882 assert(!F.ModuleName.empty() &&
2883 "MODULE_DIRECTORY found before MODULE_NAME");
2884 // If we've already loaded a module map file covering this module, we may
2885 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002886 Module *M = PP.getHeaderSearchInfo().lookupModule(
2887 F.ModuleName, /*AllowSearch*/ true,
2888 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002889 if (M && M->Directory) {
2890 // If we're implicitly loading a module, the base directory can't
2891 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002892 // Don't emit module relocation error if we have -fno-validate-pch
2893 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2894 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002895 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2896 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002897 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2898 Diag(diag::err_imported_module_relocated)
2899 << F.ModuleName << Blob << M->Directory->getName();
2900 return OutOfDate;
2901 }
2902 }
Benjamin Krameradcd0262020-01-28 20:23:46 +01002903 F.BaseDirectory = std::string(M->Directory->getName());
Richard Smith223d3f22014-12-06 03:21:08 +00002904 } else {
Benjamin Krameradcd0262020-01-28 20:23:46 +01002905 F.BaseDirectory = std::string(Blob);
Richard Smith223d3f22014-12-06 03:21:08 +00002906 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002907 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002908 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002909
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002910 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002911 if (ASTReadResult Result =
2912 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2913 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002914 break;
2915
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002916 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002917 NumInputs = Record[0];
2918 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002919 F.InputFileOffsets =
2920 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002921 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002922 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 break;
2924 }
2925 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002926}
2927
Ben Langmuir2c9af442014-04-10 17:57:43 +00002928ASTReader::ASTReadResult
2929ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002930 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002931
JF Bastien0e828952019-06-26 19:50:12 +00002932 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2933 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002934 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 }
2936
2937 // Read all of the records and blocks for the AST file.
2938 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002939 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002940 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2941 if (!MaybeEntry) {
2942 Error(MaybeEntry.takeError());
2943 return Failure;
2944 }
2945 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002946
Chris Lattnere7b154b2013-01-19 21:39:22 +00002947 switch (Entry.Kind) {
2948 case llvm::BitstreamEntry::Error:
2949 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002950 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002951 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002952 // Outside of C++, we do not store a lookup map for the translation unit.
2953 // Instead, mark it as needing a lookup map to be built if this module
2954 // contains any declarations lexically within it (which it always does!).
2955 // This usually has no cost, since we very rarely need the lookup map for
2956 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002957 if (ASTContext *Ctx = ContextObj) {
2958 DeclContext *DC = Ctx->getTranslationUnitDecl();
2959 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2960 DC->setMustBuildLookupTable();
2961 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002962
Ben Langmuir2c9af442014-04-10 17:57:43 +00002963 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002964 case llvm::BitstreamEntry::SubBlock:
2965 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 case DECLTYPES_BLOCK_ID:
2967 // We lazily load the decls block, but we want to set up the
2968 // DeclsCursor cursor to point into it. Clone our current bitcode
2969 // cursor to it, enter the block and read the abbrevs in that block.
2970 // With the main cursor, we just skip over it.
2971 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002972 if (llvm::Error Err = Stream.SkipBlock()) {
2973 Error(std::move(Err));
2974 return Failure;
2975 }
2976 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002978 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 }
2980 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002981
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 case PREPROCESSOR_BLOCK_ID:
2983 F.MacroCursor = Stream;
2984 if (!PP.getExternalSource())
2985 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002986
JF Bastien0e828952019-06-26 19:50:12 +00002987 if (llvm::Error Err = Stream.SkipBlock()) {
2988 Error(std::move(Err));
2989 return Failure;
2990 }
2991 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002992 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002993 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 }
2995 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2996 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002997
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 case PREPROCESSOR_DETAIL_BLOCK_ID:
2999 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00003000
3001 if (llvm::Error Err = Stream.SkipBlock()) {
3002 Error(std::move(Err));
3003 return Failure;
3004 }
3005 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00003007 Error("malformed preprocessor detail record in AST file");
3008 return Failure;
3009 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00003011 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003012
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 if (!PP.getPreprocessingRecord())
3014 PP.createPreprocessingRecord();
3015 if (!PP.getPreprocessingRecord()->getExternalSource())
3016 PP.getPreprocessingRecord()->SetExternalSource(*this);
3017 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003018
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 case SOURCE_MANAGER_BLOCK_ID:
3020 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003021 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003023
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00003025 if (ASTReadResult Result =
3026 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003027 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003029
Guy Benyei11169dd2012-12-18 14:30:41 +00003030 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003031 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00003032
3033 if (llvm::Error Err = Stream.SkipBlock()) {
3034 Error(std::move(Err));
3035 return Failure;
3036 }
3037 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003039 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 }
3041 CommentsCursors.push_back(std::make_pair(C, &F));
3042 break;
3043 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003044
Guy Benyei11169dd2012-12-18 14:30:41 +00003045 default:
JF Bastien0e828952019-06-26 19:50:12 +00003046 if (llvm::Error Err = Stream.SkipBlock()) {
3047 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00003048 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003049 }
3050 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 }
3052 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003053
Chris Lattnere7b154b2013-01-19 21:39:22 +00003054 case llvm::BitstreamEntry::Record:
3055 // The interesting case.
3056 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 }
3058
3059 // Read and process a record.
3060 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003061 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00003062 Expected<unsigned> MaybeRecordType =
3063 Stream.readRecord(Entry.ID, Record, &Blob);
3064 if (!MaybeRecordType) {
3065 Error(MaybeRecordType.takeError());
3066 return Failure;
3067 }
3068 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003069
3070 // If we're not loading an AST context, we don't care about most records.
3071 if (!ContextObj) {
3072 switch (RecordType) {
3073 case IDENTIFIER_TABLE:
3074 case IDENTIFIER_OFFSET:
3075 case INTERESTING_IDENTIFIERS:
3076 case STATISTICS:
3077 case PP_CONDITIONAL_STACK:
3078 case PP_COUNTER_VALUE:
3079 case SOURCE_LOCATION_OFFSETS:
3080 case MODULE_OFFSET_MAP:
3081 case SOURCE_MANAGER_LINE_TABLE:
3082 case SOURCE_LOCATION_PRELOADS:
3083 case PPD_ENTITIES_OFFSETS:
3084 case HEADER_SEARCH_TABLE:
3085 case IMPORTED_MODULES:
3086 case MACRO_OFFSET:
3087 break;
3088 default:
3089 continue;
3090 }
3091 }
3092
3093 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 default: // Default behavior: ignore.
3095 break;
3096
3097 case TYPE_OFFSET: {
3098 if (F.LocalNumTypes != 0) {
3099 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003100 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 }
Dmitry Polukhina7afb212020-04-16 09:24:46 -07003102 F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 F.LocalNumTypes = Record[0];
3104 unsigned LocalBaseTypeIndex = Record[1];
3105 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003106
Guy Benyei11169dd2012-12-18 14:30:41 +00003107 if (F.LocalNumTypes > 0) {
3108 // Introduce the global -> local mapping for types within this module.
3109 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003110
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 // Introduce the local -> global mapping for types within this module.
3112 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003113 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003115
3116 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 }
3118 break;
3119 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003120
Guy Benyei11169dd2012-12-18 14:30:41 +00003121 case DECL_OFFSET: {
3122 if (F.LocalNumDecls != 0) {
3123 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003124 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003126 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 F.LocalNumDecls = Record[0];
3128 unsigned LocalBaseDeclID = Record[1];
3129 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003132 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 // module.
3134 GlobalDeclMap.insert(
3135 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 // Introduce the local -> global mapping for declarations within this
3138 // module.
3139 F.DeclRemap.insertOrReplace(
3140 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003141
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 // Introduce the global -> local mapping for declarations within this
3143 // module.
3144 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003145
Ben Langmuir52ca6782014-10-20 16:27:32 +00003146 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3147 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 break;
3149 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003152 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003153 LexicalContents Contents(
3154 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3155 Blob.data()),
3156 static_cast<unsigned int>(Blob.size() / 4));
3157 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 TU->setHasExternalLexicalStorage(true);
3159 break;
3160 }
3161
3162 case UPDATE_VISIBLE: {
3163 unsigned Idx = 0;
3164 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003165 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003166 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003167 // If we've already loaded the decl, perform the updates when we finish
3168 // loading this block.
3169 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003170 PendingUpdateRecords.push_back(
3171 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 break;
3173 }
3174
3175 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003176 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003178 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3179 (const unsigned char *)F.IdentifierTableData + Record[0],
3180 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3181 (const unsigned char *)F.IdentifierTableData,
3182 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003183
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3185 }
3186 break;
3187
3188 case IDENTIFIER_OFFSET: {
3189 if (F.LocalNumIdentifiers != 0) {
3190 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003191 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003192 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003193 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 F.LocalNumIdentifiers = Record[0];
3195 unsigned LocalBaseIdentifierID = Record[1];
3196 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003197
Guy Benyei11169dd2012-12-18 14:30:41 +00003198 if (F.LocalNumIdentifiers > 0) {
3199 // Introduce the global -> local mapping for identifiers within this
3200 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003201 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003203
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 // Introduce the local -> global mapping for identifiers within this
3205 // module.
3206 F.IdentifierRemap.insertOrReplace(
3207 std::make_pair(LocalBaseIdentifierID,
3208 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003209
Ben Langmuir52ca6782014-10-20 16:27:32 +00003210 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3211 + F.LocalNumIdentifiers);
3212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 break;
3214 }
3215
Richard Smith33e0f7e2015-07-22 02:08:40 +00003216 case INTERESTING_IDENTIFIERS:
3217 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3218 break;
3219
Ben Langmuir332aafe2014-01-31 01:06:56 +00003220 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003221 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3222 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003224 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 break;
3226
David Blaikie9ffe5a32017-01-30 05:00:26 +00003227 case MODULAR_CODEGEN_DECLS:
3228 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3229 // them (ie: if we're not codegenerating this module).
Hans Wennborg7ea9a6e2020-02-27 14:33:43 +01003230 if (F.Kind == MK_MainFile)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003231 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3232 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3233 break;
3234
Guy Benyei11169dd2012-12-18 14:30:41 +00003235 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003236 if (SpecialTypes.empty()) {
3237 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3238 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3239 break;
3240 }
3241
3242 if (SpecialTypes.size() != Record.size()) {
3243 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003244 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003245 }
3246
3247 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3248 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3249 if (!SpecialTypes[I])
3250 SpecialTypes[I] = ID;
3251 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3252 // merge step?
3253 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 break;
3255
3256 case STATISTICS:
3257 TotalNumStatements += Record[0];
3258 TotalNumMacros += Record[1];
3259 TotalLexicalDeclContexts += Record[2];
3260 TotalVisibleDeclContexts += Record[3];
3261 break;
3262
3263 case UNUSED_FILESCOPED_DECLS:
3264 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3265 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3266 break;
3267
3268 case DELEGATING_CTORS:
3269 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3270 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3271 break;
3272
3273 case WEAK_UNDECLARED_IDENTIFIERS:
3274 if (Record.size() % 4 != 0) {
3275 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003276 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003278
3279 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 // files. This isn't the way to do it :)
3281 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003282
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 // Translate the weak, undeclared identifiers into global IDs.
3284 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3285 WeakUndeclaredIdentifiers.push_back(
3286 getGlobalIdentifierID(F, Record[I++]));
3287 WeakUndeclaredIdentifiers.push_back(
3288 getGlobalIdentifierID(F, Record[I++]));
3289 WeakUndeclaredIdentifiers.push_back(
3290 ReadSourceLocation(F, Record, I).getRawEncoding());
3291 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3292 }
3293 break;
3294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003296 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 F.LocalNumSelectors = Record[0];
3298 unsigned LocalBaseSelectorID = Record[1];
3299 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003300
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003302 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 // module.
3304 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003305
3306 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 // module.
3308 F.SelectorRemap.insertOrReplace(
3309 std::make_pair(LocalBaseSelectorID,
3310 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003311
3312 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 }
3314 break;
3315 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003316
Guy Benyei11169dd2012-12-18 14:30:41 +00003317 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003318 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003319 if (Record[0])
3320 F.SelectorLookupTable
3321 = ASTSelectorLookupTable::Create(
3322 F.SelectorLookupTableData + Record[0],
3323 F.SelectorLookupTableData,
3324 ASTSelectorLookupTrait(*this, F));
3325 TotalNumMethodPoolEntries += Record[1];
3326 break;
3327
3328 case REFERENCED_SELECTOR_POOL:
3329 if (!Record.empty()) {
3330 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003331 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 Record[Idx++]));
3333 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3334 getRawEncoding());
3335 }
3336 }
3337 break;
3338
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003339 case PP_CONDITIONAL_STACK:
3340 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003341 unsigned Idx = 0, End = Record.size() - 1;
3342 bool ReachedEOFWhileSkipping = Record[Idx++];
3343 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3344 if (ReachedEOFWhileSkipping) {
3345 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3346 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3347 bool FoundNonSkipPortion = Record[Idx++];
3348 bool FoundElse = Record[Idx++];
3349 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3350 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3351 FoundElse, ElseLoc);
3352 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003353 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003354 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003355 auto Loc = ReadSourceLocation(F, Record, Idx);
3356 bool WasSkipping = Record[Idx++];
3357 bool FoundNonSkip = Record[Idx++];
3358 bool FoundElse = Record[Idx++];
3359 ConditionalStack.push_back(
3360 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3361 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003362 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003363 }
3364 break;
3365
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 case PP_COUNTER_VALUE:
3367 if (!Record.empty() && Listener)
3368 Listener->ReadCounter(F, Record[0]);
3369 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003370
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003372 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003373 F.NumFileSortedDecls = Record[0];
3374 break;
3375
3376 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003377 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003378 F.LocalNumSLocEntries = Record[0];
3379 unsigned SLocSpaceSize = Record[1];
Dmitry Polukhina7afb212020-04-16 09:24:46 -07003380 F.SLocEntryOffsetsBase = Record[2];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003381 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003382 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003383 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003384 if (!F.SLocEntryBaseID) {
3385 Error("ran out of source locations");
3386 break;
3387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 // Make our entry in the range map. BaseID is negative and growing, so
3389 // we invert it. Because we invert it, though, we need the other end of
3390 // the range.
3391 unsigned RangeStart =
3392 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3393 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3394 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3395
3396 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3397 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3398 GlobalSLocOffsetMap.insert(
3399 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3400 - SLocSpaceSize,&F));
3401
3402 // Initialize the remapping table.
3403 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003404 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003406 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003407 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003408
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 TotalNumSLocEntries += F.LocalNumSLocEntries;
3410 break;
3411 }
3412
Richard Smith37a93df2017-02-18 00:32:02 +00003413 case MODULE_OFFSET_MAP:
3414 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003416
3417 case SOURCE_MANAGER_LINE_TABLE:
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003418 if (ParseLineTable(F, Record)) {
3419 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003420 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003421 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003422 break;
3423
3424 case SOURCE_LOCATION_PRELOADS: {
3425 // Need to transform from the local view (1-based IDs) to the global view,
3426 // which is based off F.SLocEntryBaseID.
3427 if (!F.PreloadSLocEntries.empty()) {
3428 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003429 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003431
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 F.PreloadSLocEntries.swap(Record);
3433 break;
3434 }
3435
3436 case EXT_VECTOR_DECLS:
3437 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3438 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3439 break;
3440
3441 case VTABLE_USES:
3442 if (Record.size() % 3 != 0) {
3443 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003444 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003445 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003446
Guy Benyei11169dd2012-12-18 14:30:41 +00003447 // Later tables overwrite earlier ones.
3448 // FIXME: Modules will have some trouble with this. This is clearly not
3449 // the right way to do this.
3450 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003451
Guy Benyei11169dd2012-12-18 14:30:41 +00003452 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3453 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3454 VTableUses.push_back(
3455 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3456 VTableUses.push_back(Record[Idx++]);
3457 }
3458 break;
3459
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 case PENDING_IMPLICIT_INSTANTIATIONS:
3461 if (PendingInstantiations.size() % 2 != 0) {
3462 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003463 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 }
3465
3466 if (Record.size() % 2 != 0) {
3467 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003468 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 }
3470
3471 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3472 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3473 PendingInstantiations.push_back(
3474 ReadSourceLocation(F, Record, I).getRawEncoding());
3475 }
3476 break;
3477
3478 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003479 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003480 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003481 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003482 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003483 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3484 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3485 break;
3486
3487 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003488 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3489 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3490 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003491
3492 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 unsigned StartingID;
3495 if (!PP.getPreprocessingRecord())
3496 PP.createPreprocessingRecord();
3497 if (!PP.getPreprocessingRecord()->getExternalSource())
3498 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003499 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003500 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003501 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 F.BasePreprocessedEntityID = StartingID;
3503
3504 if (F.NumPreprocessedEntities > 0) {
3505 // Introduce the global -> local mapping for preprocessed entities in
3506 // this module.
3507 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003508
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 // Introduce the local -> global mapping for preprocessed entities in
3510 // this module.
3511 F.PreprocessedEntityRemap.insertOrReplace(
3512 std::make_pair(LocalBasePreprocessedEntityID,
3513 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3514 }
3515
3516 break;
3517 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003518
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003519 case PPD_SKIPPED_RANGES: {
3520 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3521 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3522 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3523
3524 if (!PP.getPreprocessingRecord())
3525 PP.createPreprocessingRecord();
3526 if (!PP.getPreprocessingRecord()->getExternalSource())
3527 PP.getPreprocessingRecord()->SetExternalSource(*this);
3528 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3529 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003530
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003531 if (F.NumPreprocessedSkippedRanges > 0)
3532 GlobalSkippedRangeMap.insert(
3533 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3534 break;
3535 }
3536
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003537 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 if (Record.size() % 2 != 0) {
3539 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003540 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003542 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3543 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3544 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3545
3546 // If we've already loaded the decl, perform the updates when we finish
3547 // loading this block.
3548 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003549 PendingUpdateRecords.push_back(
3550 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003551 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003553
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003554 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 if (F.LocalNumObjCCategoriesInMap != 0) {
3556 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003557 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003558 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003559
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003561 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003563
Guy Benyei11169dd2012-12-18 14:30:41 +00003564 case OBJC_CATEGORIES:
3565 F.ObjCCategories.swap(Record);
3566 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003567
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 case CUDA_SPECIAL_DECL_REFS:
3569 // Later tables overwrite earlier ones.
3570 // FIXME: Modules will have trouble with this.
3571 CUDASpecialDeclRefs.clear();
3572 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3573 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3574 break;
3575
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003576 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003577 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003578 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003579 if (Record[0]) {
3580 F.HeaderFileInfoTable
3581 = HeaderFileInfoLookupTable::Create(
3582 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3583 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003584 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003586 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003587
Guy Benyei11169dd2012-12-18 14:30:41 +00003588 PP.getHeaderSearchInfo().SetExternalSource(this);
3589 if (!PP.getHeaderSearchInfo().getExternalLookup())
3590 PP.getHeaderSearchInfo().SetExternalLookup(this);
3591 }
3592 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003593
Guy Benyei11169dd2012-12-18 14:30:41 +00003594 case FP_PRAGMA_OPTIONS:
3595 // Later tables overwrite earlier ones.
3596 FPPragmaOptions.swap(Record);
3597 break;
3598
3599 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003600 for (unsigned I = 0, E = Record.size(); I != E; ) {
3601 auto Name = ReadString(Record, I);
3602 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003603 Opt.Supported = Record[I++] != 0;
3604 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003605 Opt.Avail = Record[I++];
3606 Opt.Core = Record[I++];
3607 }
3608 break;
3609
3610 case OPENCL_EXTENSION_TYPES:
3611 for (unsigned I = 0, E = Record.size(); I != E;) {
3612 auto TypeID = static_cast<::TypeID>(Record[I++]);
3613 auto *Type = GetType(TypeID).getTypePtr();
3614 auto NumExt = static_cast<unsigned>(Record[I++]);
3615 for (unsigned II = 0; II != NumExt; ++II) {
3616 auto Ext = ReadString(Record, I);
3617 OpenCLTypeExtMap[Type].insert(Ext);
3618 }
3619 }
3620 break;
3621
3622 case OPENCL_EXTENSION_DECLS:
3623 for (unsigned I = 0, E = Record.size(); I != E;) {
3624 auto DeclID = static_cast<::DeclID>(Record[I++]);
3625 auto *Decl = GetDecl(DeclID);
3626 auto NumExt = static_cast<unsigned>(Record[I++]);
3627 for (unsigned II = 0; II != NumExt; ++II) {
3628 auto Ext = ReadString(Record, I);
3629 OpenCLDeclExtMap[Decl].insert(Ext);
3630 }
3631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 break;
3633
3634 case TENTATIVE_DEFINITIONS:
3635 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3636 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3637 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003638
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 case KNOWN_NAMESPACES:
3640 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3641 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3642 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003643
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003644 case UNDEFINED_BUT_USED:
3645 if (UndefinedButUsed.size() % 2 != 0) {
3646 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003647 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003648 }
3649
3650 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003651 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003652 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003653 }
3654 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003655 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3656 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003657 ReadSourceLocation(F, Record, I).getRawEncoding());
3658 }
3659 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003660
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003661 case DELETE_EXPRS_TO_ANALYZE:
3662 for (unsigned I = 0, N = Record.size(); I != N;) {
3663 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3664 const uint64_t Count = Record[I++];
3665 DelayedDeleteExprs.push_back(Count);
3666 for (uint64_t C = 0; C < Count; ++C) {
3667 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3668 bool IsArrayForm = Record[I++] == 1;
3669 DelayedDeleteExprs.push_back(IsArrayForm);
3670 }
3671 }
3672 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003673
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003674 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003675 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 // If we aren't loading a module (which has its own exports), make
3677 // all of the imported modules visible.
3678 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003679 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3680 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3681 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003682 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003683 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003684 if (DeserializationListener)
3685 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3686 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003687 }
3688 }
3689 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003690
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 case MACRO_OFFSET: {
3692 if (F.LocalNumMacros != 0) {
3693 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003694 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003696 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003697 F.LocalNumMacros = Record[0];
3698 unsigned LocalBaseMacroID = Record[1];
Dmitry Polukhina7afb212020-04-16 09:24:46 -07003699 F.MacroOffsetsBase = Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 F.BaseMacroID = getTotalNumMacros();
3701
3702 if (F.LocalNumMacros > 0) {
3703 // Introduce the global -> local mapping for macros within this module.
3704 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3705
3706 // Introduce the local -> global mapping for macros within this module.
3707 F.MacroRemap.insertOrReplace(
3708 std::make_pair(LocalBaseMacroID,
3709 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003710
3711 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003712 }
3713 break;
3714 }
3715
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003716 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003717 LateParsedTemplates.append(Record.begin(), Record.end());
3718 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003719
3720 case OPTIMIZE_PRAGMA_OPTIONS:
3721 if (Record.size() != 1) {
3722 Error("invalid pragma optimize record");
3723 return Failure;
3724 }
3725 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3726 break;
Nico Weber72889432014-09-06 01:25:55 +00003727
Nico Weber779355f2016-03-02 23:22:00 +00003728 case MSSTRUCT_PRAGMA_OPTIONS:
3729 if (Record.size() != 1) {
3730 Error("invalid pragma ms_struct record");
3731 return Failure;
3732 }
3733 PragmaMSStructState = Record[0];
3734 break;
3735
Nico Weber42932312016-03-03 00:17:35 +00003736 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3737 if (Record.size() != 2) {
3738 Error("invalid pragma ms_struct record");
3739 return Failure;
3740 }
3741 PragmaMSPointersToMembersState = Record[0];
3742 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3743 break;
3744
Nico Weber72889432014-09-06 01:25:55 +00003745 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3746 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3747 UnusedLocalTypedefNameCandidates.push_back(
3748 getGlobalDeclID(F, Record[I]));
3749 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003750
3751 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3752 if (Record.size() != 1) {
3753 Error("invalid cuda pragma options record");
3754 return Failure;
3755 }
3756 ForceCUDAHostDeviceDepth = Record[0];
3757 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003758
3759 case PACK_PRAGMA_OPTIONS: {
3760 if (Record.size() < 3) {
3761 Error("invalid pragma pack record");
3762 return Failure;
3763 }
3764 PragmaPackCurrentValue = Record[0];
3765 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3766 unsigned NumStackEntries = Record[2];
3767 unsigned Idx = 3;
3768 // Reset the stack when importing a new module.
3769 PragmaPackStack.clear();
3770 for (unsigned I = 0; I < NumStackEntries; ++I) {
3771 PragmaPackStackEntry Entry;
3772 Entry.Value = Record[Idx++];
3773 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003774 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003775 PragmaPackStrings.push_back(ReadString(Record, Idx));
3776 Entry.SlotLabel = PragmaPackStrings.back();
3777 PragmaPackStack.push_back(Entry);
3778 }
3779 break;
3780 }
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05003781
Melanie Blowerf5360d42020-05-01 10:32:06 -07003782 case FLOAT_CONTROL_PRAGMA_OPTIONS: {
3783 if (Record.size() < 3) {
3784 Error("invalid pragma pack record");
3785 return Failure;
3786 }
3787 FpPragmaCurrentValue = Record[0];
3788 FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
3789 unsigned NumStackEntries = Record[2];
3790 unsigned Idx = 3;
3791 // Reset the stack when importing a new module.
3792 FpPragmaStack.clear();
3793 for (unsigned I = 0; I < NumStackEntries; ++I) {
3794 FpPragmaStackEntry Entry;
3795 Entry.Value = Record[Idx++];
3796 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3797 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
3798 FpPragmaStrings.push_back(ReadString(Record, Idx));
3799 Entry.SlotLabel = FpPragmaStrings.back();
3800 FpPragmaStack.push_back(Entry);
3801 }
3802 break;
3803 }
3804
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05003805 case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
3806 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3807 DeclsToCheckForDeferredDiags.push_back(getGlobalDeclID(F, Record[I]));
3808 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 }
3810 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003811}
3812
Richard Smith37a93df2017-02-18 00:32:02 +00003813void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3814 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3815
3816 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003817 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003818 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3819 F.ModuleOffsetMap = StringRef();
3820
3821 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3822 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3823 F.SLocRemap.insert(std::make_pair(0U, 0));
3824 F.SLocRemap.insert(std::make_pair(2U, 1));
3825 }
3826
3827 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003828 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003829 RemapBuilder SLocRemap(F.SLocRemap);
3830 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3831 RemapBuilder MacroRemap(F.MacroRemap);
3832 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3833 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3834 RemapBuilder SelectorRemap(F.SelectorRemap);
3835 RemapBuilder DeclRemap(F.DeclRemap);
3836 RemapBuilder TypeRemap(F.TypeRemap);
3837
3838 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003839 // FIXME: Looking up dependency modules by filename is horrible. Let's
3840 // start fixing this with prebuilt and explicit modules and see how it
3841 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003842 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003843 ModuleKind Kind = static_cast<ModuleKind>(
3844 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003845 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3846 StringRef Name = StringRef((const char*)Data, Len);
3847 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003848 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3849 ? ModuleMgr.lookupByModuleName(Name)
3850 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003851 if (!OM) {
3852 std::string Msg =
3853 "SourceLocation remap refers to unknown module, cannot find ";
Benjamin Krameradcd0262020-01-28 20:23:46 +01003854 Msg.append(std::string(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003855 Error(Msg);
3856 return;
3857 }
3858
3859 uint32_t SLocOffset =
3860 endian::readNext<uint32_t, little, unaligned>(Data);
3861 uint32_t IdentifierIDOffset =
3862 endian::readNext<uint32_t, little, unaligned>(Data);
3863 uint32_t MacroIDOffset =
3864 endian::readNext<uint32_t, little, unaligned>(Data);
3865 uint32_t PreprocessedEntityIDOffset =
3866 endian::readNext<uint32_t, little, unaligned>(Data);
3867 uint32_t SubmoduleIDOffset =
3868 endian::readNext<uint32_t, little, unaligned>(Data);
3869 uint32_t SelectorIDOffset =
3870 endian::readNext<uint32_t, little, unaligned>(Data);
3871 uint32_t DeclIDOffset =
3872 endian::readNext<uint32_t, little, unaligned>(Data);
3873 uint32_t TypeIndexOffset =
3874 endian::readNext<uint32_t, little, unaligned>(Data);
3875
3876 uint32_t None = std::numeric_limits<uint32_t>::max();
3877
3878 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3879 RemapBuilder &Remap) {
3880 if (Offset != None)
3881 Remap.insert(std::make_pair(Offset,
3882 static_cast<int>(BaseOffset - Offset)));
3883 };
3884 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3885 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3886 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3887 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3888 PreprocessedEntityRemap);
3889 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3890 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3891 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3892 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3893
3894 // Global -> local mappings.
3895 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3896 }
3897}
3898
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003899ASTReader::ASTReadResult
3900ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3901 const ModuleFile *ImportedBy,
3902 unsigned ClientLoadCapabilities) {
3903 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003904 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003905
3906 // Try to resolve ModuleName in the current header search context and
3907 // verify that it is found in the same module map file as we saved. If the
3908 // top-level AST file is a main file, skip this check because there is no
3909 // usable header search context.
3910 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003911 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003912 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003913 // An implicitly-loaded module file should have its module listed in some
3914 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003915 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003916 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3917 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003918 // Don't emit module relocation error if we have -fno-validate-pch
3919 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003920 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003921 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003922 // This module was defined by an imported (explicit) module.
3923 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3924 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003925 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003926 // This module was built with a different module map.
3927 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003928 << F.ModuleName << F.FileName
3929 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3930 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003931 // In case it was imported by a PCH, there's a chance the user is
3932 // just missing to include the search path to the directory containing
3933 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003934 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003935 Diag(diag::note_imported_by_pch_module_not_found)
3936 << llvm::sys::path::parent_path(F.ModuleMapPath);
3937 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003938 }
3939 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003940 }
3941
Richard Smithe842a472014-10-22 02:05:46 +00003942 assert(M->Name == F.ModuleName && "found module with different name");
3943
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003944 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003945 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3946 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003947 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003948 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3949 "top-level import should be verified");
3950 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003951 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3952 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003953 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3954 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003955 return OutOfDate;
3956 }
3957
3958 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3959 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3960 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003961 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003962 auto F = FileMgr.getFile(Filename, false, false);
3963 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003964 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3965 Error("could not find file '" + Filename +"' referenced by AST file");
3966 return OutOfDate;
3967 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003968 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003969 }
3970
3971 // Check any additional module map files (e.g. module.private.modulemap)
3972 // that are not in the pcm.
3973 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003974 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003975 // Remove files that match
3976 // Note: SmallPtrSet::erase is really remove
3977 if (!AdditionalStoredMaps.erase(ModMap)) {
3978 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3979 Diag(diag::err_module_different_modmap)
3980 << F.ModuleName << /*new*/0 << ModMap->getName();
3981 return OutOfDate;
3982 }
3983 }
3984 }
3985
3986 // Check any additional module map files that are in the pcm, but not
3987 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003988 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003989 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3990 Diag(diag::err_module_different_modmap)
3991 << F.ModuleName << /*not new*/1 << ModMap->getName();
3992 return OutOfDate;
3993 }
3994 }
3995
3996 if (Listener)
3997 Listener->ReadModuleMapFile(F.ModuleMapPath);
3998 return Success;
3999}
4000
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004001/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00004002static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
4003 // Find the entry for this selector in the method pool.
4004 Sema::GlobalMethodPool::iterator Known
4005 = S.MethodPool.find(Method->getSelector());
4006 if (Known == S.MethodPool.end())
4007 return;
4008
4009 // Retrieve the appropriate method list.
4010 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
4011 : Known->second.second;
4012 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00004013 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00004014 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00004015 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00004016 Found = true;
4017 } else {
4018 // Keep searching.
4019 continue;
4020 }
4021 }
4022
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00004023 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00004024 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00004025 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00004026 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00004027 }
4028}
4029
Richard Smithde711422015-04-23 21:20:19 +00004030void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00004031 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00004032 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00004033 bool wasHidden = D->isHidden();
4034 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00004035
Vedant Kumar48b4f762018-04-14 01:40:48 +00004036 if (wasHidden && SemaObj) {
4037 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00004038 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004039 }
4040 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 }
4042}
4043
Richard Smith49f906a2014-03-01 00:08:04 +00004044void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004045 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004046 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004048 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004049 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004051 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00004052
4053 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004054 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 // there is nothing more to do.
4056 continue;
4057 }
Richard Smith49f906a2014-03-01 00:08:04 +00004058
Richard Smith6bc75022020-04-17 20:25:15 -07004059 if (Mod->isUnimportable()) {
4060 // Modules that aren't importable cannot be made visible.
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 continue;
4062 }
4063
4064 // Update the module's name visibility.
4065 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00004066
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 // If we've already deserialized any names from this module,
4068 // mark them as visible.
4069 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4070 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00004071 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00004073 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00004074 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4075 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00004076 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00004077
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004079 SmallVector<Module *, 16> Exports;
4080 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004081 for (SmallVectorImpl<Module *>::iterator
4082 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4083 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00004084 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004085 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004087 }
4088}
4089
Richard Smith6561f922016-09-12 21:06:40 +00004090/// We've merged the definition \p MergedDef into the existing definition
4091/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4092/// visible.
4093void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4094 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004095 if (Def->isHidden()) {
4096 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004097 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004098 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004099 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004100 getContext().mergeDefinitionIntoModule(
4101 Def, MergedDef->getImportedOwningModule(),
4102 /*NotifyListeners*/ false);
4103 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004104 }
Richard Smith6561f922016-09-12 21:06:40 +00004105 }
4106}
4107
Douglas Gregore060e572013-01-25 01:03:03 +00004108bool ASTReader::loadGlobalIndex() {
4109 if (GlobalIndex)
4110 return false;
4111
4112 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004113 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004114 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004115
Douglas Gregore060e572013-01-25 01:03:03 +00004116 // Try to load the global index.
4117 TriedLoadingGlobalIndex = true;
4118 StringRef ModuleCachePath
4119 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004120 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4121 GlobalModuleIndex::readIndex(ModuleCachePath);
4122 if (llvm::Error Err = std::move(Result.second)) {
4123 assert(!Result.first);
4124 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004125 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004126 }
Douglas Gregore060e572013-01-25 01:03:03 +00004127
4128 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004129 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004130 return false;
4131}
4132
4133bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004134 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004135 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4136}
4137
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004138static void updateModuleTimestamp(ModuleFile &MF) {
4139 // Overwrite the timestamp file contents so that file's mtime changes.
4140 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004141 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004142 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004143 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004144 return;
4145 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004146 OS.close();
4147 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004148}
4149
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004150/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004151/// cursor into the start of the given block ID, returning false on success and
4152/// true on failure.
4153static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004154 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004155 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4156 if (!MaybeEntry) {
4157 // FIXME this drops errors on the floor.
4158 consumeError(MaybeEntry.takeError());
4159 return true;
4160 }
4161 llvm::BitstreamEntry Entry = MaybeEntry.get();
4162
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004163 switch (Entry.Kind) {
4164 case llvm::BitstreamEntry::Error:
4165 case llvm::BitstreamEntry::EndBlock:
4166 return true;
4167
4168 case llvm::BitstreamEntry::Record:
4169 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004170 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4171 break;
4172 else {
4173 // FIXME this drops errors on the floor.
4174 consumeError(Skipped.takeError());
4175 return true;
4176 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004177
4178 case llvm::BitstreamEntry::SubBlock:
4179 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004180 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4181 // FIXME this drops the error on the floor.
4182 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004183 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004184 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004185 // Found it!
4186 return false;
4187 }
4188
JF Bastien0e828952019-06-26 19:50:12 +00004189 if (llvm::Error Err = Cursor.SkipBlock()) {
4190 // FIXME this drops the error on the floor.
4191 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004192 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004193 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004194 }
4195 }
4196}
4197
Benjamin Kramer0772c422016-02-13 13:42:54 +00004198ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 ModuleKind Type,
4200 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004201 unsigned ClientLoadCapabilities,
4202 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004203 llvm::SaveAndRestore<SourceLocation>
4204 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4205
Richard Smithd1c46742014-04-30 02:24:17 +00004206 // Defer any pending actions until we get to the end of reading the AST file.
4207 Deserializing AnASTFile(this);
4208
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004210 unsigned PreviousGeneration = 0;
4211 if (ContextObj)
4212 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004213
4214 unsigned NumModules = ModuleMgr.size();
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004215 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4216 assert(ReadResult && "expected to return error");
Duncan P. N. Exon Smith8e9e4332019-11-10 10:31:03 -08004217 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004218 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004219 ? &PP.getHeaderSearchInfo().getModuleMap()
4220 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004221
4222 // If we find that any modules are unusable, the global index is going
4223 // to be out-of-date. Just remove it.
4224 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004225 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 return ReadResult;
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004227 };
4228
4229 SmallVector<ImportedModule, 4> Loaded;
4230 switch (ASTReadResult ReadResult =
4231 ReadASTCore(FileName, Type, ImportLoc,
4232 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4233 ASTFileSignature(), ClientLoadCapabilities)) {
4234 case Failure:
4235 case Missing:
4236 case OutOfDate:
4237 case VersionMismatch:
4238 case ConfigurationMismatch:
4239 case HadErrors:
4240 return removeModulesAndReturn(ReadResult);
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 case Success:
4242 break;
4243 }
4244
4245 // Here comes stuff that we only do once the entire chain is loaded.
4246
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004247 // Load the AST blocks of all of the modules that we loaded. We can still
4248 // hit errors parsing the ASTs at this point.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004249 for (ImportedModule &M : Loaded) {
4250 ModuleFile &F = *M.Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004251
4252 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004253 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004254 return removeModulesAndReturn(Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00004255
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08004256 // The AST block should always have a definition for the main module.
4257 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4258 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4259 return removeModulesAndReturn(Failure);
4260 }
4261
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004262 // Read the extension blocks.
4263 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4264 if (ASTReadResult Result = ReadExtensionBlock(F))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004265 return removeModulesAndReturn(Result);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004266 }
4267
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004268 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004269 // bits of all files we've seen.
4270 F.GlobalBitOffset = TotalModulesSizeInBits;
4271 TotalModulesSizeInBits += F.SizeInBits;
4272 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004273 }
4274
4275 // Preload source locations and interesting indentifiers.
4276 for (ImportedModule &M : Loaded) {
4277 ModuleFile &F = *M.Mod;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004278
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004280 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4281 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004282 // Load it through the SourceManager and don't call ReadSLocEntry()
4283 // directly because the entry may have already been loaded in which case
4284 // calling ReadSLocEntry() directly would trigger an assertion in
4285 // SourceManager.
4286 SourceMgr.getLoadedSLocEntryByID(Index);
4287 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004288
Richard Smithea741482017-05-01 22:10:47 +00004289 // Map the original source file ID into the ID space of the current
4290 // compilation.
4291 if (F.OriginalSourceFileID.isValid()) {
4292 F.OriginalSourceFileID = FileID::get(
4293 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4294 }
4295
Richard Smith33e0f7e2015-07-22 02:08:40 +00004296 // Preload all the pending interesting identifiers by marking them out of
4297 // date.
4298 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004299 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004300 F.IdentifierTableData + Offset);
4301
4302 ASTIdentifierLookupTrait Trait(*this, F);
4303 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4304 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004305 auto &II = PP.getIdentifierTable().getOwn(Key);
4306 II.setOutOfDate(true);
4307
4308 // Mark this identifier as being from an AST file so that we can track
4309 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004310 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004311
4312 // Associate the ID with the identifier so that the writer can reuse it.
4313 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4314 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004315 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 }
4317
Douglas Gregor603cd862013-03-22 18:50:14 +00004318 // Setup the import locations and notify the module manager that we've
4319 // committed to these module files.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004320 for (ImportedModule &M : Loaded) {
4321 ModuleFile &F = *M.Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004322
4323 ModuleMgr.moduleFileAccepted(&F);
4324
4325 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004326 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004327 // FIXME: We assume that locations from PCH / preamble do not need
4328 // any translation.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004329 if (!M.ImportedBy)
4330 F.ImportLoc = M.ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 else
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004332 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004333 }
4334
Richard Smithdbafb6c2017-06-29 23:23:46 +00004335 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004336 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4337 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004338 // Mark all of the identifiers in the identifier table as being out of date,
4339 // so that various accessors know to check the loaded modules when the
4340 // identifier is used.
4341 //
4342 // For C++ modules, we don't need information on many identifiers (just
4343 // those that provide macros or are poisoned), so we mark all of
4344 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004345 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4346 IdEnd = PP.getIdentifierTable().end();
4347 Id != IdEnd; ++Id)
4348 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004349 }
Manman Rena0f31a02016-04-29 19:04:05 +00004350 // Mark selectors as out of date.
4351 for (auto Sel : SelectorGeneration)
4352 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004353
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004355 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4356 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4358 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004359
4360 switch (Unresolved.Kind) {
4361 case UnresolvedModuleRef::Conflict:
4362 if (ResolvedMod) {
4363 Module::Conflict Conflict;
4364 Conflict.Other = ResolvedMod;
4365 Conflict.Message = Unresolved.String.str();
4366 Unresolved.Mod->Conflicts.push_back(Conflict);
4367 }
4368 continue;
4369
4370 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004372 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374
Douglas Gregorfb912652013-03-20 21:10:35 +00004375 case UnresolvedModuleRef::Export:
4376 if (ResolvedMod || Unresolved.IsWildcard)
4377 Unresolved.Mod->Exports.push_back(
4378 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4379 continue;
4380 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004382 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004383
Graydon Hoaree7196af2016-12-09 21:45:49 +00004384 if (Imported)
4385 Imported->append(ImportedModules.begin(),
4386 ImportedModules.end());
4387
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004388 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4389 // Might be unnecessary as use declarations are only used to build the
4390 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004391
Richard Smithdbafb6c2017-06-29 23:23:46 +00004392 if (ContextObj)
4393 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004394
Richard Smith3d8e97e2013-10-18 06:54:39 +00004395 if (SemaObj)
4396 UpdateSema();
4397
Guy Benyei11169dd2012-12-18 14:30:41 +00004398 if (DeserializationListener)
4399 DeserializationListener->ReaderInitialized(this);
4400
4401 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004402 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004403 // If this AST file is a precompiled preamble, then set the
4404 // preamble file ID of the source manager to the file source file
4405 // from which the preamble was built.
4406 if (Type == MK_Preamble) {
4407 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4408 } else if (Type == MK_MainFile) {
4409 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4410 }
4411 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004412
Guy Benyei11169dd2012-12-18 14:30:41 +00004413 // For any Objective-C class definitions we have already loaded, make sure
4414 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004415 if (ContextObj) {
4416 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4417 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4418 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004419 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004420 }
4421 }
Douglas Gregore060e572013-01-25 01:03:03 +00004422
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004423 if (PP.getHeaderSearchInfo()
4424 .getHeaderSearchOpts()
4425 .ModulesValidateOncePerBuildSession) {
4426 // Now we are certain that the module and all modules it depends on are
4427 // up to date. Create or update timestamp files for modules that are
4428 // located in the module cache (not for PCH files that could be anywhere
4429 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004430 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4431 ImportedModule &M = Loaded[I];
4432 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004433 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004434 }
4435 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004436 }
4437
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 return Success;
4439}
4440
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004441static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004442
JF Bastien0e828952019-06-26 19:50:12 +00004443/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4444static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4445 // FIXME checking magic headers is done in other places such as
4446 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4447 // always done the same. Unify it all with a helper.
4448 if (!Stream.canSkipToPos(4))
4449 return llvm::createStringError(std::errc::illegal_byte_sequence,
4450 "file too small to contain AST file magic");
4451 for (unsigned C : {'C', 'P', 'C', 'H'})
4452 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4453 if (Res.get() != C)
4454 return llvm::createStringError(
4455 std::errc::illegal_byte_sequence,
4456 "file doesn't start with AST file magic");
4457 } else
4458 return Res.takeError();
4459 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004460}
4461
Richard Smith0f99d6a2015-08-09 08:48:41 +00004462static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4463 switch (Kind) {
4464 case MK_PCH:
4465 return 0; // PCH
4466 case MK_ImplicitModule:
4467 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004468 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004469 return 1; // module
4470 case MK_MainFile:
4471 case MK_Preamble:
4472 return 2; // main source file
4473 }
4474 llvm_unreachable("unknown module kind");
4475}
4476
Guy Benyei11169dd2012-12-18 14:30:41 +00004477ASTReader::ASTReadResult
4478ASTReader::ReadASTCore(StringRef FileName,
4479 ModuleKind Type,
4480 SourceLocation ImportLoc,
4481 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004482 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004483 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004484 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004485 unsigned ClientLoadCapabilities) {
4486 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004488 ModuleManager::AddModuleResult AddResult
4489 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004490 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004491 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004492 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004493
Douglas Gregor7029ce12013-03-19 00:28:20 +00004494 switch (AddResult) {
4495 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004496 Diag(diag::remark_module_import)
4497 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4498 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004499 return Success;
4500
4501 case ModuleManager::NewlyLoaded:
4502 // Load module file below.
4503 break;
4504
4505 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004506 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004507 // it.
4508 if (ClientLoadCapabilities & ARR_Missing)
4509 return Missing;
4510
4511 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004512 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004513 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004514 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004515 return Failure;
4516
4517 case ModuleManager::OutOfDate:
4518 // We couldn't load the module file because it is out-of-date. If the
4519 // client can handle out-of-date, return it.
4520 if (ClientLoadCapabilities & ARR_OutOfDate)
4521 return OutOfDate;
4522
4523 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004524 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004525 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004526 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 return Failure;
4528 }
4529
Douglas Gregor7029ce12013-03-19 00:28:20 +00004530 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004531
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004532 bool ShouldFinalizePCM = false;
4533 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4534 auto &MC = getModuleManager().getModuleCache();
4535 if (ShouldFinalizePCM)
4536 MC.finalizePCM(FileName);
4537 else
Rumeet Dhindsa57a2eaf2020-03-10 10:59:26 -07004538 MC.tryToDropPCM(FileName);
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004539 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004540 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004541 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004542 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004543 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004544
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004546 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4547 Diag(diag::err_module_file_invalid)
4548 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004549 return Failure;
4550 }
4551
4552 // This is used for compatibility with older PCH formats.
4553 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004554 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004555 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4556 if (!MaybeEntry) {
4557 Error(MaybeEntry.takeError());
4558 return Failure;
4559 }
4560 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004561
Chris Lattnerefa77172013-01-20 00:00:22 +00004562 switch (Entry.Kind) {
4563 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004564 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004565 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 Error("invalid record at top-level of AST file");
4567 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004568
Chris Lattnerefa77172013-01-20 00:00:22 +00004569 case llvm::BitstreamEntry::SubBlock:
4570 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004571 }
4572
Chris Lattnerefa77172013-01-20 00:00:22 +00004573 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 case CONTROL_BLOCK_ID:
4575 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004576 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004578 // Check that we didn't try to load a non-module AST file as a module.
4579 //
4580 // FIXME: Should we also perform the converse check? Loading a module as
4581 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004582 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4583 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004584 F.ModuleName.empty()) {
4585 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4586 if (Result != OutOfDate ||
4587 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4588 Diag(diag::err_module_file_not_module) << FileName;
4589 return Result;
4590 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 break;
4592
4593 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004594 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004595 case OutOfDate: return OutOfDate;
4596 case VersionMismatch: return VersionMismatch;
4597 case ConfigurationMismatch: return ConfigurationMismatch;
4598 case HadErrors: return HadErrors;
4599 }
4600 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004601
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 case AST_BLOCK_ID:
4603 if (!HaveReadControlBlock) {
4604 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004605 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 return VersionMismatch;
4607 }
4608
4609 // Record that we've loaded this module.
4610 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004611 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 return Success;
4613
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004614 case UNHASHED_CONTROL_BLOCK_ID:
4615 // This block is handled using look-ahead during ReadControlBlock. We
4616 // shouldn't get here!
4617 Error("malformed block record in AST file");
4618 return Failure;
4619
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 default:
JF Bastien0e828952019-06-26 19:50:12 +00004621 if (llvm::Error Err = Stream.SkipBlock()) {
4622 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 return Failure;
4624 }
4625 break;
4626 }
4627 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004628
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004629 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004630}
4631
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004632ASTReader::ASTReadResult
4633ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4634 unsigned ClientLoadCapabilities) {
4635 const HeaderSearchOptions &HSOpts =
4636 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4637 bool AllowCompatibleConfigurationMismatch =
4638 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4639
4640 ASTReadResult Result = readUnhashedControlBlockImpl(
4641 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4642 Listener.get(),
4643 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4644
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004645 // If F was directly imported by another module, it's implicitly validated by
4646 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004647 if (DisableValidation || WasImportedBy ||
4648 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4649 return Success;
4650
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004651 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004652 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004653 return Failure;
4654 }
4655
4656 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004657 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004658 // with it; we can only load a single version of each module.
4659 //
4660 // This can happen when a module is imported in two contexts: in one, as a
4661 // user module; in another, as a system module (due to an import from
4662 // another module marked with the [system] flag). It usually indicates a
4663 // bug in the module map: this module should also be marked with [system].
4664 //
4665 // If -Wno-system-headers (the default), and the first import is as a
4666 // system module, then validation will fail during the as-user import,
4667 // since -Werror flags won't have been validated. However, it's reasonable
4668 // to treat this consistently as a system module.
4669 //
4670 // If -Wsystem-headers, the PCM on disk was built with
4671 // -Wno-system-headers, and the first import is as a user module, then
4672 // validation will fail during the as-system import since the PCM on disk
4673 // doesn't guarantee that -Werror was respected. However, the -Werror
4674 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004675 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004676 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4677 return Success;
4678 }
4679 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004680
4681 return Result;
4682}
4683
4684ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4685 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4686 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4687 bool ValidateDiagnosticOptions) {
4688 // Initialize a stream.
4689 BitstreamCursor Stream(StreamData);
4690
4691 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004692 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4693 // FIXME this drops the error on the floor.
4694 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004695 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004696 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004697
4698 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4699 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4700 return Failure;
4701
4702 // Read all of the records in the options block.
4703 RecordData Record;
4704 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004705 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004706 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4707 if (!MaybeEntry) {
4708 // FIXME this drops the error on the floor.
4709 consumeError(MaybeEntry.takeError());
4710 return Failure;
4711 }
4712 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004713
4714 switch (Entry.Kind) {
4715 case llvm::BitstreamEntry::Error:
4716 case llvm::BitstreamEntry::SubBlock:
4717 return Failure;
4718
4719 case llvm::BitstreamEntry::EndBlock:
4720 return Result;
4721
4722 case llvm::BitstreamEntry::Record:
4723 // The interesting case.
4724 break;
4725 }
4726
4727 // Read and process a record.
4728 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004729 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4730 if (!MaybeRecordType) {
4731 // FIXME this drops the error.
4732 return Failure;
4733 }
4734 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004735 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004736 if (F)
4737 std::copy(Record.begin(), Record.end(), F->Signature.data());
4738 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004739 case DIAGNOSTIC_OPTIONS: {
4740 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4741 if (Listener && ValidateDiagnosticOptions &&
4742 !AllowCompatibleConfigurationMismatch &&
4743 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004744 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004745 break;
4746 }
4747 case DIAG_PRAGMA_MAPPINGS:
4748 if (!F)
4749 break;
4750 if (F->PragmaDiagMappings.empty())
4751 F->PragmaDiagMappings.swap(Record);
4752 else
4753 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4754 Record.begin(), Record.end());
4755 break;
4756 }
4757 }
4758}
4759
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004760/// Parse a record and blob containing module file extension metadata.
4761static bool parseModuleFileExtensionMetadata(
4762 const SmallVectorImpl<uint64_t> &Record,
4763 StringRef Blob,
4764 ModuleFileExtensionMetadata &Metadata) {
4765 if (Record.size() < 4) return true;
4766
4767 Metadata.MajorVersion = Record[0];
4768 Metadata.MinorVersion = Record[1];
4769
4770 unsigned BlockNameLen = Record[2];
4771 unsigned UserInfoLen = Record[3];
4772
4773 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4774
4775 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4776 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4777 Blob.data() + BlockNameLen + UserInfoLen);
4778 return false;
4779}
4780
4781ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4782 BitstreamCursor &Stream = F.Stream;
4783
4784 RecordData Record;
4785 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004786 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4787 if (!MaybeEntry) {
4788 Error(MaybeEntry.takeError());
4789 return Failure;
4790 }
4791 llvm::BitstreamEntry Entry = MaybeEntry.get();
4792
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004793 switch (Entry.Kind) {
4794 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004795 if (llvm::Error Err = Stream.SkipBlock()) {
4796 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004797 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004798 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004799 continue;
4800
4801 case llvm::BitstreamEntry::EndBlock:
4802 return Success;
4803
4804 case llvm::BitstreamEntry::Error:
4805 return HadErrors;
4806
4807 case llvm::BitstreamEntry::Record:
4808 break;
4809 }
4810
4811 Record.clear();
4812 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004813 Expected<unsigned> MaybeRecCode =
4814 Stream.readRecord(Entry.ID, Record, &Blob);
4815 if (!MaybeRecCode) {
4816 Error(MaybeRecCode.takeError());
4817 return Failure;
4818 }
4819 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004820 case EXTENSION_METADATA: {
4821 ModuleFileExtensionMetadata Metadata;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004822 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4823 Error("malformed EXTENSION_METADATA in AST file");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004824 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004825 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004826
4827 // Find a module file extension with this block name.
4828 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4829 if (Known == ModuleFileExtensions.end()) break;
4830
4831 // Form a reader.
4832 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4833 F, Stream)) {
4834 F.ExtensionReaders.push_back(std::move(Reader));
4835 }
4836
4837 break;
4838 }
4839 }
4840 }
4841
4842 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004843}
4844
Richard Smitha7e2cc62015-05-01 01:53:09 +00004845void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004846 assert(ContextObj && "no context to initialize");
4847 ASTContext &Context = *ContextObj;
4848
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 // If there's a listener, notify them that we "read" the translation unit.
4850 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004851 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 Context.getTranslationUnitDecl());
4853
Guy Benyei11169dd2012-12-18 14:30:41 +00004854 // FIXME: Find a better way to deal with collisions between these
4855 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004856
Guy Benyei11169dd2012-12-18 14:30:41 +00004857 // Load the special types.
4858 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4859 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4860 if (!Context.CFConstantStringTypeDecl)
4861 Context.setCFConstantStringType(GetType(String));
4862 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004863
Guy Benyei11169dd2012-12-18 14:30:41 +00004864 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4865 QualType FileType = GetType(File);
4866 if (FileType.isNull()) {
4867 Error("FILE type is NULL");
4868 return;
4869 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004870
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004872 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 Context.setFILEDecl(Typedef->getDecl());
4874 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004875 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 if (!Tag) {
4877 Error("Invalid FILE type in AST file");
4878 return;
4879 }
4880 Context.setFILEDecl(Tag->getDecl());
4881 }
4882 }
4883 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004884
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4886 QualType Jmp_bufType = GetType(Jmp_buf);
4887 if (Jmp_bufType.isNull()) {
4888 Error("jmp_buf type is NULL");
4889 return;
4890 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004891
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004893 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 Context.setjmp_bufDecl(Typedef->getDecl());
4895 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004896 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 if (!Tag) {
4898 Error("Invalid jmp_buf type in AST file");
4899 return;
4900 }
4901 Context.setjmp_bufDecl(Tag->getDecl());
4902 }
4903 }
4904 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004905
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4907 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4908 if (Sigjmp_bufType.isNull()) {
4909 Error("sigjmp_buf type is NULL");
4910 return;
4911 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004912
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004914 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 Context.setsigjmp_bufDecl(Typedef->getDecl());
4916 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004917 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004918 assert(Tag && "Invalid sigjmp_buf type in AST file");
4919 Context.setsigjmp_bufDecl(Tag->getDecl());
4920 }
4921 }
4922 }
4923
4924 if (unsigned ObjCIdRedef
4925 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4926 if (Context.ObjCIdRedefinitionType.isNull())
4927 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4928 }
4929
4930 if (unsigned ObjCClassRedef
4931 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4932 if (Context.ObjCClassRedefinitionType.isNull())
4933 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4934 }
4935
4936 if (unsigned ObjCSelRedef
4937 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4938 if (Context.ObjCSelRedefinitionType.isNull())
4939 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4940 }
4941
4942 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4943 QualType Ucontext_tType = GetType(Ucontext_t);
4944 if (Ucontext_tType.isNull()) {
4945 Error("ucontext_t type is NULL");
4946 return;
4947 }
4948
4949 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004950 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004951 Context.setucontext_tDecl(Typedef->getDecl());
4952 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004953 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 assert(Tag && "Invalid ucontext_t type in AST file");
4955 Context.setucontext_tDecl(Tag->getDecl());
4956 }
4957 }
4958 }
4959 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004960
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4962
4963 // If there were any CUDA special declarations, deserialize them.
4964 if (!CUDASpecialDeclRefs.empty()) {
4965 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4966 Context.setcudaConfigureCallDecl(
4967 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4968 }
Richard Smith56be7542014-03-21 00:33:59 +00004969
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004971 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004972 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004973 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004974 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004975 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004976 if (Import.ImportLoc.isValid())
4977 PP.makeModuleVisible(Imported, Import.ImportLoc);
4978 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004979 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004980 }
4981 ImportedModules.clear();
4982}
4983
4984void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004985 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004986}
4987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004988/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004989/// else returns 0.
4990static ASTFileSignature readASTFileSignature(StringRef PCH) {
4991 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004992 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4993 // FIXME this drops the error on the floor.
4994 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004995 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004996 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004997
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004998 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4999 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00005000 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00005001
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005002 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00005003 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005004 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005005 Expected<llvm::BitstreamEntry> MaybeEntry =
5006 Stream.advanceSkippingSubblocks();
5007 if (!MaybeEntry) {
5008 // FIXME this drops the error on the floor.
5009 consumeError(MaybeEntry.takeError());
5010 return ASTFileSignature();
5011 }
5012 llvm::BitstreamEntry Entry = MaybeEntry.get();
5013
Simon Pilgrim0b33f112016-11-16 16:11:08 +00005014 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005015 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00005016
5017 Record.clear();
5018 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005019 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5020 if (!MaybeRecord) {
5021 // FIXME this drops the error on the floor.
5022 consumeError(MaybeRecord.takeError());
5023 return ASTFileSignature();
5024 }
5025 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005026 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
5027 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00005028 }
5029}
5030
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005031/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00005032/// directly from the AST file, without actually loading the AST
5033/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005034std::string ASTReader::getOriginalSourceFile(
5035 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005036 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005037 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00005038 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00005040 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5041 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00005042 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 }
5044
5045 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00005046 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00005047
5048 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005049 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5050 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005051 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005053
Chris Lattnere7b154b2013-01-19 21:39:22 +00005054 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005055 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005056 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005057 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00005058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005059
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005060 // Scan for ORIGINAL_FILE inside the control block.
5061 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005062 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005063 Expected<llvm::BitstreamEntry> MaybeEntry =
5064 Stream.advanceSkippingSubblocks();
5065 if (!MaybeEntry) {
5066 // FIXME this drops errors on the floor.
5067 consumeError(MaybeEntry.takeError());
5068 return std::string();
5069 }
5070 llvm::BitstreamEntry Entry = MaybeEntry.get();
5071
Chris Lattnere7b154b2013-01-19 21:39:22 +00005072 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005073 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005074
Chris Lattnere7b154b2013-01-19 21:39:22 +00005075 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5076 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005077 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005079
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005081 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005082 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5083 if (!MaybeRecord) {
5084 // FIXME this drops the errors on the floor.
5085 consumeError(MaybeRecord.takeError());
5086 return std::string();
5087 }
5088 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00005089 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005091}
5092
5093namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005094
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 class SimplePCHValidator : public ASTReaderListener {
5096 const LangOptions &ExistingLangOpts;
5097 const TargetOptions &ExistingTargetOpts;
5098 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005099 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00005100 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005101
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 public:
5103 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5104 const TargetOptions &ExistingTargetOpts,
5105 const PreprocessorOptions &ExistingPPOpts,
Benjamin Krameradcd0262020-01-28 20:23:46 +01005106 StringRef ExistingModuleCachePath, FileManager &FileMgr)
5107 : ExistingLangOpts(ExistingLangOpts),
5108 ExistingTargetOpts(ExistingTargetOpts),
5109 ExistingPPOpts(ExistingPPOpts),
5110 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005111
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005112 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5113 bool AllowCompatibleDifferences) override {
5114 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5115 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005116 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005117
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005118 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5119 bool AllowCompatibleDifferences) override {
5120 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5121 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005122 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005123
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005124 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5125 StringRef SpecificModuleCachePath,
5126 bool Complain) override {
5127 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5128 ExistingModuleCachePath,
5129 nullptr, ExistingLangOpts);
5130 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005131
Craig Topper3e89dfe2014-03-13 02:13:41 +00005132 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5133 bool Complain,
5134 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005135 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005136 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 }
5138 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005139
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005140} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005141
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005142bool ASTReader::readASTFileControlBlock(
5143 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005144 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005145 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005146 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005148 // FIXME: This allows use of the VFS; we do not allow use of the
5149 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005150 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 if (!Buffer) {
5152 return true;
5153 }
5154
5155 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005156 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5157 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005158
5159 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005160 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5161 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005162 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005163 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005164
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005165 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005166 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005167 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005168
5169 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005170 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005171 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005172 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005173
Guy Benyei11169dd2012-12-18 14:30:41 +00005174 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005175 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005176 bool DoneWithControlBlock = false;
5177 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005178 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5179 if (!MaybeEntry) {
5180 // FIXME this drops the error on the floor.
5181 consumeError(MaybeEntry.takeError());
5182 return true;
5183 }
5184 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005185
5186 switch (Entry.Kind) {
5187 case llvm::BitstreamEntry::SubBlock: {
5188 switch (Entry.ID) {
5189 case OPTIONS_BLOCK_ID: {
5190 std::string IgnoredSuggestedPredefines;
5191 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5192 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005193 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005194 return true;
5195 break;
5196 }
5197
5198 case INPUT_FILES_BLOCK_ID:
5199 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005200 if (llvm::Error Err = Stream.SkipBlock()) {
5201 // FIXME this drops the error on the floor.
5202 consumeError(std::move(Err));
5203 return true;
5204 }
5205 if (NeedsInputFiles &&
5206 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005207 return true;
5208 break;
5209
5210 default:
JF Bastien0e828952019-06-26 19:50:12 +00005211 if (llvm::Error Err = Stream.SkipBlock()) {
5212 // FIXME this drops the error on the floor.
5213 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005214 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005215 }
Richard Smith0516b182015-09-08 19:40:14 +00005216 break;
5217 }
5218
5219 continue;
5220 }
5221
5222 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005223 DoneWithControlBlock = true;
5224 break;
Richard Smith0516b182015-09-08 19:40:14 +00005225
5226 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005227 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005228
5229 case llvm::BitstreamEntry::Record:
5230 break;
5231 }
5232
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005233 if (DoneWithControlBlock) break;
5234
Guy Benyei11169dd2012-12-18 14:30:41 +00005235 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005236 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005237 Expected<unsigned> MaybeRecCode =
5238 Stream.readRecord(Entry.ID, Record, &Blob);
5239 if (!MaybeRecCode) {
5240 // FIXME this drops the error.
5241 return Failure;
5242 }
5243 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005244 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005245 if (Record[0] != VERSION_MAJOR)
5246 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005247 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005248 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005249 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005250 case MODULE_NAME:
5251 Listener.ReadModuleName(Blob);
5252 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005253 case MODULE_DIRECTORY:
Benjamin Krameradcd0262020-01-28 20:23:46 +01005254 ModuleDir = std::string(Blob);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005255 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005256 case MODULE_MAP_FILE: {
5257 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005258 auto Path = ReadString(Record, Idx);
5259 ResolveImportedPath(Path, ModuleDir);
5260 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005261 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005262 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005263 case INPUT_FILE_OFFSETS: {
5264 if (!NeedsInputFiles)
5265 break;
5266
5267 unsigned NumInputFiles = Record[0];
5268 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005269 const llvm::support::unaligned_uint64_t *InputFileOffs =
5270 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005271 for (unsigned I = 0; I != NumInputFiles; ++I) {
5272 // Go find this input file.
5273 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005274
5275 if (isSystemFile && !NeedsSystemInputFiles)
5276 break; // the rest are system input files
5277
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005278 BitstreamCursor &Cursor = InputFilesCursor;
5279 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005280 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5281 // FIXME this drops errors on the floor.
5282 consumeError(std::move(Err));
5283 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005284
JF Bastien0e828952019-06-26 19:50:12 +00005285 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5286 if (!MaybeCode) {
5287 // FIXME this drops errors on the floor.
5288 consumeError(MaybeCode.takeError());
5289 }
5290 unsigned Code = MaybeCode.get();
5291
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005292 RecordData Record;
5293 StringRef Blob;
5294 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005295 Expected<unsigned> MaybeRecordType =
5296 Cursor.readRecord(Code, Record, &Blob);
5297 if (!MaybeRecordType) {
5298 // FIXME this drops errors on the floor.
5299 consumeError(MaybeRecordType.takeError());
5300 }
5301 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00005302 case INPUT_FILE_HASH:
5303 break;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005304 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005305 bool Overridden = static_cast<bool>(Record[3]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01005306 std::string Filename = std::string(Blob);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005307 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005308 shouldContinue = Listener.visitInputFile(
5309 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005310 break;
5311 }
5312 if (!shouldContinue)
5313 break;
5314 }
5315 break;
5316 }
5317
Richard Smithd4b230b2014-10-27 23:01:16 +00005318 case IMPORTS: {
5319 if (!NeedsImports)
5320 break;
5321
5322 unsigned Idx = 0, N = Record.size();
5323 while (Idx < N) {
5324 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005325 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5326 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005327 std::string Filename = ReadString(Record, Idx);
5328 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005329 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005330 }
5331 break;
5332 }
5333
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005334 default:
5335 // No other validation to perform.
5336 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005337 }
5338 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005339
5340 // Look for module file extension blocks, if requested.
5341 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005342 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005343 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5344 bool DoneWithExtensionBlock = false;
5345 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005346 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5347 if (!MaybeEntry) {
5348 // FIXME this drops the error.
5349 return true;
5350 }
5351 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005352
JF Bastien0e828952019-06-26 19:50:12 +00005353 switch (Entry.Kind) {
5354 case llvm::BitstreamEntry::SubBlock:
5355 if (llvm::Error Err = Stream.SkipBlock()) {
5356 // FIXME this drops the error on the floor.
5357 consumeError(std::move(Err));
5358 return true;
5359 }
5360 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005361
JF Bastien0e828952019-06-26 19:50:12 +00005362 case llvm::BitstreamEntry::EndBlock:
5363 DoneWithExtensionBlock = true;
5364 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005365
JF Bastien0e828952019-06-26 19:50:12 +00005366 case llvm::BitstreamEntry::Error:
5367 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005368
JF Bastien0e828952019-06-26 19:50:12 +00005369 case llvm::BitstreamEntry::Record:
5370 break;
5371 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005372
5373 Record.clear();
5374 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005375 Expected<unsigned> MaybeRecCode =
5376 Stream.readRecord(Entry.ID, Record, &Blob);
5377 if (!MaybeRecCode) {
5378 // FIXME this drops the error.
5379 return true;
5380 }
5381 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005382 case EXTENSION_METADATA: {
5383 ModuleFileExtensionMetadata Metadata;
5384 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5385 return true;
5386
5387 Listener.readModuleFileExtension(Metadata);
5388 break;
5389 }
5390 }
5391 }
5392 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005393 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005394 }
5395
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005396 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5397 if (readUnhashedControlBlockImpl(
5398 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5399 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5400 ValidateDiagnosticOptions) != Success)
5401 return true;
5402
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005403 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005404}
5405
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005406bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5407 const PCHContainerReader &PCHContainerRdr,
5408 const LangOptions &LangOpts,
5409 const TargetOptions &TargetOpts,
5410 const PreprocessorOptions &PPOpts,
5411 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005412 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5413 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005414 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005415 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005416 validator,
5417 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005418}
5419
Ben Langmuir2c9af442014-04-10 17:57:43 +00005420ASTReader::ASTReadResult
5421ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005422 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005423 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5424 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005425 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 }
5427
5428 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5429 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005430 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 RecordData Record;
5432 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005433 Expected<llvm::BitstreamEntry> MaybeEntry =
5434 F.Stream.advanceSkippingSubblocks();
5435 if (!MaybeEntry) {
5436 Error(MaybeEntry.takeError());
5437 return Failure;
5438 }
5439 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005440
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005441 switch (Entry.Kind) {
5442 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5443 case llvm::BitstreamEntry::Error:
5444 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005445 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005446 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005447 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005448 case llvm::BitstreamEntry::Record:
5449 // The interesting case.
5450 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005452
Guy Benyei11169dd2012-12-18 14:30:41 +00005453 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005454 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005455 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005456 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5457 if (!MaybeKind) {
5458 Error(MaybeKind.takeError());
5459 return Failure;
5460 }
5461 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005462
5463 if ((Kind == SUBMODULE_METADATA) != First) {
5464 Error("submodule metadata record should be at beginning of block");
5465 return Failure;
5466 }
5467 First = false;
5468
5469 // Submodule information is only valid if we have a current module.
5470 // FIXME: Should we error on these cases?
5471 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5472 Kind != SUBMODULE_DEFINITION)
5473 continue;
5474
5475 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 default: // Default behavior: ignore.
5477 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005478
Richard Smith03478d92014-10-23 22:12:14 +00005479 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005480 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005482 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005483 }
Richard Smith03478d92014-10-23 22:12:14 +00005484
Chris Lattner0e6c9402013-01-20 02:38:54 +00005485 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005486 unsigned Idx = 0;
5487 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5488 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005489 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005490 bool IsFramework = Record[Idx++];
5491 bool IsExplicit = Record[Idx++];
5492 bool IsSystem = Record[Idx++];
5493 bool IsExternC = Record[Idx++];
5494 bool InferSubmodules = Record[Idx++];
5495 bool InferExplicitSubmodules = Record[Idx++];
5496 bool InferExportWildcard = Record[Idx++];
5497 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005498 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005499
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005500 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005501 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005502 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005503
Guy Benyei11169dd2012-12-18 14:30:41 +00005504 // Retrieve this (sub)module from the module map, creating it if
5505 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005506 CurrentModule =
5507 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5508 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005509
5510 // FIXME: set the definition loc for CurrentModule, or call
5511 // ModMap.setInferredModuleAllowedBy()
5512
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5514 if (GlobalIndex >= SubmodulesLoaded.size() ||
5515 SubmodulesLoaded[GlobalIndex]) {
5516 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005517 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005519
Douglas Gregor7029ce12013-03-19 00:28:20 +00005520 if (!ParentModule) {
5521 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005522 // Don't emit module relocation error if we have -fno-validate-pch
5523 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5524 CurFile != F.File) {
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08005525 Error(diag::err_module_file_conflict,
5526 CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5527 F.File->getName());
Ben Langmuir2c9af442014-04-10 17:57:43 +00005528 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005529 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005530 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005531
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08005532 F.DidReadTopLevelSubmodule = true;
Douglas Gregor7029ce12013-03-19 00:28:20 +00005533 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005534 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005535 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005536
Richard Smithdd8b5332017-09-04 05:37:53 +00005537 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005538 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 CurrentModule->IsFromModuleFile = true;
5540 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005541 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005542 CurrentModule->InferSubmodules = InferSubmodules;
5543 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5544 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005545 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005546 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005547 if (DeserializationListener)
5548 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005549
Guy Benyei11169dd2012-12-18 14:30:41 +00005550 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005551
Richard Smith8a3e39a2016-03-28 21:31:09 +00005552 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005553 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005554 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005555 CurrentModule->UnresolvedConflicts.clear();
5556 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005557
5558 // The module is available unless it's missing a requirement; relevant
5559 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5560 // Missing headers that were present when the module was built do not
5561 // make it unavailable -- if we got this far, this must be an explicitly
5562 // imported module file.
5563 CurrentModule->Requirements.clear();
5564 CurrentModule->MissingHeaders.clear();
Richard Smithfc76b4a2020-04-17 16:23:41 -07005565 CurrentModule->IsUnimportable =
5566 ParentModule && ParentModule->IsUnimportable;
5567 CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
Guy Benyei11169dd2012-12-18 14:30:41 +00005568 break;
5569 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005570
Guy Benyei11169dd2012-12-18 14:30:41 +00005571 case SUBMODULE_UMBRELLA_HEADER: {
Benjamin Krameradcd0262020-01-28 20:23:46 +01005572 std::string Filename = std::string(Blob);
Richard Smith2b63d152015-05-16 02:28:53 +00005573 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005574 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005575 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005576 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5577 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005578 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5579 Error("mismatched umbrella headers in submodule");
5580 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005581 }
5582 }
5583 break;
5584 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005585
Richard Smith202210b2014-10-24 20:23:01 +00005586 case SUBMODULE_HEADER:
5587 case SUBMODULE_EXCLUDED_HEADER:
5588 case SUBMODULE_PRIVATE_HEADER:
5589 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005590 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5591 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005592 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005593
Richard Smith202210b2014-10-24 20:23:01 +00005594 case SUBMODULE_TEXTUAL_HEADER:
5595 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5596 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5597 // them here.
5598 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005599
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005600 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005601 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005602 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005603
5604 case SUBMODULE_UMBRELLA_DIR: {
Benjamin Krameradcd0262020-01-28 20:23:46 +01005605 std::string Dirname = std::string(Blob);
Richard Smith2b63d152015-05-16 02:28:53 +00005606 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005607 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005609 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5610 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005611 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5612 Error("mismatched umbrella directories in submodule");
5613 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 }
5615 }
5616 break;
5617 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005618
Guy Benyei11169dd2012-12-18 14:30:41 +00005619 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 F.BaseSubmoduleID = getTotalNumSubmodules();
5621 F.LocalNumSubmodules = Record[0];
5622 unsigned LocalBaseSubmoduleID = Record[1];
5623 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005624 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005625 // module.
5626 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005627
5628 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005629 // module.
5630 F.SubmoduleRemap.insertOrReplace(
5631 std::make_pair(LocalBaseSubmoduleID,
5632 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005633
Ben Langmuir52ca6782014-10-20 16:27:32 +00005634 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 break;
5637 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005638
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005639 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005640 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005641 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005642 Unresolved.File = &F;
5643 Unresolved.Mod = CurrentModule;
5644 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005645 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005646 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005647 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005648 }
5649 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005650
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005651 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005652 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005653 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005654 Unresolved.File = &F;
5655 Unresolved.Mod = CurrentModule;
5656 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005657 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005659 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005660 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005661
5662 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005663 // the parsed, unresolved exports around.
5664 CurrentModule->UnresolvedExports.clear();
5665 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005666
5667 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005668 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5669 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005670 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005671
5672 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005673 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005674 CurrentModule->LinkLibraries.push_back(
Benjamin Krameradcd0262020-01-28 20:23:46 +01005675 Module::LinkLibrary(std::string(Blob), Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005676 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005677
5678 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005679 CurrentModule->ConfigMacros.push_back(Blob.str());
5680 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005681
5682 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005683 UnresolvedModuleRef Unresolved;
5684 Unresolved.File = &F;
5685 Unresolved.Mod = CurrentModule;
5686 Unresolved.ID = Record[0];
5687 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5688 Unresolved.IsWildcard = false;
5689 Unresolved.String = Blob;
5690 UnresolvedModuleRefs.push_back(Unresolved);
5691 break;
5692 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005693
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005694 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005695 if (!ContextObj)
5696 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005697 SmallVector<uint32_t, 16> Inits;
5698 for (auto &ID : Record)
5699 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005700 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005701 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005702 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005703
5704 case SUBMODULE_EXPORT_AS:
5705 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005706 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005707 break;
5708 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005709 }
5710}
5711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005712/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005713/// structure.
5714///
5715/// This routine parses the language options from the AST file and then gives
5716/// them to the AST listener if one is set.
5717///
5718/// \returns true if the listener deems the file unacceptable, false otherwise.
5719bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5720 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005721 ASTReaderListener &Listener,
5722 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005723 LangOptions LangOpts;
5724 unsigned Idx = 0;
5725#define LANGOPT(Name, Bits, Default, Description) \
5726 LangOpts.Name = Record[Idx++];
5727#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5728 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5729#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005730#define SANITIZER(NAME, ID) \
5731 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005732#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005733
Ben Langmuircd98cb72015-06-23 18:20:18 +00005734 for (unsigned N = Record[Idx++]; N; --N)
5735 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5736
Vedant Kumar48b4f762018-04-14 01:40:48 +00005737 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005738 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5739 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005740
Ben Langmuird4a667a2015-06-23 18:20:23 +00005741 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005742
5743 // Comment options.
5744 for (unsigned N = Record[Idx++]; N; --N) {
5745 LangOpts.CommentOpts.BlockCommandNames.push_back(
5746 ReadString(Record, Idx));
5747 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005748 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005749
Samuel Antaoee8fb302016-01-06 13:42:12 +00005750 // OpenMP offloading options.
5751 for (unsigned N = Record[Idx++]; N; --N) {
5752 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5753 }
5754
5755 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5756
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005757 return Listener.ReadLanguageOptions(LangOpts, Complain,
5758 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005759}
5760
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005761bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5762 ASTReaderListener &Listener,
5763 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005764 unsigned Idx = 0;
5765 TargetOptions TargetOpts;
5766 TargetOpts.Triple = ReadString(Record, Idx);
5767 TargetOpts.CPU = ReadString(Record, Idx);
5768 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005769 for (unsigned N = Record[Idx++]; N; --N) {
5770 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5771 }
5772 for (unsigned N = Record[Idx++]; N; --N) {
5773 TargetOpts.Features.push_back(ReadString(Record, Idx));
5774 }
5775
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005776 return Listener.ReadTargetOptions(TargetOpts, Complain,
5777 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005778}
5779
5780bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5781 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005782 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005783 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005784#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005785#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005786 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005787#include "clang/Basic/DiagnosticOptions.def"
5788
Richard Smith3be1cb22014-08-07 00:24:21 +00005789 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005790 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005791 for (unsigned N = Record[Idx++]; N; --N)
5792 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005793
5794 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5795}
5796
5797bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5798 ASTReaderListener &Listener) {
5799 FileSystemOptions FSOpts;
5800 unsigned Idx = 0;
5801 FSOpts.WorkingDir = ReadString(Record, Idx);
5802 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5803}
5804
5805bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5806 bool Complain,
5807 ASTReaderListener &Listener) {
5808 HeaderSearchOptions HSOpts;
5809 unsigned Idx = 0;
5810 HSOpts.Sysroot = ReadString(Record, Idx);
5811
5812 // Include entries.
5813 for (unsigned N = Record[Idx++]; N; --N) {
5814 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005815 frontend::IncludeDirGroup Group
5816 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005817 bool IsFramework = Record[Idx++];
5818 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005819 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5820 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 }
5822
5823 // System header prefixes.
5824 for (unsigned N = Record[Idx++]; N; --N) {
5825 std::string Prefix = ReadString(Record, Idx);
5826 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005827 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 }
5829
5830 HSOpts.ResourceDir = ReadString(Record, Idx);
5831 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005832 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005833 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005834 HSOpts.ImplicitModuleMaps = Record[Idx++];
5835 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005836 HSOpts.UseBuiltinIncludes = Record[Idx++];
5837 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5838 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5839 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005840 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005841
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005842 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5843 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005844}
5845
5846bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5847 bool Complain,
5848 ASTReaderListener &Listener,
5849 std::string &SuggestedPredefines) {
5850 PreprocessorOptions PPOpts;
5851 unsigned Idx = 0;
5852
5853 // Macro definitions/undefs
5854 for (unsigned N = Record[Idx++]; N; --N) {
5855 std::string Macro = ReadString(Record, Idx);
5856 bool IsUndef = Record[Idx++];
5857 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5858 }
5859
5860 // Includes
5861 for (unsigned N = Record[Idx++]; N; --N) {
5862 PPOpts.Includes.push_back(ReadString(Record, Idx));
5863 }
5864
5865 // Macro Includes
5866 for (unsigned N = Record[Idx++]; N; --N) {
5867 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5868 }
5869
5870 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005871 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005872 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 PPOpts.ObjCXXARCStandardLibrary =
5874 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5875 SuggestedPredefines.clear();
5876 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5877 SuggestedPredefines);
5878}
5879
5880std::pair<ModuleFile *, unsigned>
5881ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5882 GlobalPreprocessedEntityMapType::iterator
5883 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005884 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005885 "Corrupted global preprocessed entity map");
5886 ModuleFile *M = I->second;
5887 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5888 return std::make_pair(M, LocalIndex);
5889}
5890
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005891llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005892ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5893 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5894 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5895 Mod.NumPreprocessedEntities);
5896
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005897 return llvm::make_range(PreprocessingRecord::iterator(),
5898 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005899}
5900
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005901llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005902ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005903 return llvm::make_range(
5904 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5905 ModuleDeclIterator(this, &Mod,
5906 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005907}
5908
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005909SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5910 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5911 assert(I != GlobalSkippedRangeMap.end() &&
5912 "Corrupted global skipped range map");
5913 ModuleFile *M = I->second;
5914 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5915 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5916 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5917 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5918 TranslateSourceLocation(*M, RawRange.getEnd()));
5919 assert(Range.isValid());
5920 return Range;
5921}
5922
Guy Benyei11169dd2012-12-18 14:30:41 +00005923PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5924 PreprocessedEntityID PPID = Index+1;
5925 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5926 ModuleFile &M = *PPInfo.first;
5927 unsigned LocalIndex = PPInfo.second;
5928 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5929
Guy Benyei11169dd2012-12-18 14:30:41 +00005930 if (!PP.getPreprocessingRecord()) {
5931 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005932 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005933 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005934
5935 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Dmitry Polukhina7afb212020-04-16 09:24:46 -07005936 if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
5937 M.MacroOffsetsBase + PPOffs.BitOffset)) {
JF Bastien0e828952019-06-26 19:50:12 +00005938 Error(std::move(Err));
5939 return nullptr;
5940 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005941
JF Bastien0e828952019-06-26 19:50:12 +00005942 Expected<llvm::BitstreamEntry> MaybeEntry =
5943 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5944 if (!MaybeEntry) {
5945 Error(MaybeEntry.takeError());
5946 return nullptr;
5947 }
5948 llvm::BitstreamEntry Entry = MaybeEntry.get();
5949
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005950 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005951 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005952
Guy Benyei11169dd2012-12-18 14:30:41 +00005953 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005954 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5955 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005957 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005958 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005959 Expected<unsigned> MaybeRecType =
5960 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5961 if (!MaybeRecType) {
5962 Error(MaybeRecType.takeError());
5963 return nullptr;
5964 }
5965 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005966 case PPD_MACRO_EXPANSION: {
5967 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005968 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005969 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 if (isBuiltin)
5971 Name = getLocalIdentifier(M, Record[1]);
5972 else {
Richard Smith66a81862015-05-04 02:25:31 +00005973 PreprocessedEntityID GlobalID =
5974 getGlobalPreprocessedEntityID(M, Record[1]);
5975 Def = cast<MacroDefinitionRecord>(
5976 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005977 }
5978
5979 MacroExpansion *ME;
5980 if (isBuiltin)
5981 ME = new (PPRec) MacroExpansion(Name, Range);
5982 else
5983 ME = new (PPRec) MacroExpansion(Def, Range);
5984
5985 return ME;
5986 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005987
Guy Benyei11169dd2012-12-18 14:30:41 +00005988 case PPD_MACRO_DEFINITION: {
5989 // Decode the identifier info and then check again; if the macro is
5990 // still defined and associated with the identifier,
5991 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005992 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005993
5994 if (DeserializationListener)
5995 DeserializationListener->MacroDefinitionRead(PPID, MD);
5996
5997 return MD;
5998 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005999
Guy Benyei11169dd2012-12-18 14:30:41 +00006000 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00006001 const char *FullFileNameStart = Blob.data() + Record[0];
6002 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00006003 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006004 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00006005 if (auto FE = PP.getFileManager().getFile(FullFileName))
6006 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006007
Guy Benyei11169dd2012-12-18 14:30:41 +00006008 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00006009 InclusionDirective::InclusionKind Kind
6010 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
6011 InclusionDirective *ID
6012 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00006013 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 Record[1], Record[3],
6015 File,
6016 Range);
6017 return ID;
6018 }
6019 }
6020
6021 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
6022}
6023
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006024/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00006025/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00006026///
6027/// \param SLocMapI points at a chunk of a module that contains no
6028/// preprocessed entities or the entities it contains are not the ones we are
6029/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00006030PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
6031 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6032 ++SLocMapI;
6033 for (GlobalSLocOffsetMapType::const_iterator
6034 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6035 ModuleFile &M = *SLocMapI->second;
6036 if (M.NumPreprocessedEntities)
6037 return M.BasePreprocessedEntityID;
6038 }
6039
6040 return getTotalNumPreprocessedEntities();
6041}
6042
6043namespace {
6044
Guy Benyei11169dd2012-12-18 14:30:41 +00006045struct PPEntityComp {
6046 const ASTReader &Reader;
6047 ModuleFile &M;
6048
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006049 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006050
6051 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6052 SourceLocation LHS = getLoc(L);
6053 SourceLocation RHS = getLoc(R);
6054 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6055 }
6056
6057 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6058 SourceLocation LHS = getLoc(L);
6059 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6060 }
6061
6062 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6063 SourceLocation RHS = getLoc(R);
6064 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6065 }
6066
6067 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00006068 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006069 }
6070};
6071
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006072} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006073
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006074PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6075 bool EndsAfter) const {
6076 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00006077 return getTotalNumPreprocessedEntities();
6078
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006079 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6080 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00006081 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6082 "Corrupted global sloc offset map");
6083
6084 if (SLocMapI->second->NumPreprocessedEntities == 0)
6085 return findNextPreprocessedEntity(SLocMapI);
6086
6087 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006088
6089 using pp_iterator = const PPEntityOffset *;
6090
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6092 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6093
6094 size_t Count = M.NumPreprocessedEntities;
6095 size_t Half;
6096 pp_iterator First = pp_begin;
6097 pp_iterator PPI;
6098
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006099 if (EndsAfter) {
6100 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00006101 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006102 } else {
6103 // Do a binary search manually instead of using std::lower_bound because
6104 // The end locations of entities may be unordered (when a macro expansion
6105 // is inside another macro argument), but for this case it is not important
6106 // whether we get the first macro expansion or its containing macro.
6107 while (Count > 0) {
6108 Half = Count / 2;
6109 PPI = First;
6110 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006111 if (SourceMgr.isBeforeInTranslationUnit(
6112 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006113 First = PPI;
6114 ++First;
6115 Count = Count - Half - 1;
6116 } else
6117 Count = Half;
6118 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006119 }
6120
6121 if (PPI == pp_end)
6122 return findNextPreprocessedEntity(SLocMapI);
6123
6124 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6125}
6126
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006127/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006128/// preprocessed entities that \arg Range encompasses.
6129std::pair<unsigned, unsigned>
6130 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6131 if (Range.isInvalid())
6132 return std::make_pair(0,0);
6133 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6134
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006135 PreprocessedEntityID BeginID =
6136 findPreprocessedEntity(Range.getBegin(), false);
6137 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 return std::make_pair(BeginID, EndID);
6139}
6140
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006141/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006142/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006143Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 FileID FID) {
6145 if (FID.isInvalid())
6146 return false;
6147
6148 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6149 ModuleFile &M = *PPInfo.first;
6150 unsigned LocalIndex = PPInfo.second;
6151 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006152
Richard Smithcb34bd32016-03-27 07:28:06 +00006153 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 if (Loc.isInvalid())
6155 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006156
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6158 return true;
6159 else
6160 return false;
6161}
6162
6163namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006164
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006165 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006166 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006168 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006169
Guy Benyei11169dd2012-12-18 14:30:41 +00006170 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006171 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006172
6173 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006174 HeaderFileInfoLookupTable *Table
6175 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006176 if (!Table)
6177 return false;
6178
6179 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006180 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006181 if (Pos == Table->end())
6182 return false;
6183
Richard Smithbdf2d932015-07-30 03:37:16 +00006184 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 return true;
6186 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006187
David Blaikie05785d12013-02-20 22:23:23 +00006188 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006189 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006190
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006191} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006192
6193HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006194 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006195 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006196 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006198
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 return HeaderFileInfo();
6200}
6201
6202void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006203 using DiagState = DiagnosticsEngine::DiagState;
6204 SmallVector<DiagState *, 32> DiagStates;
6205
Vedant Kumar48b4f762018-04-14 01:40:48 +00006206 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006207 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006208 auto &Record = F.PragmaDiagMappings;
6209 if (Record.empty())
6210 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006211
Richard Smithd230de22017-01-26 01:01:01 +00006212 DiagStates.clear();
6213
6214 auto ReadDiagState =
6215 [&](const DiagState &BasedOn, SourceLocation Loc,
6216 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6217 unsigned BackrefID = Record[Idx++];
6218 if (BackrefID != 0)
6219 return DiagStates[BackrefID - 1];
6220
Guy Benyei11169dd2012-12-18 14:30:41 +00006221 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006222 Diag.DiagStates.push_back(BasedOn);
6223 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006225 unsigned Size = Record[Idx++];
6226 assert(Idx + Size * 2 <= Record.size() &&
6227 "Invalid data, not enough diag/map pairs");
6228 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006229 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006230 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006231 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006232 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6233 continue;
6234
6235 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6236
6237 // If this mapping was specified as a warning but the severity was
6238 // upgraded due to diagnostic settings, simulate the current diagnostic
6239 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006240 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6241 NewMapping.setSeverity(diag::Severity::Warning);
6242 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006243 }
6244
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006245 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006246 }
Richard Smithd230de22017-01-26 01:01:01 +00006247 return NewState;
6248 };
6249
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006250 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006251 DiagState *FirstState;
6252 if (F.Kind == MK_ImplicitModule) {
6253 // Implicitly-built modules are reused with different diagnostic
6254 // settings. Use the initial diagnostic state from Diag to simulate this
6255 // compilation's diagnostic settings.
6256 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6257 DiagStates.push_back(FirstState);
6258
6259 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006260 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006261 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006262 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006263 assert(Idx < Record.size() &&
6264 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006265 } else if (F.isModule()) {
6266 // For an explicit module, preserve the flags from the module build
6267 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6268 // -Wblah flags.
6269 unsigned Flags = Record[Idx++];
6270 DiagState Initial;
6271 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6272 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6273 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6274 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6275 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6276 Initial.ExtBehavior = (diag::Severity)Flags;
6277 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006278
Richard Smith6c2b5a82018-02-09 01:15:13 +00006279 assert(F.OriginalSourceFileID.isValid());
6280
Richard Smithe37391c2017-05-03 00:28:49 +00006281 // Set up the root buffer of the module to start with the initial
6282 // diagnostic state of the module itself, to cover files that contain no
6283 // explicit transitions (for which we did not serialize anything).
6284 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6285 .StateTransitions.push_back({FirstState, 0});
6286 } else {
6287 // For prefix ASTs, start with whatever the user configured on the
6288 // command line.
6289 Idx++; // Skip flags.
6290 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6291 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006292 }
Richard Smithd230de22017-01-26 01:01:01 +00006293
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006294 // Read the state transitions.
6295 unsigned NumLocations = Record[Idx++];
6296 while (NumLocations--) {
6297 assert(Idx < Record.size() &&
6298 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006299 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6300 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006301 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006302 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6303 unsigned Transitions = Record[Idx++];
6304
6305 // Note that we don't need to set up Parent/ParentOffset here, because
6306 // we won't be changing the diagnostic state within imported FileIDs
6307 // (other than perhaps appending to the main source file, which has no
6308 // parent).
6309 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6310 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6311 for (unsigned I = 0; I != Transitions; ++I) {
6312 unsigned Offset = Record[Idx++];
6313 auto *State =
6314 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6315 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 }
6317 }
Richard Smithd230de22017-01-26 01:01:01 +00006318
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006319 // Read the final state.
6320 assert(Idx < Record.size() &&
6321 "Invalid data, missing final pragma diagnostic state");
6322 SourceLocation CurStateLoc =
6323 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6324 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6325
6326 if (!F.isModule()) {
6327 Diag.DiagStatesByLoc.CurDiagState = CurState;
6328 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6329
6330 // Preserve the property that the imaginary root file describes the
6331 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006332 FileID NullFile;
6333 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006334 if (T.empty())
6335 T.push_back({CurState, 0});
6336 else
6337 T[0].State = CurState;
6338 }
6339
Richard Smithd230de22017-01-26 01:01:01 +00006340 // Don't try to read these mappings again.
6341 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 }
6343}
6344
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006345/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006346ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6347 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6348 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6349 ModuleFile *M = I->second;
Dmitry Polukhina7afb212020-04-16 09:24:46 -07006350 return RecordLocation(
6351 M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset());
Guy Benyei11169dd2012-12-18 14:30:41 +00006352}
6353
John McCalld505e572019-12-13 21:54:44 -05006354static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6355 switch (code) {
6356#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6357 case TYPE_##CODE_ID: return Type::CLASS_ID;
6358#include "clang/Serialization/TypeBitCodes.def"
6359 default: return llvm::None;
6360 }
John McCall3ce3d232019-12-13 03:37:23 -05006361}
6362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006363/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006364///
6365/// The index is the type ID, shifted and minus the number of predefs. This
6366/// routine actually reads the record corresponding to the type at the given
6367/// location. It is a helper routine for GetType, which deals with reading type
6368/// IDs.
6369QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006370 assert(ContextObj && "reading type with no AST context");
6371 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006372 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006373 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006374
6375 // Keep track of where we are in the stream, then jump back there
6376 // after reading this type.
6377 SavedStreamPosition SavedPosition(DeclsCursor);
6378
6379 ReadingKindTracker ReadingKind(Read_Type, *this);
6380
6381 // Note that we are loading a type record.
6382 Deserializing AType(this);
6383
JF Bastien0e828952019-06-26 19:50:12 +00006384 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6385 Error(std::move(Err));
6386 return QualType();
6387 }
John McCall3ce3d232019-12-13 03:37:23 -05006388 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6389 if (!RawCode) {
6390 Error(RawCode.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006391 return QualType();
6392 }
JF Bastien0e828952019-06-26 19:50:12 +00006393
John McCall3ce3d232019-12-13 03:37:23 -05006394 ASTRecordReader Record(*this, *Loc.F);
6395 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6396 if (!Code) {
6397 Error(Code.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006398 return QualType();
6399 }
John McCalld505e572019-12-13 21:54:44 -05006400 if (Code.get() == TYPE_EXT_QUAL) {
6401 QualType baseType = Record.readQualType();
6402 Qualifiers quals = Record.readQualifiers();
6403 return Context.getQualifiedType(baseType, quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00006404 }
6405
John McCalld505e572019-12-13 21:54:44 -05006406 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6407 if (!maybeClass) {
6408 Error("Unexpected code for type");
6409 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006410 }
6411
John McCalld505e572019-12-13 21:54:44 -05006412 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6413 return TypeReader.read(*maybeClass);
Richard Smith564417a2014-03-20 21:47:22 +00006414}
6415
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006416namespace clang {
6417
6418class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
John McCall3ce3d232019-12-13 03:37:23 -05006419 ASTRecordReader &Reader;
Guy Benyei11169dd2012-12-18 14:30:41 +00006420
John McCall3ce3d232019-12-13 03:37:23 -05006421 SourceLocation readSourceLocation() {
6422 return Reader.readSourceLocation();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006423 }
6424
6425 TypeSourceInfo *GetTypeSourceInfo() {
John McCall3ce3d232019-12-13 03:37:23 -05006426 return Reader.readTypeSourceInfo();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006427 }
6428
6429 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
John McCall3ce3d232019-12-13 03:37:23 -05006430 return Reader.readNestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 }
6432
Richard Smithe43e2b32018-08-20 21:47:29 +00006433 Attr *ReadAttr() {
John McCall3ce3d232019-12-13 03:37:23 -05006434 return Reader.readAttr();
Richard Smithe43e2b32018-08-20 21:47:29 +00006435 }
6436
Guy Benyei11169dd2012-12-18 14:30:41 +00006437public:
John McCall3ce3d232019-12-13 03:37:23 -05006438 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006439
6440 // We want compile-time assurance that we've enumerated all of
6441 // these, so unfortunately we have to declare them first, then
6442 // define them out-of-line.
6443#define ABSTRACT_TYPELOC(CLASS, PARENT)
6444#define TYPELOC(CLASS, PARENT) \
6445 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6446#include "clang/AST/TypeLocNodes.def"
6447
6448 void VisitFunctionTypeLoc(FunctionTypeLoc);
6449 void VisitArrayTypeLoc(ArrayTypeLoc);
6450};
6451
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006452} // namespace clang
6453
Guy Benyei11169dd2012-12-18 14:30:41 +00006454void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6455 // nothing to do
6456}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006457
Guy Benyei11169dd2012-12-18 14:30:41 +00006458void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006459 TL.setBuiltinLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006460 if (TL.needsExtraLocalData()) {
John McCall3ce3d232019-12-13 03:37:23 -05006461 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6462 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6463 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6464 TL.setModeAttr(Reader.readInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 }
6466}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006467
Guy Benyei11169dd2012-12-18 14:30:41 +00006468void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006469 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006470}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006471
Guy Benyei11169dd2012-12-18 14:30:41 +00006472void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006473 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006474}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006475
Reid Kleckner8a365022013-06-24 17:51:48 +00006476void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6477 // nothing to do
6478}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006479
Reid Kleckner0503a872013-12-05 01:23:43 +00006480void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6481 // nothing to do
6482}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006483
Leonard Chanc72aaf62019-05-07 03:20:17 +00006484void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006485 TL.setExpansionLoc(readSourceLocation());
Leonard Chanc72aaf62019-05-07 03:20:17 +00006486}
6487
Guy Benyei11169dd2012-12-18 14:30:41 +00006488void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006489 TL.setCaretLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006490}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006491
Guy Benyei11169dd2012-12-18 14:30:41 +00006492void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006493 TL.setAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006494}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006495
Guy Benyei11169dd2012-12-18 14:30:41 +00006496void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006497 TL.setAmpAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006498}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006499
Guy Benyei11169dd2012-12-18 14:30:41 +00006500void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006501 TL.setStarLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006502 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006503}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006504
Guy Benyei11169dd2012-12-18 14:30:41 +00006505void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006506 TL.setLBracketLoc(readSourceLocation());
6507 TL.setRBracketLoc(readSourceLocation());
6508 if (Reader.readBool())
6509 TL.setSizeExpr(Reader.readExpr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006510 else
Craig Toppera13603a2014-05-22 05:54:18 +00006511 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006512}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006513
Guy Benyei11169dd2012-12-18 14:30:41 +00006514void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6515 VisitArrayTypeLoc(TL);
6516}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006517
Guy Benyei11169dd2012-12-18 14:30:41 +00006518void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6519 VisitArrayTypeLoc(TL);
6520}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006521
Guy Benyei11169dd2012-12-18 14:30:41 +00006522void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6523 VisitArrayTypeLoc(TL);
6524}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006525
Guy Benyei11169dd2012-12-18 14:30:41 +00006526void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6527 DependentSizedArrayTypeLoc TL) {
6528 VisitArrayTypeLoc(TL);
6529}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006530
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006531void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6532 DependentAddressSpaceTypeLoc TL) {
6533
John McCall3ce3d232019-12-13 03:37:23 -05006534 TL.setAttrNameLoc(readSourceLocation());
6535 TL.setAttrOperandParensRange(Reader.readSourceRange());
6536 TL.setAttrExprOperand(Reader.readExpr());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006537}
6538
Guy Benyei11169dd2012-12-18 14:30:41 +00006539void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6540 DependentSizedExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006541 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006542}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006543
Guy Benyei11169dd2012-12-18 14:30:41 +00006544void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006545 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006546}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006547
Erich Keanef702b022018-07-13 19:46:04 +00006548void TypeLocReader::VisitDependentVectorTypeLoc(
6549 DependentVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006550 TL.setNameLoc(readSourceLocation());
Erich Keanef702b022018-07-13 19:46:04 +00006551}
6552
Guy Benyei11169dd2012-12-18 14:30:41 +00006553void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006554 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006555}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006556
Florian Hahn10658692020-05-11 17:45:51 +01006557void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
6558 TL.setAttrNameLoc(readSourceLocation());
6559 TL.setAttrOperandParensRange(Reader.readSourceRange());
6560 TL.setAttrRowOperand(Reader.readExpr());
6561 TL.setAttrColumnOperand(Reader.readExpr());
6562}
6563
6564void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
6565 DependentSizedMatrixTypeLoc TL) {
6566 TL.setAttrNameLoc(readSourceLocation());
6567 TL.setAttrOperandParensRange(Reader.readSourceRange());
6568 TL.setAttrRowOperand(Reader.readExpr());
6569 TL.setAttrColumnOperand(Reader.readExpr());
6570}
6571
Guy Benyei11169dd2012-12-18 14:30:41 +00006572void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006573 TL.setLocalRangeBegin(readSourceLocation());
6574 TL.setLParenLoc(readSourceLocation());
6575 TL.setRParenLoc(readSourceLocation());
6576 TL.setExceptionSpecRange(Reader.readSourceRange());
6577 TL.setLocalRangeEnd(readSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006578 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
John McCall3ce3d232019-12-13 03:37:23 -05006579 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00006580 }
6581}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006582
Guy Benyei11169dd2012-12-18 14:30:41 +00006583void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6584 VisitFunctionTypeLoc(TL);
6585}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006586
Guy Benyei11169dd2012-12-18 14:30:41 +00006587void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6588 VisitFunctionTypeLoc(TL);
6589}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006590
Guy Benyei11169dd2012-12-18 14:30:41 +00006591void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006592 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006593}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006596 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006597}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006598
Guy Benyei11169dd2012-12-18 14:30:41 +00006599void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006600 TL.setTypeofLoc(readSourceLocation());
6601 TL.setLParenLoc(readSourceLocation());
6602 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006603}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006604
Guy Benyei11169dd2012-12-18 14:30:41 +00006605void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006606 TL.setTypeofLoc(readSourceLocation());
6607 TL.setLParenLoc(readSourceLocation());
6608 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006609 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006610}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006611
Guy Benyei11169dd2012-12-18 14:30:41 +00006612void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006613 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006614}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006615
Guy Benyei11169dd2012-12-18 14:30:41 +00006616void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006617 TL.setKWLoc(readSourceLocation());
6618 TL.setLParenLoc(readSourceLocation());
6619 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006620 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006621}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006622
Guy Benyei11169dd2012-12-18 14:30:41 +00006623void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006624 TL.setNameLoc(readSourceLocation());
Saar Razb481f022020-01-22 02:03:05 +02006625 if (Reader.readBool()) {
6626 TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6627 TL.setTemplateKWLoc(readSourceLocation());
6628 TL.setConceptNameLoc(readSourceLocation());
6629 TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6630 TL.setLAngleLoc(readSourceLocation());
6631 TL.setRAngleLoc(readSourceLocation());
6632 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6633 TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
6634 TL.getTypePtr()->getArg(i).getKind()));
6635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006636}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006637
Richard Smith600b5262017-01-26 20:40:47 +00006638void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6639 DeducedTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006640 TL.setTemplateNameLoc(readSourceLocation());
Richard Smith600b5262017-01-26 20:40:47 +00006641}
6642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006644 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006645}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006646
Guy Benyei11169dd2012-12-18 14:30:41 +00006647void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006648 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006649}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006650
Guy Benyei11169dd2012-12-18 14:30:41 +00006651void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006652 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006653}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006654
Guy Benyei11169dd2012-12-18 14:30:41 +00006655void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006656 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006657}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006658
Guy Benyei11169dd2012-12-18 14:30:41 +00006659void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6660 SubstTemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006661 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006662}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006663
Guy Benyei11169dd2012-12-18 14:30:41 +00006664void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6665 SubstTemplateTypeParmPackTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006666 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006667}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006668
Guy Benyei11169dd2012-12-18 14:30:41 +00006669void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6670 TemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006671 TL.setTemplateKeywordLoc(readSourceLocation());
6672 TL.setTemplateNameLoc(readSourceLocation());
6673 TL.setLAngleLoc(readSourceLocation());
6674 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006675 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006676 TL.setArgLocInfo(
6677 i,
John McCall3ce3d232019-12-13 03:37:23 -05006678 Reader.readTemplateArgumentLocInfo(
6679 TL.getTypePtr()->getArg(i).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006680}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006681
Guy Benyei11169dd2012-12-18 14:30:41 +00006682void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006683 TL.setLParenLoc(readSourceLocation());
6684 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006685}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006686
Guy Benyei11169dd2012-12-18 14:30:41 +00006687void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006688 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006689 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006690}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006693 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006694}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006695
Guy Benyei11169dd2012-12-18 14:30:41 +00006696void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006697 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006698 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006699 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006700}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006701
Guy Benyei11169dd2012-12-18 14:30:41 +00006702void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6703 DependentTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006704 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006705 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006706 TL.setTemplateKeywordLoc(readSourceLocation());
6707 TL.setTemplateNameLoc(readSourceLocation());
6708 TL.setLAngleLoc(readSourceLocation());
6709 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006710 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006711 TL.setArgLocInfo(
6712 I,
John McCall3ce3d232019-12-13 03:37:23 -05006713 Reader.readTemplateArgumentLocInfo(
6714 TL.getTypePtr()->getArg(I).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006715}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006716
Guy Benyei11169dd2012-12-18 14:30:41 +00006717void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006718 TL.setEllipsisLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006719}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006720
Guy Benyei11169dd2012-12-18 14:30:41 +00006721void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006722 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006723}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006724
Manman Rene6be26c2016-09-13 17:25:08 +00006725void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6726 if (TL.getNumProtocols()) {
John McCall3ce3d232019-12-13 03:37:23 -05006727 TL.setProtocolLAngleLoc(readSourceLocation());
6728 TL.setProtocolRAngleLoc(readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006729 }
6730 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006731 TL.setProtocolLoc(i, readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006732}
6733
Guy Benyei11169dd2012-12-18 14:30:41 +00006734void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006735 TL.setHasBaseTypeAsWritten(Reader.readBool());
6736 TL.setTypeArgsLAngleLoc(readSourceLocation());
6737 TL.setTypeArgsRAngleLoc(readSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006738 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006739 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
John McCall3ce3d232019-12-13 03:37:23 -05006740 TL.setProtocolLAngleLoc(readSourceLocation());
6741 TL.setProtocolRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006742 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006743 TL.setProtocolLoc(i, readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006744}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006745
Guy Benyei11169dd2012-12-18 14:30:41 +00006746void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006747 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006748}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006751 TL.setKWLoc(readSourceLocation());
6752 TL.setLParenLoc(readSourceLocation());
6753 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006754}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006755
Xiuli Pan9c14e282016-01-09 12:53:17 +00006756void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006757 TL.setKWLoc(readSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006758}
Guy Benyei11169dd2012-12-18 14:30:41 +00006759
Erich Keane5f0903e2020-04-17 10:44:19 -07006760void TypeLocReader::VisitExtIntTypeLoc(clang::ExtIntTypeLoc TL) {
6761 TL.setNameLoc(readSourceLocation());
6762}
6763void TypeLocReader::VisitDependentExtIntTypeLoc(
6764 clang::DependentExtIntTypeLoc TL) {
6765 TL.setNameLoc(readSourceLocation());
6766}
6767
6768
John McCall3ce3d232019-12-13 03:37:23 -05006769void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6770 TypeLocReader TLR(*this);
Richard Smithc23d7342018-06-29 20:46:25 +00006771 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6772 TLR.Visit(TL);
6773}
6774
John McCall3ce3d232019-12-13 03:37:23 -05006775TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6776 QualType InfoTy = readType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006778 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006779
6780 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
John McCall3ce3d232019-12-13 03:37:23 -05006781 readTypeLoc(TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006782 return TInfo;
6783}
6784
6785QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006786 assert(ContextObj && "reading type with no AST context");
6787 ASTContext &Context = *ContextObj;
6788
Guy Benyei11169dd2012-12-18 14:30:41 +00006789 unsigned FastQuals = ID & Qualifiers::FastMask;
6790 unsigned Index = ID >> Qualifiers::FastWidth;
6791
6792 if (Index < NUM_PREDEF_TYPE_IDS) {
6793 QualType T;
6794 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006795 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006796 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006797 case PREDEF_TYPE_VOID_ID:
6798 T = Context.VoidTy;
6799 break;
6800 case PREDEF_TYPE_BOOL_ID:
6801 T = Context.BoolTy;
6802 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006803 case PREDEF_TYPE_CHAR_U_ID:
6804 case PREDEF_TYPE_CHAR_S_ID:
6805 // FIXME: Check that the signedness of CharTy is correct!
6806 T = Context.CharTy;
6807 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006808 case PREDEF_TYPE_UCHAR_ID:
6809 T = Context.UnsignedCharTy;
6810 break;
6811 case PREDEF_TYPE_USHORT_ID:
6812 T = Context.UnsignedShortTy;
6813 break;
6814 case PREDEF_TYPE_UINT_ID:
6815 T = Context.UnsignedIntTy;
6816 break;
6817 case PREDEF_TYPE_ULONG_ID:
6818 T = Context.UnsignedLongTy;
6819 break;
6820 case PREDEF_TYPE_ULONGLONG_ID:
6821 T = Context.UnsignedLongLongTy;
6822 break;
6823 case PREDEF_TYPE_UINT128_ID:
6824 T = Context.UnsignedInt128Ty;
6825 break;
6826 case PREDEF_TYPE_SCHAR_ID:
6827 T = Context.SignedCharTy;
6828 break;
6829 case PREDEF_TYPE_WCHAR_ID:
6830 T = Context.WCharTy;
6831 break;
6832 case PREDEF_TYPE_SHORT_ID:
6833 T = Context.ShortTy;
6834 break;
6835 case PREDEF_TYPE_INT_ID:
6836 T = Context.IntTy;
6837 break;
6838 case PREDEF_TYPE_LONG_ID:
6839 T = Context.LongTy;
6840 break;
6841 case PREDEF_TYPE_LONGLONG_ID:
6842 T = Context.LongLongTy;
6843 break;
6844 case PREDEF_TYPE_INT128_ID:
6845 T = Context.Int128Ty;
6846 break;
Ties Stuijecd682b2020-06-05 00:20:02 +01006847 case PREDEF_TYPE_BFLOAT16_ID:
6848 T = Context.BFloat16Ty;
6849 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006850 case PREDEF_TYPE_HALF_ID:
6851 T = Context.HalfTy;
6852 break;
6853 case PREDEF_TYPE_FLOAT_ID:
6854 T = Context.FloatTy;
6855 break;
6856 case PREDEF_TYPE_DOUBLE_ID:
6857 T = Context.DoubleTy;
6858 break;
6859 case PREDEF_TYPE_LONGDOUBLE_ID:
6860 T = Context.LongDoubleTy;
6861 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006862 case PREDEF_TYPE_SHORT_ACCUM_ID:
6863 T = Context.ShortAccumTy;
6864 break;
6865 case PREDEF_TYPE_ACCUM_ID:
6866 T = Context.AccumTy;
6867 break;
6868 case PREDEF_TYPE_LONG_ACCUM_ID:
6869 T = Context.LongAccumTy;
6870 break;
6871 case PREDEF_TYPE_USHORT_ACCUM_ID:
6872 T = Context.UnsignedShortAccumTy;
6873 break;
6874 case PREDEF_TYPE_UACCUM_ID:
6875 T = Context.UnsignedAccumTy;
6876 break;
6877 case PREDEF_TYPE_ULONG_ACCUM_ID:
6878 T = Context.UnsignedLongAccumTy;
6879 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006880 case PREDEF_TYPE_SHORT_FRACT_ID:
6881 T = Context.ShortFractTy;
6882 break;
6883 case PREDEF_TYPE_FRACT_ID:
6884 T = Context.FractTy;
6885 break;
6886 case PREDEF_TYPE_LONG_FRACT_ID:
6887 T = Context.LongFractTy;
6888 break;
6889 case PREDEF_TYPE_USHORT_FRACT_ID:
6890 T = Context.UnsignedShortFractTy;
6891 break;
6892 case PREDEF_TYPE_UFRACT_ID:
6893 T = Context.UnsignedFractTy;
6894 break;
6895 case PREDEF_TYPE_ULONG_FRACT_ID:
6896 T = Context.UnsignedLongFractTy;
6897 break;
6898 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6899 T = Context.SatShortAccumTy;
6900 break;
6901 case PREDEF_TYPE_SAT_ACCUM_ID:
6902 T = Context.SatAccumTy;
6903 break;
6904 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6905 T = Context.SatLongAccumTy;
6906 break;
6907 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6908 T = Context.SatUnsignedShortAccumTy;
6909 break;
6910 case PREDEF_TYPE_SAT_UACCUM_ID:
6911 T = Context.SatUnsignedAccumTy;
6912 break;
6913 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6914 T = Context.SatUnsignedLongAccumTy;
6915 break;
6916 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6917 T = Context.SatShortFractTy;
6918 break;
6919 case PREDEF_TYPE_SAT_FRACT_ID:
6920 T = Context.SatFractTy;
6921 break;
6922 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6923 T = Context.SatLongFractTy;
6924 break;
6925 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6926 T = Context.SatUnsignedShortFractTy;
6927 break;
6928 case PREDEF_TYPE_SAT_UFRACT_ID:
6929 T = Context.SatUnsignedFractTy;
6930 break;
6931 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6932 T = Context.SatUnsignedLongFractTy;
6933 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006934 case PREDEF_TYPE_FLOAT16_ID:
6935 T = Context.Float16Ty;
6936 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006937 case PREDEF_TYPE_FLOAT128_ID:
6938 T = Context.Float128Ty;
6939 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006940 case PREDEF_TYPE_OVERLOAD_ID:
6941 T = Context.OverloadTy;
6942 break;
6943 case PREDEF_TYPE_BOUND_MEMBER:
6944 T = Context.BoundMemberTy;
6945 break;
6946 case PREDEF_TYPE_PSEUDO_OBJECT:
6947 T = Context.PseudoObjectTy;
6948 break;
6949 case PREDEF_TYPE_DEPENDENT_ID:
6950 T = Context.DependentTy;
6951 break;
6952 case PREDEF_TYPE_UNKNOWN_ANY:
6953 T = Context.UnknownAnyTy;
6954 break;
6955 case PREDEF_TYPE_NULLPTR_ID:
6956 T = Context.NullPtrTy;
6957 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006958 case PREDEF_TYPE_CHAR8_ID:
6959 T = Context.Char8Ty;
6960 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006961 case PREDEF_TYPE_CHAR16_ID:
6962 T = Context.Char16Ty;
6963 break;
6964 case PREDEF_TYPE_CHAR32_ID:
6965 T = Context.Char32Ty;
6966 break;
6967 case PREDEF_TYPE_OBJC_ID:
6968 T = Context.ObjCBuiltinIdTy;
6969 break;
6970 case PREDEF_TYPE_OBJC_CLASS:
6971 T = Context.ObjCBuiltinClassTy;
6972 break;
6973 case PREDEF_TYPE_OBJC_SEL:
6974 T = Context.ObjCBuiltinSelTy;
6975 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006976#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6977 case PREDEF_TYPE_##Id##_ID: \
6978 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006979 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006980#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006981#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6982 case PREDEF_TYPE_##Id##_ID: \
6983 T = Context.Id##Ty; \
6984 break;
6985#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006986 case PREDEF_TYPE_SAMPLER_ID:
6987 T = Context.OCLSamplerTy;
6988 break;
6989 case PREDEF_TYPE_EVENT_ID:
6990 T = Context.OCLEventTy;
6991 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006992 case PREDEF_TYPE_CLK_EVENT_ID:
6993 T = Context.OCLClkEventTy;
6994 break;
6995 case PREDEF_TYPE_QUEUE_ID:
6996 T = Context.OCLQueueTy;
6997 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006998 case PREDEF_TYPE_RESERVE_ID_ID:
6999 T = Context.OCLReserveIDTy;
7000 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007001 case PREDEF_TYPE_AUTO_DEDUCT:
7002 T = Context.getAutoDeductType();
7003 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007004 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7005 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007006 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7008 T = Context.ARCUnbridgedCastTy;
7009 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 case PREDEF_TYPE_BUILTIN_FN:
7011 T = Context.BuiltinFnTy;
7012 break;
Florian Hahn8f3f88d2020-06-01 19:42:03 +01007013 case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
7014 T = Context.IncompleteMatrixIdxTy;
7015 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007016 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7017 T = Context.OMPArraySectionTy;
7018 break;
Alexey Bataev7ac9efb2020-02-05 09:33:05 -05007019 case PREDEF_TYPE_OMP_ARRAY_SHAPING:
7020 T = Context.OMPArraySectionTy;
7021 break;
Alexey Bataev13a15042020-04-01 15:06:38 -04007022 case PREDEF_TYPE_OMP_ITERATOR:
7023 T = Context.OMPIteratorTy;
7024 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00007025#define SVE_TYPE(Name, Id, SingletonId) \
7026 case PREDEF_TYPE_##Id##_ID: \
7027 T = Context.SingletonId; \
7028 break;
7029#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 }
7031
7032 assert(!T.isNull() && "Unknown predefined type");
7033 return T.withFastQualifiers(FastQuals);
7034 }
7035
7036 Index -= NUM_PREDEF_TYPE_IDS;
7037 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7038 if (TypesLoaded[Index].isNull()) {
7039 TypesLoaded[Index] = readTypeRecord(Index);
7040 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007041 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007042
7043 TypesLoaded[Index]->setFromAST();
7044 if (DeserializationListener)
7045 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7046 TypesLoaded[Index]);
7047 }
7048
7049 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7050}
7051
7052QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7053 return GetType(getGlobalTypeID(F, LocalID));
7054}
7055
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007056serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007057ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7058 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7059 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007060
Guy Benyei11169dd2012-12-18 14:30:41 +00007061 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7062 return LocalID;
7063
Richard Smith37a93df2017-02-18 00:32:02 +00007064 if (!F.ModuleOffsetMap.empty())
7065 ReadModuleOffsetMap(F);
7066
Guy Benyei11169dd2012-12-18 14:30:41 +00007067 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7068 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7069 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071 unsigned GlobalIndex = LocalIndex + I->second;
7072 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7073}
7074
7075TemplateArgumentLocInfo
John McCall3ce3d232019-12-13 03:37:23 -05007076ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 switch (Kind) {
7078 case TemplateArgument::Expression:
John McCall3ce3d232019-12-13 03:37:23 -05007079 return readExpr();
Guy Benyei11169dd2012-12-18 14:30:41 +00007080 case TemplateArgument::Type:
John McCall3ce3d232019-12-13 03:37:23 -05007081 return readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007082 case TemplateArgument::Template: {
John McCall3ce3d232019-12-13 03:37:23 -05007083 NestedNameSpecifierLoc QualifierLoc =
7084 readNestedNameSpecifierLoc();
7085 SourceLocation TemplateNameLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7087 SourceLocation());
7088 }
7089 case TemplateArgument::TemplateExpansion: {
John McCall3ce3d232019-12-13 03:37:23 -05007090 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7091 SourceLocation TemplateNameLoc = readSourceLocation();
7092 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007093 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007094 EllipsisLoc);
7095 }
7096 case TemplateArgument::Null:
7097 case TemplateArgument::Integral:
7098 case TemplateArgument::Declaration:
7099 case TemplateArgument::NullPtr:
7100 case TemplateArgument::Pack:
7101 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007102 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 }
7104 llvm_unreachable("unexpected template argument loc");
7105}
7106
John McCall3ce3d232019-12-13 03:37:23 -05007107TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7108 TemplateArgument Arg = readTemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00007109
7110 if (Arg.getKind() == TemplateArgument::Expression) {
John McCall3ce3d232019-12-13 03:37:23 -05007111 if (readBool()) // bool InfoHasSameExpr.
Guy Benyei11169dd2012-12-18 14:30:41 +00007112 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7113 }
John McCall3ce3d232019-12-13 03:37:23 -05007114 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00007115}
7116
John McCall3ce3d232019-12-13 03:37:23 -05007117const ASTTemplateArgumentListInfo *
7118ASTRecordReader::readASTTemplateArgumentListInfo() {
7119 SourceLocation LAngleLoc = readSourceLocation();
7120 SourceLocation RAngleLoc = readSourceLocation();
7121 unsigned NumArgsAsWritten = readInt();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007122 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7123 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05007124 TemplArgsInfo.addArgument(readTemplateArgumentLoc());
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007125 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7126}
7127
Guy Benyei11169dd2012-12-18 14:30:41 +00007128Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7129 return GetDecl(ID);
7130}
7131
Richard Smith053f6c62014-05-16 23:01:30 +00007132void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007133 if (NumCurrentElementsDeserializing) {
7134 // We arrange to not care about the complete redeclaration chain while we're
7135 // deserializing. Just remember that the AST has marked this one as complete
7136 // but that it's not actually complete yet, so we know we still need to
7137 // complete it later.
7138 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7139 return;
7140 }
7141
Richard Smith053f6c62014-05-16 23:01:30 +00007142 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7143
Richard Smith053f6c62014-05-16 23:01:30 +00007144 // If this is a named declaration, complete it by looking it up
7145 // within its context.
7146 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007147 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007148 // all mergeable entities within it.
7149 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7150 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7151 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007152 if (!getContext().getLangOpts().CPlusPlus &&
7153 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007154 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007155 // the identifier instead. (For C++ modules, we don't store decls
7156 // in the serialized identifier table, so we do the lookup in the TU.)
7157 auto *II = Name.getAsIdentifierInfo();
7158 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007159 if (II->isOutOfDate())
7160 updateOutOfDateIdentifier(*II);
7161 } else
7162 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007163 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007164 // Find all declarations of this kind from the relevant context.
7165 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7166 auto *DC = cast<DeclContext>(DCDecl);
7167 SmallVector<Decl*, 8> Decls;
7168 FindExternalLexicalDecls(
7169 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7170 }
Richard Smith053f6c62014-05-16 23:01:30 +00007171 }
7172 }
Richard Smith50895422015-01-31 03:04:55 +00007173
7174 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7175 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7176 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7177 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7178 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7179 if (auto *Template = FD->getPrimaryTemplate())
7180 Template->LoadLazySpecializations();
7181 }
Richard Smith053f6c62014-05-16 23:01:30 +00007182}
7183
Richard Smithc2bb8182015-03-24 06:36:48 +00007184CXXCtorInitializer **
7185ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7186 RecordLocation Loc = getLocalBitOffset(Offset);
7187 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7188 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007189 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7190 Error(std::move(Err));
7191 return nullptr;
7192 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007193 ReadingKindTracker ReadingKind(Read_Decl, *this);
7194
JF Bastien0e828952019-06-26 19:50:12 +00007195 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7196 if (!MaybeCode) {
7197 Error(MaybeCode.takeError());
7198 return nullptr;
7199 }
7200 unsigned Code = MaybeCode.get();
7201
John McCall3ce3d232019-12-13 03:37:23 -05007202 ASTRecordReader Record(*this, *Loc.F);
7203 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007204 if (!MaybeRecCode) {
7205 Error(MaybeRecCode.takeError());
7206 return nullptr;
7207 }
7208 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007209 Error("malformed AST file: missing C++ ctor initializers");
7210 return nullptr;
7211 }
7212
John McCall3ce3d232019-12-13 03:37:23 -05007213 return Record.readCXXCtorInitializers();
Richard Smithc2bb8182015-03-24 06:36:48 +00007214}
7215
Guy Benyei11169dd2012-12-18 14:30:41 +00007216CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007217 assert(ContextObj && "reading base specifiers with no AST context");
7218 ASTContext &Context = *ContextObj;
7219
Guy Benyei11169dd2012-12-18 14:30:41 +00007220 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007221 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007222 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007223 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7224 Error(std::move(Err));
7225 return nullptr;
7226 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 ReadingKindTracker ReadingKind(Read_Decl, *this);
JF Bastien0e828952019-06-26 19:50:12 +00007228
7229 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7230 if (!MaybeCode) {
7231 Error(MaybeCode.takeError());
7232 return nullptr;
7233 }
7234 unsigned Code = MaybeCode.get();
7235
John McCall3ce3d232019-12-13 03:37:23 -05007236 ASTRecordReader Record(*this, *Loc.F);
7237 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007238 if (!MaybeRecCode) {
7239 Error(MaybeCode.takeError());
7240 return nullptr;
7241 }
7242 unsigned RecCode = MaybeRecCode.get();
7243
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007245 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007246 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 }
7248
John McCall3ce3d232019-12-13 03:37:23 -05007249 unsigned NumBases = Record.readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00007250 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007251 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007252 for (unsigned I = 0; I != NumBases; ++I)
John McCall3ce3d232019-12-13 03:37:23 -05007253 Bases[I] = Record.readCXXBaseSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 return Bases;
7255}
7256
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007257serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007258ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7259 if (LocalID < NUM_PREDEF_DECL_IDS)
7260 return LocalID;
7261
Richard Smith37a93df2017-02-18 00:32:02 +00007262 if (!F.ModuleOffsetMap.empty())
7263 ReadModuleOffsetMap(F);
7264
Guy Benyei11169dd2012-12-18 14:30:41 +00007265 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7266 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7267 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007268
Guy Benyei11169dd2012-12-18 14:30:41 +00007269 return LocalID + I->second;
7270}
7271
7272bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7273 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007274 // Predefined decls aren't from any module.
7275 if (ID < NUM_PREDEF_DECL_IDS)
7276 return false;
7277
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007278 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007279 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007280}
7281
Douglas Gregor9f782892013-01-21 15:25:38 +00007282ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007284 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007285 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7286 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7287 return I->second;
7288}
7289
7290SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7291 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007292 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007293
Guy Benyei11169dd2012-12-18 14:30:41 +00007294 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7295
7296 if (Index > DeclsLoaded.size()) {
7297 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007298 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007299 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007300
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 if (Decl *D = DeclsLoaded[Index])
7302 return D->getLocation();
7303
Richard Smithcb34bd32016-03-27 07:28:06 +00007304 SourceLocation Loc;
7305 DeclCursorForID(ID, Loc);
7306 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007307}
7308
Richard Smithfe620d22015-03-05 23:24:12 +00007309static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7310 switch (ID) {
7311 case PREDEF_DECL_NULL_ID:
7312 return nullptr;
7313
7314 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7315 return Context.getTranslationUnitDecl();
7316
7317 case PREDEF_DECL_OBJC_ID_ID:
7318 return Context.getObjCIdDecl();
7319
7320 case PREDEF_DECL_OBJC_SEL_ID:
7321 return Context.getObjCSelDecl();
7322
7323 case PREDEF_DECL_OBJC_CLASS_ID:
7324 return Context.getObjCClassDecl();
7325
7326 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7327 return Context.getObjCProtocolDecl();
7328
7329 case PREDEF_DECL_INT_128_ID:
7330 return Context.getInt128Decl();
7331
7332 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7333 return Context.getUInt128Decl();
7334
7335 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7336 return Context.getObjCInstanceTypeDecl();
7337
7338 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7339 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007340
Richard Smith9b88a4c2015-07-27 05:40:23 +00007341 case PREDEF_DECL_VA_LIST_TAG:
7342 return Context.getVaListTagDecl();
7343
Charles Davisc7d5c942015-09-17 20:55:33 +00007344 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7345 return Context.getBuiltinMSVaListDecl();
7346
Richard Smithbab6df82020-04-11 22:15:29 -07007347 case PREDEF_DECL_BUILTIN_MS_GUID_ID:
7348 return Context.getMSGuidTagDecl();
7349
Richard Smithf19e1272015-03-07 00:04:49 +00007350 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7351 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007352
7353 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7354 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007355
7356 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7357 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007358
7359 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7360 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007361
7362 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7363 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007364 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007365 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007366}
7367
Richard Smithcd45dbc2014-04-19 03:48:30 +00007368Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007369 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007370 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007371 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007372 if (D) {
7373 // Track that we have merged the declaration with ID \p ID into the
7374 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007375 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007376 if (Merged.empty())
7377 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 }
Richard Smithfe620d22015-03-05 23:24:12 +00007379 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007380 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007381
Guy Benyei11169dd2012-12-18 14:30:41 +00007382 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7383
7384 if (Index >= DeclsLoaded.size()) {
7385 assert(0 && "declaration ID out-of-range for AST file");
7386 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007387 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007389
7390 return DeclsLoaded[Index];
7391}
7392
7393Decl *ASTReader::GetDecl(DeclID ID) {
7394 if (ID < NUM_PREDEF_DECL_IDS)
7395 return GetExistingDecl(ID);
7396
7397 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7398
7399 if (Index >= DeclsLoaded.size()) {
7400 assert(0 && "declaration ID out-of-range for AST file");
7401 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007402 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007403 }
7404
Guy Benyei11169dd2012-12-18 14:30:41 +00007405 if (!DeclsLoaded[Index]) {
7406 ReadDeclRecord(ID);
7407 if (DeserializationListener)
7408 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7409 }
7410
7411 return DeclsLoaded[Index];
7412}
7413
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007414DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007415 DeclID GlobalID) {
7416 if (GlobalID < NUM_PREDEF_DECL_IDS)
7417 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007418
Guy Benyei11169dd2012-12-18 14:30:41 +00007419 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7420 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7421 ModuleFile *Owner = I->second;
7422
7423 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7424 = M.GlobalToLocalDeclIDs.find(Owner);
7425 if (Pos == M.GlobalToLocalDeclIDs.end())
7426 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007427
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 return GlobalID - Owner->BaseDeclID + Pos->second;
7429}
7430
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007431serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007432 const RecordData &Record,
7433 unsigned &Idx) {
7434 if (Idx >= Record.size()) {
7435 Error("Corrupted AST file");
7436 return 0;
7437 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007438
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 return getGlobalDeclID(F, Record[Idx++]);
7440}
7441
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007442/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007443///
7444/// This operation will read a new statement from the external
7445/// source each time it is called, and is meant to be used via a
7446/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7447Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7448 // Switch case IDs are per Decl.
7449 ClearSwitchCaseIDs();
7450
7451 // Offset here is a global offset across the entire chain.
7452 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007453 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7454 Error(std::move(Err));
7455 return nullptr;
7456 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007457 assert(NumCurrentElementsDeserializing == 0 &&
7458 "should not be called while already deserializing");
7459 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 return ReadStmtFromStream(*Loc.F);
7461}
7462
Richard Smith3cb15722015-08-05 22:41:45 +00007463void ASTReader::FindExternalLexicalDecls(
7464 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7465 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007466 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7467
Richard Smith9ccdd932015-08-06 22:14:12 +00007468 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007469 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7470 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7471 auto K = (Decl::Kind)+LexicalDecls[I];
7472 if (!IsKindWeWant(K))
7473 continue;
7474
7475 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7476
7477 // Don't add predefined declarations to the lexical context more
7478 // than once.
7479 if (ID < NUM_PREDEF_DECL_IDS) {
7480 if (PredefsVisited[ID])
7481 continue;
7482
7483 PredefsVisited[ID] = true;
7484 }
7485
7486 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007487 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007488 if (!DC->isDeclInLexicalTraversal(D))
7489 Decls.push_back(D);
7490 }
7491 }
7492 };
7493
7494 if (isa<TranslationUnitDecl>(DC)) {
7495 for (auto Lexical : TULexicalDecls)
7496 Visit(Lexical.first, Lexical.second);
7497 } else {
7498 auto I = LexicalDecls.find(DC);
7499 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007500 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007501 }
7502
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007504}
7505
7506namespace {
7507
7508class DeclIDComp {
7509 ASTReader &Reader;
7510 ModuleFile &Mod;
7511
7512public:
7513 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7514
7515 bool operator()(LocalDeclID L, LocalDeclID R) const {
7516 SourceLocation LHS = getLocation(L);
7517 SourceLocation RHS = getLocation(R);
7518 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7519 }
7520
7521 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7522 SourceLocation RHS = getLocation(R);
7523 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7524 }
7525
7526 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7527 SourceLocation LHS = getLocation(L);
7528 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7529 }
7530
7531 SourceLocation getLocation(LocalDeclID ID) const {
7532 return Reader.getSourceManager().getFileLoc(
7533 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7534 }
7535};
7536
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007537} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007538
7539void ASTReader::FindFileRegionDecls(FileID File,
7540 unsigned Offset, unsigned Length,
7541 SmallVectorImpl<Decl *> &Decls) {
7542 SourceManager &SM = getSourceManager();
7543
7544 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7545 if (I == FileDeclIDs.end())
7546 return;
7547
7548 FileDeclsInfo &DInfo = I->second;
7549 if (DInfo.Decls.empty())
7550 return;
7551
7552 SourceLocation
7553 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7554 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7555
7556 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007557 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7558 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007559 if (BeginIt != DInfo.Decls.begin())
7560 --BeginIt;
7561
7562 // If we are pointing at a top-level decl inside an objc container, we need
7563 // to backtrack until we find it otherwise we will fail to report that the
7564 // region overlaps with an objc container.
7565 while (BeginIt != DInfo.Decls.begin() &&
7566 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7567 ->isTopLevelDeclInObjCContainer())
7568 --BeginIt;
7569
Fangrui Song7264a472019-07-03 08:13:17 +00007570 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7571 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007572 if (EndIt != DInfo.Decls.end())
7573 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007574
Guy Benyei11169dd2012-12-18 14:30:41 +00007575 for (ArrayRef<serialization::LocalDeclID>::iterator
7576 DIt = BeginIt; DIt != EndIt; ++DIt)
7577 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7578}
7579
Richard Smith9ce12e32013-02-07 03:30:24 +00007580bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007581ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7582 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007583 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007584 "DeclContext has no visible decls in storage");
7585 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007586 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007587
Richard Smithd88a7f12015-09-01 20:35:42 +00007588 auto It = Lookups.find(DC);
7589 if (It == Lookups.end())
7590 return false;
7591
Richard Smith8c913ec2014-08-14 02:21:01 +00007592 Deserializing LookupResults(this);
7593
Richard Smithd88a7f12015-09-01 20:35:42 +00007594 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007595 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007596 for (DeclID ID : It->second.Table.find(Name)) {
7597 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007598 if (ND->getDeclName() == Name)
7599 Decls.push_back(ND);
7600 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007601
Guy Benyei11169dd2012-12-18 14:30:41 +00007602 ++NumVisibleDeclContextsRead;
7603 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007604 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007605}
7606
Guy Benyei11169dd2012-12-18 14:30:41 +00007607void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7608 if (!DC->hasExternalVisibleStorage())
7609 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007610
7611 auto It = Lookups.find(DC);
7612 assert(It != Lookups.end() &&
7613 "have external visible storage but no lookup tables");
7614
Craig Topper79be4cd2013-07-05 04:33:53 +00007615 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007616
Vedant Kumar48b4f762018-04-14 01:40:48 +00007617 for (DeclID ID : It->second.Table.findAll()) {
7618 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007619 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 }
7621
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 ++NumVisibleDeclContextsRead;
7623
Vedant Kumar48b4f762018-04-14 01:40:48 +00007624 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7625 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7626 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007627 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7628}
7629
Richard Smithd88a7f12015-09-01 20:35:42 +00007630const serialization::reader::DeclContextLookupTable *
7631ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7632 auto I = Lookups.find(Primary);
7633 return I == Lookups.end() ? nullptr : &I->second;
7634}
7635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007636/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007637/// before receiving the implementation, and codegen depends on this.
7638/// We simulate this by deserializing and passing to consumer the methods of the
7639/// implementation before passing the deserialized implementation decl.
7640static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7641 ASTConsumer *Consumer) {
7642 assert(ImplD && Consumer);
7643
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007644 for (auto *I : ImplD->methods())
7645 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007646
7647 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7648}
7649
Guy Benyei11169dd2012-12-18 14:30:41 +00007650void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007651 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007652 PassObjCImplDeclToConsumer(ImplD, Consumer);
7653 else
7654 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7655}
7656
7657void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7658 this->Consumer = Consumer;
7659
Richard Smith9e2341d2015-03-23 03:25:59 +00007660 if (Consumer)
7661 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007662
7663 if (DeserializationListener)
7664 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007665}
7666
7667void ASTReader::PrintStats() {
7668 std::fprintf(stderr, "*** AST File Statistics:\n");
7669
7670 unsigned NumTypesLoaded
7671 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7672 QualType());
7673 unsigned NumDeclsLoaded
7674 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007675 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007676 unsigned NumIdentifiersLoaded
7677 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7678 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007679 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007680 unsigned NumMacrosLoaded
7681 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7682 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007683 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 unsigned NumSelectorsLoaded
7685 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7686 SelectorsLoaded.end(),
7687 Selector());
7688
7689 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7690 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7691 NumSLocEntriesRead, TotalNumSLocEntries,
7692 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7693 if (!TypesLoaded.empty())
7694 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7695 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7696 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7697 if (!DeclsLoaded.empty())
7698 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7699 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7700 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7701 if (!IdentifiersLoaded.empty())
7702 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7703 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7704 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7705 if (!MacrosLoaded.empty())
7706 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7707 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7708 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7709 if (!SelectorsLoaded.empty())
7710 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7711 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7712 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7713 if (TotalNumStatements)
7714 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7715 NumStatementsRead, TotalNumStatements,
7716 ((float)NumStatementsRead/TotalNumStatements * 100));
7717 if (TotalNumMacros)
7718 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7719 NumMacrosRead, TotalNumMacros,
7720 ((float)NumMacrosRead/TotalNumMacros * 100));
7721 if (TotalLexicalDeclContexts)
7722 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7723 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7724 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7725 * 100));
7726 if (TotalVisibleDeclContexts)
7727 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7728 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7729 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7730 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007731 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007732 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7733 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7734 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7735 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007736 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007737 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7738 NumMethodPoolHits, NumMethodPoolLookups,
7739 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007740 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007741 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7742 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7743 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7744 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007745 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007746 std::fprintf(stderr,
7747 " %u / %u identifier table lookups succeeded (%f%%)\n",
7748 NumIdentifierLookupHits, NumIdentifierLookups,
7749 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007750
Douglas Gregore060e572013-01-25 01:03:03 +00007751 if (GlobalIndex) {
7752 std::fprintf(stderr, "\n");
7753 GlobalIndex->printStats();
7754 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007755
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 std::fprintf(stderr, "\n");
7757 dump();
7758 std::fprintf(stderr, "\n");
7759}
7760
7761template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007762LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007763dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007764 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007765 InitialCapacity> &Map) {
7766 if (Map.begin() == Map.end())
7767 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007768
Vedant Kumar48b4f762018-04-14 01:40:48 +00007769 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7770
Guy Benyei11169dd2012-12-18 14:30:41 +00007771 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007772 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7773 I != IEnd; ++I) {
7774 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7775 << "\n";
7776 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007777}
7778
Yaron Kerencdae9412016-01-29 19:38:18 +00007779LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7781 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7782 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7783 dumpModuleIDMap("Global type map", GlobalTypeMap);
7784 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7785 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7786 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7787 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7788 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007789 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007791
Guy Benyei11169dd2012-12-18 14:30:41 +00007792 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007793 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007794 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007795}
7796
7797/// Return the amount of memory used by memory buffers, breaking down
7798/// by heap-backed versus mmap'ed memory.
7799void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007800 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007801 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007802 size_t bytes = buf->getBufferSize();
7803 switch (buf->getBufferKind()) {
7804 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7805 sizes.malloc_bytes += bytes;
7806 break;
7807 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7808 sizes.mmap_bytes += bytes;
7809 break;
7810 }
7811 }
7812 }
7813}
7814
7815void ASTReader::InitializeSema(Sema &S) {
7816 SemaObj = &S;
7817 S.addExternalSource(this);
7818
7819 // Makes sure any declarations that were deserialized "too early"
7820 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007821 for (uint64_t ID : PreloadedDeclIDs) {
7822 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007823 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007824 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007825 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007826
Richard Smith3d8e97e2013-10-18 06:54:39 +00007827 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 if (!FPPragmaOptions.empty()) {
7829 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Melanie Blower8812b0c2020-04-16 08:45:26 -07007830 SemaObj->CurFPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007831 }
7832
Yaxun Liu5b746652016-12-18 05:18:55 +00007833 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7834 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7835 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007836
7837 UpdateSema();
7838}
7839
7840void ASTReader::UpdateSema() {
7841 assert(SemaObj && "no Sema to update");
7842
7843 // Load the offsets of the declarations that Sema references.
7844 // They will be lazily deserialized when needed.
7845 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007846 assert(SemaDeclRefs.size() % 3 == 0);
7847 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007848 if (!SemaObj->StdNamespace)
7849 SemaObj->StdNamespace = SemaDeclRefs[I];
7850 if (!SemaObj->StdBadAlloc)
7851 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007852 if (!SemaObj->StdAlignValT)
7853 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007854 }
7855 SemaDeclRefs.clear();
7856 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007857
Nico Weber779355f2016-03-02 23:22:00 +00007858 // Update the state of pragmas. Use the same API as if we had encountered the
7859 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007860 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007861 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007862 if (PragmaMSStructState != -1)
7863 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007864 if (PointersToMembersPragmaLocation.isValid()) {
7865 SemaObj->ActOnPragmaMSPointersToMembers(
7866 (LangOptions::PragmaMSPointersToMembersKind)
7867 PragmaMSPointersToMembersState,
7868 PointersToMembersPragmaLocation);
7869 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007870 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007871
7872 if (PragmaPackCurrentValue) {
7873 // The bottom of the stack might have a default value. It must be adjusted
7874 // to the current value to ensure that the packing state is preserved after
7875 // popping entries that were included/imported from a PCH/module.
7876 bool DropFirst = false;
7877 if (!PragmaPackStack.empty() &&
7878 PragmaPackStack.front().Location.isInvalid()) {
7879 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7880 "Expected a default alignment value");
7881 SemaObj->PackStack.Stack.emplace_back(
7882 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007883 SemaObj->PackStack.CurrentPragmaLocation,
7884 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007885 DropFirst = true;
7886 }
7887 for (const auto &Entry :
7888 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7889 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007890 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007891 if (PragmaPackCurrentLocation.isInvalid()) {
7892 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7893 "Expected a default alignment value");
7894 // Keep the current values.
7895 } else {
7896 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7897 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7898 }
7899 }
Melanie Blowerf5360d42020-05-01 10:32:06 -07007900 if (FpPragmaCurrentValue) {
7901 // The bottom of the stack might have a default value. It must be adjusted
7902 // to the current value to ensure that fp-pragma state is preserved after
7903 // popping entries that were included/imported from a PCH/module.
7904 bool DropFirst = false;
7905 if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
7906 assert(FpPragmaStack.front().Value ==
7907 SemaObj->FpPragmaStack.DefaultValue &&
7908 "Expected a default pragma float_control value");
7909 SemaObj->FpPragmaStack.Stack.emplace_back(
7910 FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
7911 SemaObj->FpPragmaStack.CurrentPragmaLocation,
7912 FpPragmaStack.front().PushLocation);
7913 DropFirst = true;
7914 }
7915 for (const auto &Entry :
7916 llvm::makeArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
7917 SemaObj->FpPragmaStack.Stack.emplace_back(
7918 Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
7919 if (FpPragmaCurrentLocation.isInvalid()) {
7920 assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
7921 "Expected a default pragma float_control value");
7922 // Keep the current values.
7923 } else {
7924 SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
7925 SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
7926 }
7927 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007928}
7929
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007930IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 // Note that we are loading an identifier.
7932 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007933
Douglas Gregor7211ac12013-01-25 23:32:03 +00007934 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007935 NumIdentifierLookups,
7936 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007937
7938 // We don't need to do identifier table lookups in C++ modules (we preload
7939 // all interesting declarations, and don't need to use the scope for name
7940 // lookups). Perform the lookup in PCH files, though, since we don't build
7941 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007942 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007943 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007944 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007945 break;
7946 } else {
7947 // If there is a global index, look there first to determine which modules
7948 // provably do not have any results for this identifier.
7949 GlobalModuleIndex::HitSet Hits;
7950 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7951 if (!loadGlobalIndex()) {
7952 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7953 HitsPtr = &Hits;
7954 }
7955 }
7956
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007957 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007958 }
7959
Guy Benyei11169dd2012-12-18 14:30:41 +00007960 IdentifierInfo *II = Visitor.getIdentifierInfo();
7961 markIdentifierUpToDate(II);
7962 return II;
7963}
7964
7965namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007966
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007967 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007968 /// identifiers stored within a set of AST files.
7969 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007970 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 const ASTReader &Reader;
7972
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007973 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 /// the AST reader.
7975 unsigned Index;
7976
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007977 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 /// of the current AST file.
7979 ASTIdentifierLookupTable::key_iterator Current;
7980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007981 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 /// the current AST file.
7983 ASTIdentifierLookupTable::key_iterator End;
7984
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007985 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007986 bool SkipModules;
7987
Guy Benyei11169dd2012-12-18 14:30:41 +00007988 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007989 explicit ASTIdentifierIterator(const ASTReader &Reader,
7990 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007991
Craig Topper3e89dfe2014-03-13 02:13:41 +00007992 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007994
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007995} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007996
Ben Langmuir537c5b52016-05-04 00:53:13 +00007997ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7998 bool SkipModules)
7999 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008000}
8001
8002StringRef ASTIdentifierIterator::Next() {
8003 while (Current == End) {
8004 // If we have exhausted all of our AST files, we're done.
8005 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008006 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00008007
8008 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00008009 ModuleFile &F = Reader.ModuleMgr[Index];
8010 if (SkipModules && F.isModule())
8011 continue;
8012
Vedant Kumar48b4f762018-04-14 01:40:48 +00008013 ASTIdentifierLookupTable *IdTable =
8014 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 Current = IdTable->key_begin();
8016 End = IdTable->key_end();
8017 }
8018
8019 // We have any identifiers remaining in the current AST file; return
8020 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008021 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00008022 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008023 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00008024}
8025
Ben Langmuir537c5b52016-05-04 00:53:13 +00008026namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008027
Ben Langmuir537c5b52016-05-04 00:53:13 +00008028/// A utility for appending two IdentifierIterators.
8029class ChainedIdentifierIterator : public IdentifierIterator {
8030 std::unique_ptr<IdentifierIterator> Current;
8031 std::unique_ptr<IdentifierIterator> Queued;
8032
8033public:
8034 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8035 std::unique_ptr<IdentifierIterator> Second)
8036 : Current(std::move(First)), Queued(std::move(Second)) {}
8037
8038 StringRef Next() override {
8039 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008040 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008041
8042 StringRef result = Current->Next();
8043 if (!result.empty())
8044 return result;
8045
8046 // Try the queued iterator, which may itself be empty.
8047 Current.reset();
8048 std::swap(Current, Queued);
8049 return Next();
8050 }
8051};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008052
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008053} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008054
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008055IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008056 if (!loadGlobalIndex()) {
8057 std::unique_ptr<IdentifierIterator> ReaderIter(
8058 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8059 std::unique_ptr<IdentifierIterator> ModulesIter(
8060 GlobalIndex->createIdentifierIterator());
8061 return new ChainedIdentifierIterator(std::move(ReaderIter),
8062 std::move(ModulesIter));
8063 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008064
Guy Benyei11169dd2012-12-18 14:30:41 +00008065 return new ASTIdentifierIterator(*this);
8066}
8067
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008068namespace clang {
8069namespace serialization {
8070
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 class ReadMethodPoolVisitor {
8072 ASTReader &Reader;
8073 Selector Sel;
8074 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008075 unsigned InstanceBits = 0;
8076 unsigned FactoryBits = 0;
8077 bool InstanceHasMoreThanOneDecl = false;
8078 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008079 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8080 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008081
8082 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008083 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008085 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008086
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008087 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008088 if (!M.SelectorLookupTable)
8089 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008090
Guy Benyei11169dd2012-12-18 14:30:41 +00008091 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008092 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008093 return true;
8094
Richard Smithbdf2d932015-07-30 03:37:16 +00008095 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008096 ASTSelectorLookupTable *PoolTable
8097 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008098 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 if (Pos == PoolTable->end())
8100 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008101
Richard Smithbdf2d932015-07-30 03:37:16 +00008102 ++Reader.NumMethodPoolTableHits;
8103 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008104 // FIXME: Not quite happy with the statistics here. We probably should
8105 // disable this tracking when called via LoadSelector.
8106 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008107 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008109 if (Reader.DeserializationListener)
8110 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008111
Richard Smithbdf2d932015-07-30 03:37:16 +00008112 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8113 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8114 InstanceBits = Data.InstanceBits;
8115 FactoryBits = Data.FactoryBits;
8116 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8117 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 return true;
8119 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008120
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008121 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008122 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8123 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 }
8125
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008126 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008127 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 return FactoryMethods;
8129 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008130
8131 unsigned getInstanceBits() const { return InstanceBits; }
8132 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008133
Nico Weberff4b35e2014-12-27 22:14:15 +00008134 bool instanceHasMoreThanOneDecl() const {
8135 return InstanceHasMoreThanOneDecl;
8136 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008137
Nico Weberff4b35e2014-12-27 22:14:15 +00008138 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008139 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008140
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008141} // namespace serialization
8142} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008143
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008144/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008145static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8146 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008147 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8148 S.addMethodToGlobalList(&List, Methods[I]);
8149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008150}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008151
Guy Benyei11169dd2012-12-18 14:30:41 +00008152void ASTReader::ReadMethodPool(Selector Sel) {
8153 // Get the selector generation and update it to the current generation.
8154 unsigned &Generation = SelectorGeneration[Sel];
8155 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008156 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008157 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008158
Guy Benyei11169dd2012-12-18 14:30:41 +00008159 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008160 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008162 ModuleMgr.visit(Visitor);
8163
Guy Benyei11169dd2012-12-18 14:30:41 +00008164 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008165 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008167
8168 ++NumMethodPoolHits;
8169
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 if (!getSema())
8171 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008172
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 Sema &S = *getSema();
8174 Sema::GlobalMethodPool::iterator Pos
8175 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008176
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008177 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008178 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008179 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008180 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008181
8182 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8183 // when building a module we keep every method individually and may need to
8184 // update hasMoreThanOneDecl as we add the methods.
8185 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8186 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008187}
8188
Manman Rena0f31a02016-04-29 19:04:05 +00008189void ASTReader::updateOutOfDateSelector(Selector Sel) {
8190 if (SelectorOutOfDate[Sel])
8191 ReadMethodPool(Sel);
8192}
8193
Guy Benyei11169dd2012-12-18 14:30:41 +00008194void ASTReader::ReadKnownNamespaces(
8195 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8196 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008197
Vedant Kumar48b4f762018-04-14 01:40:48 +00008198 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8199 if (NamespaceDecl *Namespace
8200 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008201 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008202 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008203}
8204
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008205void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008206 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008207 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008208 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008209 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008210 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008211 Undefined.insert(std::make_pair(D, Loc));
8212 }
8213}
Nick Lewycky8334af82013-01-26 00:35:08 +00008214
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008215void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8216 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8217 Exprs) {
8218 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008219 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008220 uint64_t Count = DelayedDeleteExprs[Idx++];
8221 for (uint64_t C = 0; C < Count; ++C) {
8222 SourceLocation DeleteLoc =
8223 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8224 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8225 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8226 }
8227 }
8228}
8229
Guy Benyei11169dd2012-12-18 14:30:41 +00008230void ASTReader::ReadTentativeDefinitions(
8231 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008232 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8233 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 if (Var)
8235 TentativeDefs.push_back(Var);
8236 }
8237 TentativeDefinitions.clear();
8238}
8239
8240void ASTReader::ReadUnusedFileScopedDecls(
8241 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008242 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8243 DeclaratorDecl *D
8244 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008245 if (D)
8246 Decls.push_back(D);
8247 }
8248 UnusedFileScopedDecls.clear();
8249}
8250
8251void ASTReader::ReadDelegatingConstructors(
8252 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008253 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8254 CXXConstructorDecl *D
8255 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 if (D)
8257 Decls.push_back(D);
8258 }
8259 DelegatingCtorDecls.clear();
8260}
8261
8262void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008263 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8264 TypedefNameDecl *D
8265 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008266 if (D)
8267 Decls.push_back(D);
8268 }
8269 ExtVectorDecls.clear();
8270}
8271
Nico Weber72889432014-09-06 01:25:55 +00008272void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8273 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008274 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8275 ++I) {
8276 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8277 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008278 if (D)
8279 Decls.insert(D);
8280 }
8281 UnusedLocalTypedefNameCandidates.clear();
8282}
8283
Yaxun (Sam) Liub670ab72020-02-26 10:57:39 -05008284void ASTReader::ReadDeclsToCheckForDeferredDiags(
8285 llvm::SmallVector<Decl *, 4> &Decls) {
8286 for (unsigned I = 0, N = DeclsToCheckForDeferredDiags.size(); I != N;
8287 ++I) {
8288 auto *D = dyn_cast_or_null<Decl>(
8289 GetDecl(DeclsToCheckForDeferredDiags[I]));
8290 if (D)
8291 Decls.push_back(D);
8292 }
8293 DeclsToCheckForDeferredDiags.clear();
8294}
8295
8296
Guy Benyei11169dd2012-12-18 14:30:41 +00008297void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008298 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 if (ReferencedSelectorsData.empty())
8300 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008301
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 // If there are @selector references added them to its pool. This is for
8303 // implementation of -Wselector.
8304 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8305 unsigned I = 0;
8306 while (I < DataSize) {
8307 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8308 SourceLocation SelLoc
8309 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8310 Sels.push_back(std::make_pair(Sel, SelLoc));
8311 }
8312 ReferencedSelectorsData.clear();
8313}
8314
8315void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008316 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008317 if (WeakUndeclaredIdentifiers.empty())
8318 return;
8319
8320 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008321 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008323 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008324 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8325 SourceLocation Loc
8326 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8327 bool Used = WeakUndeclaredIdentifiers[I++];
8328 WeakInfo WI(AliasId, Loc);
8329 WI.setUsed(Used);
8330 WeakIDs.push_back(std::make_pair(WeakId, WI));
8331 }
8332 WeakUndeclaredIdentifiers.clear();
8333}
8334
8335void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8336 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8337 ExternalVTableUse VT;
8338 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8339 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8340 VT.DefinitionRequired = VTableUses[Idx++];
8341 VTables.push_back(VT);
8342 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008343
Guy Benyei11169dd2012-12-18 14:30:41 +00008344 VTableUses.clear();
8345}
8346
8347void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008348 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008350 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008351 SourceLocation Loc
8352 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8353
8354 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008355 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 PendingInstantiations.clear();
8357}
8358
Richard Smithe40f2ba2013-08-07 21:41:30 +00008359void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008360 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8361 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008362 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8363 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008364 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008365
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008366 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008367 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8368
8369 ModuleFile *F = getOwningModuleFile(LT->D);
8370 assert(F && "No module");
8371
8372 unsigned TokN = LateParsedTemplates[Idx++];
8373 LT->Toks.reserve(TokN);
8374 for (unsigned T = 0; T < TokN; ++T)
8375 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8376
Justin Lebar28f09c52016-10-10 16:26:08 +00008377 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008378 }
8379
8380 LateParsedTemplates.clear();
8381}
8382
Guy Benyei11169dd2012-12-18 14:30:41 +00008383void ASTReader::LoadSelector(Selector Sel) {
8384 // It would be complicated to avoid reading the methods anyway. So don't.
8385 ReadMethodPool(Sel);
8386}
8387
8388void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8389 assert(ID && "Non-zero identifier ID required");
8390 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8391 IdentifiersLoaded[ID - 1] = II;
8392 if (DeserializationListener)
8393 DeserializationListener->IdentifierRead(ID, II);
8394}
8395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008396/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008397/// identifier.
8398///
8399/// If the AST reader is currently in a state where the given declaration IDs
8400/// cannot safely be resolved, they are queued until it is safe to resolve
8401/// them.
8402///
8403/// \param II an IdentifierInfo that refers to one or more globally-visible
8404/// declarations.
8405///
8406/// \param DeclIDs the set of declaration IDs with the name @p II that are
8407/// visible at global scope.
8408///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008409/// \param Decls if non-null, this vector will be populated with the set of
8410/// deserialized declarations. These declarations will not be pushed into
8411/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008412void
8413ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8414 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008415 SmallVectorImpl<Decl *> *Decls) {
8416 if (NumCurrentElementsDeserializing && !Decls) {
8417 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008418 return;
8419 }
8420
Vedant Kumar48b4f762018-04-14 01:40:48 +00008421 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008422 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008423 // Queue this declaration so that it will be added to the
8424 // translation unit scope and identifier's declaration chain
8425 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008426 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008427 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008428 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008429
Vedant Kumar48b4f762018-04-14 01:40:48 +00008430 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008431
8432 // If we're simply supposed to record the declarations, do so now.
8433 if (Decls) {
8434 Decls->push_back(D);
8435 continue;
8436 }
8437
8438 // Introduce this declaration into the translation-unit scope
8439 // and add it to the declaration chain for this identifier, so
8440 // that (unqualified) name lookup will find it.
8441 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008442 }
8443}
8444
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008445IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008447 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008448
8449 if (IdentifiersLoaded.empty()) {
8450 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008451 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008452 }
8453
8454 ID -= 1;
8455 if (!IdentifiersLoaded[ID]) {
8456 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8457 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8458 ModuleFile *M = I->second;
8459 unsigned Index = ID - M->BaseIdentifierID;
8460 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8461
8462 // All of the strings in the AST file are preceded by a 16-bit length.
8463 // Extract that 16-bit length to avoid having to execute strlen().
8464 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8465 // unsigned integers. This is important to avoid integer overflow when
8466 // we cast them to 'unsigned'.
8467 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8468 unsigned StrLen = (((unsigned) StrLenPtr[0])
8469 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008470 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8471 IdentifiersLoaded[ID] = &II;
8472 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008473 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008474 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008475 }
8476
8477 return IdentifiersLoaded[ID];
8478}
8479
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008480IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8481 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008482}
8483
8484IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8485 if (LocalID < NUM_PREDEF_IDENT_IDS)
8486 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008487
Richard Smith37a93df2017-02-18 00:32:02 +00008488 if (!M.ModuleOffsetMap.empty())
8489 ReadModuleOffsetMap(M);
8490
Guy Benyei11169dd2012-12-18 14:30:41 +00008491 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8492 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008493 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008494 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008495
Guy Benyei11169dd2012-12-18 14:30:41 +00008496 return LocalID + I->second;
8497}
8498
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008499MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008500 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008501 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008502
8503 if (MacrosLoaded.empty()) {
8504 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008505 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 }
8507
8508 ID -= NUM_PREDEF_MACRO_IDS;
8509 if (!MacrosLoaded[ID]) {
8510 GlobalMacroMapType::iterator I
8511 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8512 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8513 ModuleFile *M = I->second;
8514 unsigned Index = ID - M->BaseMacroID;
Dmitry Polukhina7afb212020-04-16 09:24:46 -07008515 MacrosLoaded[ID] =
8516 ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008517
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008518 if (DeserializationListener)
8519 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8520 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008521 }
8522
8523 return MacrosLoaded[ID];
8524}
8525
8526MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8527 if (LocalID < NUM_PREDEF_MACRO_IDS)
8528 return LocalID;
8529
Richard Smith37a93df2017-02-18 00:32:02 +00008530 if (!M.ModuleOffsetMap.empty())
8531 ReadModuleOffsetMap(M);
8532
Guy Benyei11169dd2012-12-18 14:30:41 +00008533 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8534 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8535 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8536
8537 return LocalID + I->second;
8538}
8539
8540serialization::SubmoduleID
8541ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8542 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8543 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008544
Richard Smith37a93df2017-02-18 00:32:02 +00008545 if (!M.ModuleOffsetMap.empty())
8546 ReadModuleOffsetMap(M);
8547
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8549 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008550 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008551 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008552
Guy Benyei11169dd2012-12-18 14:30:41 +00008553 return LocalID + I->second;
8554}
8555
8556Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8557 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8558 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008559 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008560 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008561
Guy Benyei11169dd2012-12-18 14:30:41 +00008562 if (GlobalID > SubmodulesLoaded.size()) {
8563 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008564 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008565 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008566
Guy Benyei11169dd2012-12-18 14:30:41 +00008567 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8568}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008569
8570Module *ASTReader::getModule(unsigned ID) {
8571 return getSubmodule(ID);
8572}
8573
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008574bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8575 ModuleFile *MF = getOwningModuleFile(D);
8576 return MF && MF->PCHHasObjectFile;
8577}
8578
Richard Smithd88a7f12015-09-01 20:35:42 +00008579ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8580 if (ID & 1) {
8581 // It's a module, look it up by submodule ID.
8582 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8583 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8584 } else {
8585 // It's a prefix (preamble, PCH, ...). Look it up by index.
8586 unsigned IndexFromEnd = ID >> 1;
8587 assert(IndexFromEnd && "got reference to unknown module file");
8588 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8589 }
8590}
8591
8592unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8593 if (!F)
8594 return 1;
8595
8596 // For a file representing a module, use the submodule ID of the top-level
8597 // module as the file ID. For any other kind of file, the number of such
8598 // files loaded beforehand will be the same on reload.
8599 // FIXME: Is this true even if we have an explicit module file and a PCH?
8600 if (F->isModule())
8601 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8602
8603 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008604 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008605 assert(I != PCHModules.end() && "emitting reference to unknown file");
8606 return (I - PCHModules.end()) << 1;
8607}
8608
Reid Klecknerc915cb92020-02-27 18:13:54 -08008609llvm::Optional<ASTSourceDescriptor>
Adrian Prantl15bcf702015-06-30 17:39:43 +00008610ASTReader::getSourceDescriptor(unsigned ID) {
Adrian Prantlf4754ea2020-03-17 12:51:58 -07008611 if (Module *M = getSubmodule(ID))
Reid Klecknerc915cb92020-02-27 18:13:54 -08008612 return ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008613
8614 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008615 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008616 const auto &PCHChain = ModuleMgr.pch_modules();
8617 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008618 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008619 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008620 StringRef FileName = llvm::sys::path::filename(MF.FileName);
Reid Klecknerc915cb92020-02-27 18:13:54 -08008621 return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8622 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008623 }
8624 return None;
8625}
8626
David Blaikie1ac9c982017-04-11 21:13:37 +00008627ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008628 auto I = DefinitionSource.find(FD);
8629 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008630 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008631 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008632}
8633
Guy Benyei11169dd2012-12-18 14:30:41 +00008634Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8635 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8636}
8637
8638Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8639 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008640 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008641
8642 if (ID > SelectorsLoaded.size()) {
8643 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008644 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008645 }
8646
Craig Toppera13603a2014-05-22 05:54:18 +00008647 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008648 // Load this selector from the selector table.
8649 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8650 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8651 ModuleFile &M = *I->second;
8652 ASTSelectorLookupTrait Trait(*this, M);
8653 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8654 SelectorsLoaded[ID - 1] =
8655 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8656 if (DeserializationListener)
8657 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8658 }
8659
8660 return SelectorsLoaded[ID - 1];
8661}
8662
8663Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8664 return DecodeSelector(ID);
8665}
8666
8667uint32_t ASTReader::GetNumExternalSelectors() {
8668 // ID 0 (the null selector) is considered an external selector.
8669 return getTotalNumSelectors() + 1;
8670}
8671
8672serialization::SelectorID
8673ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8674 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8675 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008676
Richard Smith37a93df2017-02-18 00:32:02 +00008677 if (!M.ModuleOffsetMap.empty())
8678 ReadModuleOffsetMap(M);
8679
Guy Benyei11169dd2012-12-18 14:30:41 +00008680 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8681 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008682 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008683 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008684
Guy Benyei11169dd2012-12-18 14:30:41 +00008685 return LocalID + I->second;
8686}
8687
John McCall3ce3d232019-12-13 03:37:23 -05008688DeclarationNameLoc
8689ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8690 DeclarationNameLoc DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008691 switch (Name.getNameKind()) {
8692 case DeclarationName::CXXConstructorName:
8693 case DeclarationName::CXXDestructorName:
8694 case DeclarationName::CXXConversionFunctionName:
John McCall3ce3d232019-12-13 03:37:23 -05008695 DNLoc.NamedType.TInfo = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008696 break;
8697
8698 case DeclarationName::CXXOperatorName:
8699 DNLoc.CXXOperatorName.BeginOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008700 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008701 DNLoc.CXXOperatorName.EndOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008702 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008703 break;
8704
8705 case DeclarationName::CXXLiteralOperatorName:
8706 DNLoc.CXXLiteralOperatorName.OpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008707 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008708 break;
8709
8710 case DeclarationName::Identifier:
8711 case DeclarationName::ObjCZeroArgSelector:
8712 case DeclarationName::ObjCOneArgSelector:
8713 case DeclarationName::ObjCMultiArgSelector:
8714 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008715 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008716 break;
8717 }
John McCall3ce3d232019-12-13 03:37:23 -05008718 return DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008719}
8720
John McCall3ce3d232019-12-13 03:37:23 -05008721DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8722 DeclarationNameInfo NameInfo;
8723 NameInfo.setName(readDeclarationName());
8724 NameInfo.setLoc(readSourceLocation());
8725 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8726 return NameInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +00008727}
8728
John McCall3ce3d232019-12-13 03:37:23 -05008729void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8730 Info.QualifierLoc = readNestedNameSpecifierLoc();
8731 unsigned NumTPLists = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008732 Info.NumTemplParamLists = NumTPLists;
8733 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008734 Info.TemplParamLists =
8735 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008736 for (unsigned i = 0; i != NumTPLists; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05008737 Info.TemplParamLists[i] = readTemplateParameterList();
Guy Benyei11169dd2012-12-18 14:30:41 +00008738 }
8739}
8740
Guy Benyei11169dd2012-12-18 14:30:41 +00008741TemplateParameterList *
John McCall3ce3d232019-12-13 03:37:23 -05008742ASTRecordReader::readTemplateParameterList() {
8743 SourceLocation TemplateLoc = readSourceLocation();
8744 SourceLocation LAngleLoc = readSourceLocation();
8745 SourceLocation RAngleLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008746
John McCall3ce3d232019-12-13 03:37:23 -05008747 unsigned NumParams = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008748 SmallVector<NamedDecl *, 16> Params;
8749 Params.reserve(NumParams);
8750 while (NumParams--)
John McCall3ce3d232019-12-13 03:37:23 -05008751 Params.push_back(readDeclAs<NamedDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00008752
John McCall3ce3d232019-12-13 03:37:23 -05008753 bool HasRequiresClause = readBool();
8754 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
Saar Raz0330fba2019-10-15 18:44:06 +00008755
Richard Smithdbafb6c2017-06-29 23:23:46 +00008756 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
Saar Raz0330fba2019-10-15 18:44:06 +00008757 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
Guy Benyei11169dd2012-12-18 14:30:41 +00008758 return TemplateParams;
8759}
8760
John McCall3ce3d232019-12-13 03:37:23 -05008761void ASTRecordReader::readTemplateArgumentList(
8762 SmallVectorImpl<TemplateArgument> &TemplArgs,
8763 bool Canonicalize) {
8764 unsigned NumTemplateArgs = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008765 TemplArgs.reserve(NumTemplateArgs);
8766 while (NumTemplateArgs--)
John McCall3ce3d232019-12-13 03:37:23 -05008767 TemplArgs.push_back(readTemplateArgument(Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008768}
8769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008770/// Read a UnresolvedSet structure.
John McCall3ce3d232019-12-13 03:37:23 -05008771void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8772 unsigned NumDecls = readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008773 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008774 while (NumDecls--) {
John McCall3ce3d232019-12-13 03:37:23 -05008775 DeclID ID = readDeclID();
8776 AccessSpecifier AS = (AccessSpecifier) readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008777 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008778 }
8779}
8780
8781CXXBaseSpecifier
John McCall3ce3d232019-12-13 03:37:23 -05008782ASTRecordReader::readCXXBaseSpecifier() {
8783 bool isVirtual = readBool();
8784 bool isBaseOfClass = readBool();
8785 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8786 bool inheritConstructors = readBool();
8787 TypeSourceInfo *TInfo = readTypeSourceInfo();
8788 SourceRange Range = readSourceRange();
8789 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008790 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008791 EllipsisLoc);
8792 Result.setInheritConstructors(inheritConstructors);
8793 return Result;
8794}
8795
Richard Smithc2bb8182015-03-24 06:36:48 +00008796CXXCtorInitializer **
John McCall3ce3d232019-12-13 03:37:23 -05008797ASTRecordReader::readCXXCtorInitializers() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008798 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008799 unsigned NumInitializers = readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008800 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008801 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008802 for (unsigned i = 0; i != NumInitializers; ++i) {
8803 TypeSourceInfo *TInfo = nullptr;
8804 bool IsBaseVirtual = false;
8805 FieldDecl *Member = nullptr;
8806 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008807
John McCall3ce3d232019-12-13 03:37:23 -05008808 CtorInitializerType Type = (CtorInitializerType) readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008809 switch (Type) {
8810 case CTOR_INITIALIZER_BASE:
John McCall3ce3d232019-12-13 03:37:23 -05008811 TInfo = readTypeSourceInfo();
8812 IsBaseVirtual = readBool();
Richard Smithc2bb8182015-03-24 06:36:48 +00008813 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008814
Richard Smithc2bb8182015-03-24 06:36:48 +00008815 case CTOR_INITIALIZER_DELEGATING:
John McCall3ce3d232019-12-13 03:37:23 -05008816 TInfo = readTypeSourceInfo();
Richard Smithc2bb8182015-03-24 06:36:48 +00008817 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008818
Richard Smithc2bb8182015-03-24 06:36:48 +00008819 case CTOR_INITIALIZER_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008820 Member = readDeclAs<FieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008821 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008822
Richard Smithc2bb8182015-03-24 06:36:48 +00008823 case CTOR_INITIALIZER_INDIRECT_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008824 IndirectMember = readDeclAs<IndirectFieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008825 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008826 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008827
John McCall3ce3d232019-12-13 03:37:23 -05008828 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8829 Expr *Init = readExpr();
8830 SourceLocation LParenLoc = readSourceLocation();
8831 SourceLocation RParenLoc = readSourceLocation();
Richard Smithc2bb8182015-03-24 06:36:48 +00008832
8833 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008834 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008835 BOMInit = new (Context)
8836 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8837 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008838 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008839 BOMInit = new (Context)
8840 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008841 else if (Member)
8842 BOMInit = new (Context)
8843 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8844 Init, RParenLoc);
8845 else
8846 BOMInit = new (Context)
8847 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8848 LParenLoc, Init, RParenLoc);
8849
John McCall3ce3d232019-12-13 03:37:23 -05008850 if (/*IsWritten*/readBool()) {
8851 unsigned SourceOrder = readInt();
Richard Smith30e304e2016-12-14 00:03:17 +00008852 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008853 }
8854
Richard Smithc2bb8182015-03-24 06:36:48 +00008855 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008856 }
8857
Richard Smithc2bb8182015-03-24 06:36:48 +00008858 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008859}
8860
Guy Benyei11169dd2012-12-18 14:30:41 +00008861NestedNameSpecifierLoc
John McCall3ce3d232019-12-13 03:37:23 -05008862ASTRecordReader::readNestedNameSpecifierLoc() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008863 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008864 unsigned N = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008865 NestedNameSpecifierLocBuilder Builder;
8866 for (unsigned I = 0; I != N; ++I) {
John McCalld505e572019-12-13 21:54:44 -05008867 auto Kind = readNestedNameSpecifierKind();
Guy Benyei11169dd2012-12-18 14:30:41 +00008868 switch (Kind) {
8869 case NestedNameSpecifier::Identifier: {
John McCall3ce3d232019-12-13 03:37:23 -05008870 IdentifierInfo *II = readIdentifier();
8871 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008872 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8873 break;
8874 }
8875
8876 case NestedNameSpecifier::Namespace: {
John McCall3ce3d232019-12-13 03:37:23 -05008877 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8878 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008879 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8880 break;
8881 }
8882
8883 case NestedNameSpecifier::NamespaceAlias: {
John McCall3ce3d232019-12-13 03:37:23 -05008884 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8885 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008886 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8887 break;
8888 }
8889
8890 case NestedNameSpecifier::TypeSpec:
8891 case NestedNameSpecifier::TypeSpecWithTemplate: {
John McCall3ce3d232019-12-13 03:37:23 -05008892 bool Template = readBool();
8893 TypeSourceInfo *T = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008894 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008895 return NestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -05008896 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008897
8898 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008899 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008900 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8901 T->getTypeLoc(), ColonColonLoc);
8902 break;
8903 }
8904
8905 case NestedNameSpecifier::Global: {
John McCall3ce3d232019-12-13 03:37:23 -05008906 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008907 Builder.MakeGlobal(Context, ColonColonLoc);
8908 break;
8909 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008910
8911 case NestedNameSpecifier::Super: {
John McCall3ce3d232019-12-13 03:37:23 -05008912 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8913 SourceRange Range = readSourceRange();
Nikola Smiljanic67860242014-09-26 00:28:20 +00008914 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8915 break;
8916 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008917 }
8918 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008919
Guy Benyei11169dd2012-12-18 14:30:41 +00008920 return Builder.getWithLocInContext(Context);
8921}
8922
8923SourceRange
8924ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8925 unsigned &Idx) {
8926 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8927 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8928 return SourceRange(beg, end);
8929}
8930
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008931static FixedPointSemantics
8932ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
8933 unsigned &Idx) {
8934 unsigned Width = Record[Idx++];
8935 unsigned Scale = Record[Idx++];
8936 uint64_t Tmp = Record[Idx++];
8937 bool IsSigned = Tmp & 0x1;
8938 bool IsSaturated = Tmp & 0x2;
8939 bool HasUnsignedPadding = Tmp & 0x4;
8940 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
8941 HasUnsignedPadding);
8942}
8943
John McCall3ce3d232019-12-13 03:37:23 -05008944static const llvm::fltSemantics &
8945readAPFloatSemantics(ASTRecordReader &reader) {
8946 return llvm::APFloatBase::EnumToSemantics(
8947 static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8948}
8949
8950APValue ASTRecordReader::readAPValue() {
8951 unsigned Kind = readInt();
John McCalld505e572019-12-13 21:54:44 -05008952 switch ((APValue::ValueKind) Kind) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008953 case APValue::None:
8954 return APValue();
8955 case APValue::Indeterminate:
8956 return APValue::IndeterminateValue();
8957 case APValue::Int:
John McCall3ce3d232019-12-13 03:37:23 -05008958 return APValue(readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008959 case APValue::Float: {
John McCall3ce3d232019-12-13 03:37:23 -05008960 const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8961 return APValue(readAPFloat(FloatSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008962 }
8963 case APValue::FixedPoint: {
8964 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
John McCall3ce3d232019-12-13 03:37:23 -05008965 return APValue(APFixedPoint(readAPInt(), FPSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008966 }
8967 case APValue::ComplexInt: {
John McCall3ce3d232019-12-13 03:37:23 -05008968 llvm::APSInt First = readAPSInt();
8969 return APValue(std::move(First), readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008970 }
8971 case APValue::ComplexFloat: {
John McCall3ce3d232019-12-13 03:37:23 -05008972 const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8973 llvm::APFloat First = readAPFloat(FloatSema1);
8974 const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8975 return APValue(std::move(First), readAPFloat(FloatSema2));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008976 }
8977 case APValue::LValue:
8978 case APValue::Vector:
8979 case APValue::Array:
8980 case APValue::Struct:
8981 case APValue::Union:
8982 case APValue::MemberPointer:
8983 case APValue::AddrLabelDiff:
8984 // TODO : Handle all these APValue::ValueKind.
8985 return APValue();
8986 }
8987 llvm_unreachable("Invalid APValue::ValueKind");
8988}
8989
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008990/// Read a floating-point value
John McCall3ce3d232019-12-13 03:37:23 -05008991llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8992 return llvm::APFloat(Sem, readAPInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00008993}
8994
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008995// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00008996std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8997 unsigned Len = Record[Idx++];
8998 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8999 Idx += Len;
9000 return Result;
9001}
9002
Richard Smith7ed1bc92014-12-05 22:42:13 +00009003std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9004 unsigned &Idx) {
9005 std::string Filename = ReadString(Record, Idx);
9006 ResolveImportedPath(F, Filename);
9007 return Filename;
9008}
9009
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009010std::string ASTReader::ReadPath(StringRef BaseDirectory,
9011 const RecordData &Record, unsigned &Idx) {
9012 std::string Filename = ReadString(Record, Idx);
9013 if (!BaseDirectory.empty())
9014 ResolveImportedPath(Filename, BaseDirectory);
9015 return Filename;
9016}
9017
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009018VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009019 unsigned &Idx) {
9020 unsigned Major = Record[Idx++];
9021 unsigned Minor = Record[Idx++];
9022 unsigned Subminor = Record[Idx++];
9023 if (Minor == 0)
9024 return VersionTuple(Major);
9025 if (Subminor == 0)
9026 return VersionTuple(Major, Minor - 1);
9027 return VersionTuple(Major, Minor - 1, Subminor - 1);
9028}
9029
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009030CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009031 const RecordData &Record,
9032 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009033 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009034 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009035}
9036
Richard Smith37a93df2017-02-18 00:32:02 +00009037DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009038 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009039}
9040
Richard Smith37a93df2017-02-18 00:32:02 +00009041DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009042 return Diags.Report(Loc, DiagID);
9043}
9044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009045/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009046/// preprocessor.
9047IdentifierTable &ASTReader::getIdentifierTable() {
9048 return PP.getIdentifierTable();
9049}
9050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009051/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009052/// statement.
9053void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009054 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009055 "Already have a SwitchCase with this ID");
9056 (*CurrSwitchCaseStmts)[ID] = SC;
9057}
9058
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009059/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009060SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009061 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009062 return (*CurrSwitchCaseStmts)[ID];
9063}
9064
9065void ASTReader::ClearSwitchCaseIDs() {
9066 CurrSwitchCaseStmts->clear();
9067}
9068
9069void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009070 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009071 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009072 for (SmallVectorImpl<std::pair<BitstreamCursor,
9073 serialization::ModuleFile *>>::iterator
9074 I = CommentsCursors.begin(),
9075 E = CommentsCursors.end();
9076 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009077 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009078 BitstreamCursor &Cursor = I->first;
9079 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009080 SavedStreamPosition SavedPosition(Cursor);
9081
9082 RecordData Record;
9083 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00009084 Expected<llvm::BitstreamEntry> MaybeEntry =
9085 Cursor.advanceSkippingSubblocks(
9086 BitstreamCursor::AF_DontPopBlockAtEnd);
9087 if (!MaybeEntry) {
9088 Error(MaybeEntry.takeError());
9089 return;
9090 }
9091 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009092
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009093 switch (Entry.Kind) {
9094 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9095 case llvm::BitstreamEntry::Error:
9096 Error("malformed block record in AST file");
9097 return;
9098 case llvm::BitstreamEntry::EndBlock:
9099 goto NextCursor;
9100 case llvm::BitstreamEntry::Record:
9101 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009102 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009103 }
9104
9105 // Read a record.
9106 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009107 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9108 if (!MaybeComment) {
9109 Error(MaybeComment.takeError());
9110 return;
9111 }
9112 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009113 case COMMENTS_RAW_COMMENT: {
9114 unsigned Idx = 0;
9115 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009116 RawComment::CommentKind Kind =
9117 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009118 bool IsTrailingComment = Record[Idx++];
9119 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009120 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009121 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009122 break;
9123 }
9124 }
9125 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009126 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009127 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9128 FileToOffsetToComment;
9129 for (RawComment *C : Comments) {
9130 SourceLocation CommentLoc = C->getBeginLoc();
9131 if (CommentLoc.isValid()) {
9132 std::pair<FileID, unsigned> Loc =
9133 SourceMgr.getDecomposedLoc(CommentLoc);
9134 if (Loc.first.isValid())
9135 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9136 }
9137 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009138 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009139}
9140
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009141void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9142 bool IncludeSystem, bool Complain,
9143 llvm::function_ref<void(const serialization::InputFile &IF,
9144 bool isSystem)> Visitor) {
9145 unsigned NumUserInputs = MF.NumUserInputFiles;
9146 unsigned NumInputs = MF.InputFilesLoaded.size();
9147 assert(NumUserInputs <= NumInputs);
9148 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9149 for (unsigned I = 0; I < N; ++I) {
9150 bool IsSystem = I >= NumUserInputs;
9151 InputFile IF = getInputFile(MF, I+1, Complain);
9152 Visitor(IF, IsSystem);
9153 }
9154}
9155
Richard Smithf3f84612017-06-29 02:19:42 +00009156void ASTReader::visitTopLevelModuleMaps(
9157 serialization::ModuleFile &MF,
9158 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9159 unsigned NumInputs = MF.InputFilesLoaded.size();
9160 for (unsigned I = 0; I < NumInputs; ++I) {
9161 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9162 if (IFI.TopLevelModuleMap)
9163 // FIXME: This unnecessarily re-reads the InputFileInfo.
9164 if (auto *FE = getInputFile(MF, I + 1).getFile())
9165 Visitor(FE);
9166 }
9167}
9168
Richard Smithcd45dbc2014-04-19 03:48:30 +00009169std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9170 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009171 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009172 return M->getFullModuleName();
9173
9174 // Otherwise, use the name of the top-level module the decl is within.
9175 if (ModuleFile *M = getOwningModuleFile(D))
9176 return M->ModuleName;
9177
9178 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009179 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009180}
9181
Guy Benyei11169dd2012-12-18 14:30:41 +00009182void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009183 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009184 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009185 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009186 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009187 // If any identifiers with corresponding top-level declarations have
9188 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009189 using TopLevelDeclsMap =
9190 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009191 TopLevelDeclsMap TopLevelDecls;
9192
Guy Benyei11169dd2012-12-18 14:30:41 +00009193 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009194 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009195 SmallVector<uint32_t, 4> DeclIDs =
9196 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009197 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009198
9199 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009200 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009201
Richard Smitha62d1982018-08-03 01:00:01 +00009202 // Load each function type that we deferred loading because it was a
9203 // deduced type that might refer to a local type declared within itself.
9204 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9205 auto *FD = PendingFunctionTypes[I].first;
9206 FD->setType(GetType(PendingFunctionTypes[I].second));
9207
9208 // If we gave a function a deduced return type, remember that we need to
9209 // propagate that along the redeclaration chain.
9210 auto *DT = FD->getReturnType()->getContainedDeducedType();
9211 if (DT && DT->isDeduced())
9212 PendingDeducedTypeUpdates.insert(
9213 {FD->getCanonicalDecl(), FD->getReturnType()});
9214 }
9215 PendingFunctionTypes.clear();
9216
Richard Smith851072e2014-05-19 20:59:20 +00009217 // For each decl chain that we wanted to complete while deserializing, mark
9218 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009219 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9220 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9221 }
Richard Smith851072e2014-05-19 20:59:20 +00009222 PendingIncompleteDeclChains.clear();
9223
Guy Benyei11169dd2012-12-18 14:30:41 +00009224 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009225 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009226 loadPendingDeclChain(PendingDeclChains[I].first,
9227 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009228 PendingDeclChains.clear();
9229
Douglas Gregor6168bd22013-02-18 15:53:43 +00009230 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009231 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9232 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9233 IdentifierInfo *II = TLD->first;
9234 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9235 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009236 }
9237 }
9238
Guy Benyei11169dd2012-12-18 14:30:41 +00009239 // Load any pending macro definitions.
9240 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009241 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9242 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9243 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9244 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009245 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009246 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009247 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009248 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009249 resolvePendingMacro(II, Info);
9250 }
9251 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009252 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009253 ++IDIdx) {
9254 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009255 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009256 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009257 }
9258 }
9259 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009260
9261 // Wire up the DeclContexts for Decls that we delayed setting until
9262 // recursive loading is completed.
9263 while (!PendingDeclContextInfos.empty()) {
9264 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9265 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009266 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9267 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009268 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9269 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009270
Richard Smithd1c46742014-04-30 02:24:17 +00009271 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009272 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009273 auto Update = PendingUpdateRecords.pop_back_val();
9274 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009275 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009276 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009277 }
Richard Smith8a639892015-01-24 01:07:20 +00009278
9279 // At this point, all update records for loaded decls are in place, so any
9280 // fake class definitions should have become real.
9281 assert(PendingFakeDefinitionData.empty() &&
9282 "faked up a class definition but never saw the real one");
9283
Guy Benyei11169dd2012-12-18 14:30:41 +00009284 // If we deserialized any C++ or Objective-C class definitions, any
9285 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009286 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009287 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009288 for (Decl *D : PendingDefinitions) {
9289 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9290 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009291 // Make sure that the TagType points at the definition.
9292 const_cast<TagType*>(TagT)->decl = TD;
9293 }
Richard Smith8ce51082015-03-11 01:44:51 +00009294
Vedant Kumar48b4f762018-04-14 01:40:48 +00009295 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009296 for (auto *R = getMostRecentExistingDecl(RD); R;
9297 R = R->getPreviousDecl()) {
9298 assert((R == D) ==
9299 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009300 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009301 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009302 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009303 }
9304
9305 continue;
9306 }
Richard Smith8ce51082015-03-11 01:44:51 +00009307
Vedant Kumar48b4f762018-04-14 01:40:48 +00009308 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009309 // Make sure that the ObjCInterfaceType points at the definition.
9310 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9311 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009312
9313 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9314 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9315
Guy Benyei11169dd2012-12-18 14:30:41 +00009316 continue;
9317 }
Richard Smith8ce51082015-03-11 01:44:51 +00009318
Vedant Kumar48b4f762018-04-14 01:40:48 +00009319 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009320 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9321 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9322
Guy Benyei11169dd2012-12-18 14:30:41 +00009323 continue;
9324 }
Richard Smith8ce51082015-03-11 01:44:51 +00009325
Vedant Kumar48b4f762018-04-14 01:40:48 +00009326 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009327 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9328 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009329 }
9330 PendingDefinitions.clear();
9331
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009332 // Load the bodies of any functions or methods we've encountered. We do
9333 // this now (delayed) so that we can be sure that the declaration chains
9334 // have been fully wired up (hasBody relies on this).
9335 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009336 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9337 PBEnd = PendingBodies.end();
9338 PB != PBEnd; ++PB) {
9339 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009340 // For a function defined inline within a class template, force the
9341 // canonical definition to be the one inside the canonical definition of
9342 // the template. This ensures that we instantiate from a correct view
9343 // of the template.
9344 //
9345 // Sadly we can't do this more generally: we can't be sure that all
9346 // copies of an arbitrary class definition will have the same members
9347 // defined (eg, some member functions may not be instantiated, and some
9348 // special members may or may not have been implicitly defined).
9349 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9350 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9351 continue;
9352
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009353 // FIXME: Check for =delete/=default?
9354 // FIXME: Complain about ODR violations here?
9355 const FunctionDecl *Defn = nullptr;
9356 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009357 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009358 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009359 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009360 mergeDefinitionVisibility(NonConstDefn, FD);
9361
9362 if (!FD->isLateTemplateParsed() &&
9363 !NonConstDefn->isLateTemplateParsed() &&
9364 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009365 if (!isa<CXXMethodDecl>(FD)) {
9366 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9367 } else if (FD->getLexicalParent()->isFileContext() &&
9368 NonConstDefn->getLexicalParent()->isFileContext()) {
9369 // Only diagnose out-of-line method definitions. If they are
9370 // in class definitions, then an error will be generated when
9371 // processing the class bodies.
9372 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9373 }
Richard Trieue6caa262017-12-23 00:41:01 +00009374 }
9375 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009376 continue;
9377 }
9378
Vedant Kumar48b4f762018-04-14 01:40:48 +00009379 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009380 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009381 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009382 }
9383 PendingBodies.clear();
9384
Richard Smith42413142015-05-15 20:05:43 +00009385 // Do some cleanup.
9386 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9387 getContext().deduplicateMergedDefinitonsFor(ND);
9388 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009389}
9390
9391void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009392 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009393 PendingFunctionOdrMergeFailures.empty() &&
9394 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009395 return;
9396
Richard Smitha0ce9c42014-07-29 23:23:27 +00009397 // Trigger the import of the full definition of each class that had any
9398 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009399 // These updates may in turn find and diagnose some ODR failures, so take
9400 // ownership of the set first.
9401 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9402 PendingOdrMergeFailures.clear();
9403 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009404 Merge.first->buildLookup();
9405 Merge.first->decls_begin();
9406 Merge.first->bases_begin();
9407 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009408 for (auto &RecordPair : Merge.second) {
9409 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009410 RD->decls_begin();
9411 RD->bases_begin();
9412 RD->vbases_begin();
9413 }
9414 }
9415
Richard Trieue6caa262017-12-23 00:41:01 +00009416 // Trigger the import of functions.
9417 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9418 PendingFunctionOdrMergeFailures.clear();
9419 for (auto &Merge : FunctionOdrMergeFailures) {
9420 Merge.first->buildLookup();
9421 Merge.first->decls_begin();
9422 Merge.first->getBody();
9423 for (auto &FD : Merge.second) {
9424 FD->buildLookup();
9425 FD->decls_begin();
9426 FD->getBody();
9427 }
9428 }
9429
Richard Trieuab4d7302018-07-25 22:52:05 +00009430 // Trigger the import of enums.
9431 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9432 PendingEnumOdrMergeFailures.clear();
9433 for (auto &Merge : EnumOdrMergeFailures) {
9434 Merge.first->decls_begin();
9435 for (auto &Enum : Merge.second) {
9436 Enum->decls_begin();
9437 }
9438 }
9439
Richard Smitha0ce9c42014-07-29 23:23:27 +00009440 // For each declaration from a merged context, check that the canonical
9441 // definition of that context also contains a declaration of the same
9442 // entity.
9443 //
9444 // Caution: this loop does things that might invalidate iterators into
9445 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9446 while (!PendingOdrMergeChecks.empty()) {
9447 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9448
9449 // FIXME: Skip over implicit declarations for now. This matters for things
9450 // like implicitly-declared special member functions. This isn't entirely
9451 // correct; we can end up with multiple unmerged declarations of the same
9452 // implicit entity.
9453 if (D->isImplicit())
9454 continue;
9455
9456 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009457
9458 bool Found = false;
9459 const Decl *DCanon = D->getCanonicalDecl();
9460
Richard Smith01bdb7a2014-08-28 05:44:07 +00009461 for (auto RI : D->redecls()) {
9462 if (RI->getLexicalDeclContext() == CanonDef) {
9463 Found = true;
9464 break;
9465 }
9466 }
9467 if (Found)
9468 continue;
9469
Richard Smith0f4e2c42015-08-06 04:23:48 +00009470 // Quick check failed, time to do the slow thing. Note, we can't just
9471 // look up the name of D in CanonDef here, because the member that is
9472 // in CanonDef might not be found by name lookup (it might have been
9473 // replaced by a more recent declaration in the lookup table), and we
9474 // can't necessarily find it in the redeclaration chain because it might
9475 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009476 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009477 for (auto *CanonMember : CanonDef->decls()) {
9478 if (CanonMember->getCanonicalDecl() == DCanon) {
9479 // This can happen if the declaration is merely mergeable and not
9480 // actually redeclarable (we looked for redeclarations earlier).
9481 //
9482 // FIXME: We should be able to detect this more efficiently, without
9483 // pulling in all of the members of CanonDef.
9484 Found = true;
9485 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009486 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009487 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9488 if (ND->getDeclName() == D->getDeclName())
9489 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009490 }
9491
9492 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009493 // The AST doesn't like TagDecls becoming invalid after they've been
9494 // completed. We only really need to mark FieldDecls as invalid here.
9495 if (!isa<TagDecl>(D))
9496 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009497
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009498 // Ensure we don't accidentally recursively enter deserialization while
9499 // we're producing our diagnostic.
9500 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009501
9502 std::string CanonDefModule =
9503 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9504 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9505 << D << getOwningModuleNameForDiagnostic(D)
9506 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9507
9508 if (Candidates.empty())
9509 Diag(cast<Decl>(CanonDef)->getLocation(),
9510 diag::note_module_odr_violation_no_possible_decls) << D;
9511 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009512 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9513 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009514 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009515 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009516 }
9517
9518 DiagnosedOdrMergeFailures.insert(CanonDef);
9519 }
9520 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009521
Richard Trieuab4d7302018-07-25 22:52:05 +00009522 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9523 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009524 return;
9525
9526 // Ensure we don't accidentally recursively enter deserialization while
9527 // we're producing our diagnostics.
9528 Deserializing RecursionGuard(this);
9529
Richard Trieue6caa262017-12-23 00:41:01 +00009530 // Common code for hashing helpers.
9531 ODRHash Hash;
9532 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9533 Hash.clear();
9534 Hash.AddQualType(Ty);
9535 return Hash.CalculateHash();
9536 };
9537
9538 auto ComputeODRHash = [&Hash](const Stmt *S) {
9539 assert(S);
9540 Hash.clear();
9541 Hash.AddStmt(S);
9542 return Hash.CalculateHash();
9543 };
9544
9545 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9546 assert(D);
9547 Hash.clear();
9548 Hash.AddSubDecl(D);
9549 return Hash.CalculateHash();
9550 };
9551
Richard Trieu7282d322018-04-25 00:31:15 +00009552 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9553 Hash.clear();
9554 Hash.AddTemplateArgument(TA);
9555 return Hash.CalculateHash();
9556 };
9557
Richard Trieu9359e8f2018-05-30 01:12:26 +00009558 auto ComputeTemplateParameterListODRHash =
9559 [&Hash](const TemplateParameterList *TPL) {
9560 assert(TPL);
9561 Hash.clear();
9562 Hash.AddTemplateParameterList(TPL);
9563 return Hash.CalculateHash();
9564 };
9565
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009566 // Used with err_module_odr_violation_mismatch_decl and
9567 // note_module_odr_violation_mismatch_decl
9568 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
9569 enum ODRMismatchDecl {
9570 EndOfClass,
9571 PublicSpecifer,
9572 PrivateSpecifer,
9573 ProtectedSpecifer,
9574 StaticAssert,
9575 Field,
9576 CXXMethod,
9577 TypeAlias,
9578 TypeDef,
9579 Var,
9580 Friend,
9581 FunctionTemplate,
9582 Other
9583 };
9584
9585 // Used with err_module_odr_violation_mismatch_decl_diff and
9586 // note_module_odr_violation_mismatch_decl_diff
9587 enum ODRMismatchDeclDifference {
9588 StaticAssertCondition,
9589 StaticAssertMessage,
9590 StaticAssertOnlyMessage,
9591 FieldName,
9592 FieldTypeName,
9593 FieldSingleBitField,
9594 FieldDifferentWidthBitField,
9595 FieldSingleMutable,
9596 FieldSingleInitializer,
9597 FieldDifferentInitializers,
9598 MethodName,
9599 MethodDeleted,
9600 MethodDefaulted,
9601 MethodVirtual,
9602 MethodStatic,
9603 MethodVolatile,
9604 MethodConst,
9605 MethodInline,
9606 MethodNumberParameters,
9607 MethodParameterType,
9608 MethodParameterName,
9609 MethodParameterSingleDefaultArgument,
9610 MethodParameterDifferentDefaultArgument,
9611 MethodNoTemplateArguments,
9612 MethodDifferentNumberTemplateArguments,
9613 MethodDifferentTemplateArgument,
9614 MethodSingleBody,
9615 MethodDifferentBody,
9616 TypedefName,
9617 TypedefType,
9618 VarName,
9619 VarType,
9620 VarSingleInitializer,
9621 VarDifferentInitializer,
9622 VarConstexpr,
9623 FriendTypeFunction,
9624 FriendType,
9625 FriendFunction,
9626 FunctionTemplateDifferentNumberParameters,
9627 FunctionTemplateParameterDifferentKind,
9628 FunctionTemplateParameterName,
9629 FunctionTemplateParameterSingleDefaultArgument,
9630 FunctionTemplateParameterDifferentDefaultArgument,
9631 FunctionTemplateParameterDifferentType,
9632 FunctionTemplatePackParameter,
9633 };
9634
9635 // These lambdas have the common portions of the ODR diagnostics. This
9636 // has the same return as Diag(), so addition parameters can be passed
9637 // in with operator<<
9638 auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule,
9639 SourceLocation Loc, SourceRange Range,
9640 ODRMismatchDeclDifference DiffType) {
9641 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9642 << FirstRecord << FirstModule.empty() << FirstModule << Range
9643 << DiffType;
9644 };
9645 auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc,
9646 SourceRange Range, ODRMismatchDeclDifference DiffType) {
9647 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9648 << SecondModule << Range << DiffType;
9649 };
9650
9651 auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote,
9652 &ComputeQualTypeODRHash, &ComputeODRHash](
9653 NamedDecl *FirstRecord, StringRef FirstModule,
9654 StringRef SecondModule, FieldDecl *FirstField,
9655 FieldDecl *SecondField) {
9656 IdentifierInfo *FirstII = FirstField->getIdentifier();
9657 IdentifierInfo *SecondII = SecondField->getIdentifier();
9658 if (FirstII->getName() != SecondII->getName()) {
9659 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9660 FirstField->getSourceRange(), FieldName)
9661 << FirstII;
9662 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9663 SecondField->getSourceRange(), FieldName)
9664 << SecondII;
9665
9666 return true;
9667 }
9668
9669 assert(getContext().hasSameType(FirstField->getType(),
9670 SecondField->getType()));
9671
9672 QualType FirstType = FirstField->getType();
9673 QualType SecondType = SecondField->getType();
9674 if (ComputeQualTypeODRHash(FirstType) !=
9675 ComputeQualTypeODRHash(SecondType)) {
9676 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9677 FirstField->getSourceRange(), FieldTypeName)
9678 << FirstII << FirstType;
9679 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9680 SecondField->getSourceRange(), FieldTypeName)
9681 << SecondII << SecondType;
9682
9683 return true;
9684 }
9685
9686 const bool IsFirstBitField = FirstField->isBitField();
9687 const bool IsSecondBitField = SecondField->isBitField();
9688 if (IsFirstBitField != IsSecondBitField) {
9689 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9690 FirstField->getSourceRange(), FieldSingleBitField)
9691 << FirstII << IsFirstBitField;
9692 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9693 SecondField->getSourceRange(), FieldSingleBitField)
9694 << SecondII << IsSecondBitField;
9695 return true;
9696 }
9697
9698 if (IsFirstBitField && IsSecondBitField) {
9699 unsigned FirstBitWidthHash =
9700 ComputeODRHash(FirstField->getBitWidth());
9701 unsigned SecondBitWidthHash =
9702 ComputeODRHash(SecondField->getBitWidth());
9703 if (FirstBitWidthHash != SecondBitWidthHash) {
9704 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9705 FirstField->getSourceRange(),
9706 FieldDifferentWidthBitField)
9707 << FirstII << FirstField->getBitWidth()->getSourceRange();
9708 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9709 SecondField->getSourceRange(),
9710 FieldDifferentWidthBitField)
9711 << SecondII << SecondField->getBitWidth()->getSourceRange();
9712 return true;
9713 }
9714 }
9715
9716 if (!PP.getLangOpts().CPlusPlus)
9717 return false;
9718
9719 const bool IsFirstMutable = FirstField->isMutable();
9720 const bool IsSecondMutable = SecondField->isMutable();
9721 if (IsFirstMutable != IsSecondMutable) {
9722 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9723 FirstField->getSourceRange(), FieldSingleMutable)
9724 << FirstII << IsFirstMutable;
9725 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9726 SecondField->getSourceRange(), FieldSingleMutable)
9727 << SecondII << IsSecondMutable;
9728 return true;
9729 }
9730
9731 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9732 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9733 if ((!FirstInitializer && SecondInitializer) ||
9734 (FirstInitializer && !SecondInitializer)) {
9735 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9736 FirstField->getSourceRange(), FieldSingleInitializer)
9737 << FirstII << (FirstInitializer != nullptr);
9738 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9739 SecondField->getSourceRange(), FieldSingleInitializer)
9740 << SecondII << (SecondInitializer != nullptr);
9741 return true;
9742 }
9743
9744 if (FirstInitializer && SecondInitializer) {
9745 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9746 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9747 if (FirstInitHash != SecondInitHash) {
9748 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9749 FirstField->getSourceRange(),
9750 FieldDifferentInitializers)
9751 << FirstII << FirstInitializer->getSourceRange();
9752 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9753 SecondField->getSourceRange(),
9754 FieldDifferentInitializers)
9755 << SecondII << SecondInitializer->getSourceRange();
9756 return true;
9757 }
9758 }
9759
9760 return false;
9761 };
9762
9763 auto ODRDiagTypeDefOrAlias =
9764 [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash](
9765 NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule,
9766 TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD,
9767 bool IsTypeAlias) {
9768 auto FirstName = FirstTD->getDeclName();
9769 auto SecondName = SecondTD->getDeclName();
9770 if (FirstName != SecondName) {
9771 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9772 FirstTD->getSourceRange(), TypedefName)
9773 << IsTypeAlias << FirstName;
9774 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9775 SecondTD->getSourceRange(), TypedefName)
9776 << IsTypeAlias << SecondName;
9777 return true;
9778 }
9779
9780 QualType FirstType = FirstTD->getUnderlyingType();
9781 QualType SecondType = SecondTD->getUnderlyingType();
9782 if (ComputeQualTypeODRHash(FirstType) !=
9783 ComputeQualTypeODRHash(SecondType)) {
9784 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9785 FirstTD->getSourceRange(), TypedefType)
9786 << IsTypeAlias << FirstName << FirstType;
9787 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9788 SecondTD->getSourceRange(), TypedefType)
9789 << IsTypeAlias << SecondName << SecondType;
9790 return true;
9791 }
9792
9793 return false;
9794 };
9795
9796 auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote,
9797 &ComputeQualTypeODRHash, &ComputeODRHash,
9798 this](NamedDecl *FirstRecord, StringRef FirstModule,
9799 StringRef SecondModule, VarDecl *FirstVD,
9800 VarDecl *SecondVD) {
9801 auto FirstName = FirstVD->getDeclName();
9802 auto SecondName = SecondVD->getDeclName();
9803 if (FirstName != SecondName) {
9804 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9805 FirstVD->getSourceRange(), VarName)
9806 << FirstName;
9807 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9808 SecondVD->getSourceRange(), VarName)
9809 << SecondName;
9810 return true;
9811 }
9812
9813 QualType FirstType = FirstVD->getType();
9814 QualType SecondType = SecondVD->getType();
9815 if (ComputeQualTypeODRHash(FirstType) !=
9816 ComputeQualTypeODRHash(SecondType)) {
9817 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9818 FirstVD->getSourceRange(), VarType)
9819 << FirstName << FirstType;
9820 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9821 SecondVD->getSourceRange(), VarType)
9822 << SecondName << SecondType;
9823 return true;
9824 }
9825
9826 if (!PP.getLangOpts().CPlusPlus)
9827 return false;
9828
9829 const Expr *FirstInit = FirstVD->getInit();
9830 const Expr *SecondInit = SecondVD->getInit();
9831 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
9832 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9833 FirstVD->getSourceRange(), VarSingleInitializer)
9834 << FirstName << (FirstInit == nullptr)
9835 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
9836 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9837 SecondVD->getSourceRange(), VarSingleInitializer)
9838 << SecondName << (SecondInit == nullptr)
9839 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
9840 return true;
9841 }
9842
9843 if (FirstInit && SecondInit &&
9844 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
9845 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9846 FirstVD->getSourceRange(), VarDifferentInitializer)
9847 << FirstName << FirstInit->getSourceRange();
9848 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9849 SecondVD->getSourceRange(), VarDifferentInitializer)
9850 << SecondName << SecondInit->getSourceRange();
9851 return true;
9852 }
9853
9854 const bool FirstIsConstexpr = FirstVD->isConstexpr();
9855 const bool SecondIsConstexpr = SecondVD->isConstexpr();
9856 if (FirstIsConstexpr != SecondIsConstexpr) {
9857 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9858 FirstVD->getSourceRange(), VarConstexpr)
9859 << FirstName << FirstIsConstexpr;
9860 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9861 SecondVD->getSourceRange(), VarConstexpr)
9862 << SecondName << SecondIsConstexpr;
9863 return true;
9864 }
9865 return false;
9866 };
9867
9868 auto DifferenceSelector = [](Decl *D) {
9869 assert(D && "valid Decl required");
9870 switch (D->getKind()) {
9871 default:
9872 return Other;
9873 case Decl::AccessSpec:
9874 switch (D->getAccess()) {
9875 case AS_public:
9876 return PublicSpecifer;
9877 case AS_private:
9878 return PrivateSpecifer;
9879 case AS_protected:
9880 return ProtectedSpecifer;
9881 case AS_none:
9882 break;
9883 }
9884 llvm_unreachable("Invalid access specifier");
9885 case Decl::StaticAssert:
9886 return StaticAssert;
9887 case Decl::Field:
9888 return Field;
9889 case Decl::CXXMethod:
9890 case Decl::CXXConstructor:
9891 case Decl::CXXDestructor:
9892 return CXXMethod;
9893 case Decl::TypeAlias:
9894 return TypeAlias;
9895 case Decl::Typedef:
9896 return TypeDef;
9897 case Decl::Var:
9898 return Var;
9899 case Decl::Friend:
9900 return Friend;
9901 case Decl::FunctionTemplate:
9902 return FunctionTemplate;
9903 }
9904 };
9905
9906 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9907 auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9908 RecordDecl *Record,
9909 const DeclContext *DC) {
9910 for (auto *D : Record->decls()) {
9911 if (!ODRHash::isWhitelistedDecl(D, DC))
9912 continue;
9913 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9914 }
9915 };
9916
9917 struct DiffResult {
9918 Decl *FirstDecl = nullptr, *SecondDecl = nullptr;
9919 ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other;
9920 };
9921
9922 // If there is a diagnoseable difference, FirstDiffType and
9923 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9924 // filled in if not EndOfClass.
9925 auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes,
9926 DeclHashes &SecondHashes) {
9927 DiffResult DR;
9928 auto FirstIt = FirstHashes.begin();
9929 auto SecondIt = SecondHashes.begin();
9930 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9931 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9932 FirstIt->second == SecondIt->second) {
9933 ++FirstIt;
9934 ++SecondIt;
9935 continue;
9936 }
9937
9938 DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9939 DR.SecondDecl =
9940 SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9941
9942 DR.FirstDiffType =
9943 DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass;
9944 DR.SecondDiffType =
9945 DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass;
9946 return DR;
9947 }
9948 return DR;
9949 };
9950
9951 // Use this to diagnose that an unexpected Decl was encountered
9952 // or no difference was detected. This causes a generic error
9953 // message to be emitted.
9954 auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord,
9955 StringRef FirstModule,
9956 NamedDecl *SecondRecord,
9957 StringRef SecondModule) {
9958 Diag(FirstRecord->getLocation(),
9959 diag::err_module_odr_violation_different_definitions)
9960 << FirstRecord << FirstModule.empty() << FirstModule;
9961
9962 if (DR.FirstDecl) {
9963 Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference)
9964 << FirstRecord << DR.FirstDecl->getSourceRange();
9965 }
9966
9967 Diag(SecondRecord->getLocation(),
9968 diag::note_module_odr_violation_different_definitions)
9969 << SecondModule;
9970
9971 if (DR.SecondDecl) {
9972 Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference)
9973 << DR.SecondDecl->getSourceRange();
9974 }
9975 };
9976
9977 auto DiagnoseODRMismatch =
9978 [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule,
9979 NamedDecl *SecondRecord, StringRef SecondModule) {
9980 SourceLocation FirstLoc;
9981 SourceRange FirstRange;
9982 auto *FirstTag = dyn_cast<TagDecl>(FirstRecord);
9983 if (DR.FirstDiffType == EndOfClass && FirstTag) {
9984 FirstLoc = FirstTag->getBraceRange().getEnd();
9985 } else {
9986 FirstLoc = DR.FirstDecl->getLocation();
9987 FirstRange = DR.FirstDecl->getSourceRange();
9988 }
9989 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9990 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9991 << DR.FirstDiffType;
9992
9993 SourceLocation SecondLoc;
9994 SourceRange SecondRange;
9995 auto *SecondTag = dyn_cast<TagDecl>(SecondRecord);
9996 if (DR.SecondDiffType == EndOfClass && SecondTag) {
9997 SecondLoc = SecondTag->getBraceRange().getEnd();
9998 } else {
9999 SecondLoc = DR.SecondDecl->getLocation();
10000 SecondRange = DR.SecondDecl->getSourceRange();
10001 }
10002 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10003 << SecondModule << SecondRange << DR.SecondDiffType;
10004 };
10005
Richard Smithcd45dbc2014-04-19 03:48:30 +000010006 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +000010007 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010008 // If we've already pointed out a specific problem with this class, don't
10009 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +000010010 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +000010011 continue;
10012
10013 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010014 CXXRecordDecl *FirstRecord = Merge.first;
10015 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010016 for (auto &RecordPair : Merge.second) {
10017 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010018 // Multiple different declarations got merged together; tell the user
10019 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +000010020 if (FirstRecord == SecondRecord)
10021 continue;
10022
10023 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010024
10025 auto *FirstDD = FirstRecord->DefinitionData;
10026 auto *SecondDD = RecordPair.second;
10027
10028 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10029
10030 // Diagnostics from DefinitionData are emitted here.
10031 if (FirstDD != SecondDD) {
10032 enum ODRDefinitionDataDifference {
10033 NumBases,
10034 NumVBases,
10035 BaseType,
10036 BaseVirtual,
10037 BaseAccess,
10038 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010039 auto ODRDiagBaseError = [FirstRecord, &FirstModule,
10040 this](SourceLocation Loc, SourceRange Range,
10041 ODRDefinitionDataDifference DiffType) {
Richard Trieue13eabe2017-09-30 02:19:17 +000010042 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10043 << FirstRecord << FirstModule.empty() << FirstModule << Range
10044 << DiffType;
10045 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010046 auto ODRDiagBaseNote = [&SecondModule,
10047 this](SourceLocation Loc, SourceRange Range,
10048 ODRDefinitionDataDifference DiffType) {
Richard Trieue13eabe2017-09-30 02:19:17 +000010049 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10050 << SecondModule << Range << DiffType;
10051 };
10052
Richard Trieue13eabe2017-09-30 02:19:17 +000010053 unsigned FirstNumBases = FirstDD->NumBases;
10054 unsigned FirstNumVBases = FirstDD->NumVBases;
10055 unsigned SecondNumBases = SecondDD->NumBases;
10056 unsigned SecondNumVBases = SecondDD->NumVBases;
10057
10058 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10059 unsigned NumBases = DD->NumBases;
10060 if (NumBases == 0) return SourceRange();
10061 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010062 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +000010063 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +000010064 };
10065
10066 if (FirstNumBases != SecondNumBases) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010067 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10068 NumBases)
Richard Trieue13eabe2017-09-30 02:19:17 +000010069 << FirstNumBases;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010070 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10071 NumBases)
Richard Trieue13eabe2017-09-30 02:19:17 +000010072 << SecondNumBases;
10073 Diagnosed = true;
10074 break;
10075 }
10076
10077 if (FirstNumVBases != SecondNumVBases) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010078 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10079 NumVBases)
Richard Trieue13eabe2017-09-30 02:19:17 +000010080 << FirstNumVBases;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010081 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10082 NumVBases)
Richard Trieue13eabe2017-09-30 02:19:17 +000010083 << SecondNumVBases;
10084 Diagnosed = true;
10085 break;
10086 }
10087
10088 auto FirstBases = FirstDD->bases();
10089 auto SecondBases = SecondDD->bases();
10090 unsigned i = 0;
10091 for (i = 0; i < FirstNumBases; ++i) {
10092 auto FirstBase = FirstBases[i];
10093 auto SecondBase = SecondBases[i];
10094 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10095 ComputeQualTypeODRHash(SecondBase.getType())) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010096 ODRDiagBaseError(FirstRecord->getLocation(),
10097 FirstBase.getSourceRange(), BaseType)
Richard Trieue13eabe2017-09-30 02:19:17 +000010098 << (i + 1) << FirstBase.getType();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010099 ODRDiagBaseNote(SecondRecord->getLocation(),
10100 SecondBase.getSourceRange(), BaseType)
Richard Trieue13eabe2017-09-30 02:19:17 +000010101 << (i + 1) << SecondBase.getType();
10102 break;
10103 }
10104
10105 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010106 ODRDiagBaseError(FirstRecord->getLocation(),
10107 FirstBase.getSourceRange(), BaseVirtual)
Richard Trieue13eabe2017-09-30 02:19:17 +000010108 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010109 ODRDiagBaseNote(SecondRecord->getLocation(),
10110 SecondBase.getSourceRange(), BaseVirtual)
Richard Trieue13eabe2017-09-30 02:19:17 +000010111 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10112 break;
10113 }
10114
10115 if (FirstBase.getAccessSpecifierAsWritten() !=
10116 SecondBase.getAccessSpecifierAsWritten()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010117 ODRDiagBaseError(FirstRecord->getLocation(),
10118 FirstBase.getSourceRange(), BaseAccess)
Richard Trieue13eabe2017-09-30 02:19:17 +000010119 << (i + 1) << FirstBase.getType()
10120 << (int)FirstBase.getAccessSpecifierAsWritten();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010121 ODRDiagBaseNote(SecondRecord->getLocation(),
10122 SecondBase.getSourceRange(), BaseAccess)
Richard Trieue13eabe2017-09-30 02:19:17 +000010123 << (i + 1) << SecondBase.getType()
10124 << (int)SecondBase.getAccessSpecifierAsWritten();
10125 break;
10126 }
10127 }
10128
10129 if (i != FirstNumBases) {
10130 Diagnosed = true;
10131 break;
10132 }
10133 }
10134
Richard Trieu498117b2017-08-23 02:43:59 +000010135 const ClassTemplateDecl *FirstTemplate =
10136 FirstRecord->getDescribedClassTemplate();
10137 const ClassTemplateDecl *SecondTemplate =
10138 SecondRecord->getDescribedClassTemplate();
10139
10140 assert(!FirstTemplate == !SecondTemplate &&
10141 "Both pointers should be null or non-null");
10142
10143 enum ODRTemplateDifference {
10144 ParamEmptyName,
10145 ParamName,
10146 ParamSingleDefaultArgument,
10147 ParamDifferentDefaultArgument,
10148 };
10149
10150 if (FirstTemplate && SecondTemplate) {
10151 DeclHashes FirstTemplateHashes;
10152 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010153
10154 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010155 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10156 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010157 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010158 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010159 }
10160 };
10161
10162 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10163 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10164
10165 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10166 "Number of template parameters should be equal.");
10167
10168 auto FirstIt = FirstTemplateHashes.begin();
10169 auto FirstEnd = FirstTemplateHashes.end();
10170 auto SecondIt = SecondTemplateHashes.begin();
10171 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10172 if (FirstIt->second == SecondIt->second)
10173 continue;
10174
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010175 auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this](
10176 SourceLocation Loc, SourceRange Range,
10177 ODRTemplateDifference DiffType) {
Richard Trieu498117b2017-08-23 02:43:59 +000010178 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10179 << FirstRecord << FirstModule.empty() << FirstModule << Range
10180 << DiffType;
10181 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010182 auto ODRDiagTemplateNote = [&SecondModule, this](
10183 SourceLocation Loc, SourceRange Range,
10184 ODRTemplateDifference DiffType) {
Richard Trieu498117b2017-08-23 02:43:59 +000010185 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10186 << SecondModule << Range << DiffType;
10187 };
10188
Vedant Kumar48b4f762018-04-14 01:40:48 +000010189 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10190 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010191
10192 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10193 "Parameter Decl's should be the same kind.");
10194
10195 DeclarationName FirstName = FirstDecl->getDeclName();
10196 DeclarationName SecondName = SecondDecl->getDeclName();
10197
10198 if (FirstName != SecondName) {
10199 const bool FirstNameEmpty =
10200 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10201 const bool SecondNameEmpty =
10202 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10203 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10204 "Both template parameters cannot be unnamed.");
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010205 ODRDiagTemplateError(FirstDecl->getLocation(),
10206 FirstDecl->getSourceRange(),
10207 FirstNameEmpty ? ParamEmptyName : ParamName)
Richard Trieu498117b2017-08-23 02:43:59 +000010208 << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010209 ODRDiagTemplateNote(SecondDecl->getLocation(),
10210 SecondDecl->getSourceRange(),
10211 SecondNameEmpty ? ParamEmptyName : ParamName)
Richard Trieu498117b2017-08-23 02:43:59 +000010212 << SecondName;
10213 break;
10214 }
10215
10216 switch (FirstDecl->getKind()) {
10217 default:
10218 llvm_unreachable("Invalid template parameter type.");
10219 case Decl::TemplateTypeParm: {
10220 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10221 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10222 const bool HasFirstDefaultArgument =
10223 FirstParam->hasDefaultArgument() &&
10224 !FirstParam->defaultArgumentWasInherited();
10225 const bool HasSecondDefaultArgument =
10226 SecondParam->hasDefaultArgument() &&
10227 !SecondParam->defaultArgumentWasInherited();
10228
10229 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010230 ODRDiagTemplateError(FirstDecl->getLocation(),
10231 FirstDecl->getSourceRange(),
10232 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010233 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010234 ODRDiagTemplateNote(SecondDecl->getLocation(),
10235 SecondDecl->getSourceRange(),
10236 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010237 << HasSecondDefaultArgument;
10238 break;
10239 }
10240
10241 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10242 "Expecting default arguments.");
10243
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010244 ODRDiagTemplateError(FirstDecl->getLocation(),
10245 FirstDecl->getSourceRange(),
10246 ParamDifferentDefaultArgument);
10247 ODRDiagTemplateNote(SecondDecl->getLocation(),
10248 SecondDecl->getSourceRange(),
10249 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010250
10251 break;
10252 }
10253 case Decl::NonTypeTemplateParm: {
10254 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10255 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10256 const bool HasFirstDefaultArgument =
10257 FirstParam->hasDefaultArgument() &&
10258 !FirstParam->defaultArgumentWasInherited();
10259 const bool HasSecondDefaultArgument =
10260 SecondParam->hasDefaultArgument() &&
10261 !SecondParam->defaultArgumentWasInherited();
10262
10263 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010264 ODRDiagTemplateError(FirstDecl->getLocation(),
10265 FirstDecl->getSourceRange(),
10266 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010267 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010268 ODRDiagTemplateNote(SecondDecl->getLocation(),
10269 SecondDecl->getSourceRange(),
10270 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010271 << HasSecondDefaultArgument;
10272 break;
10273 }
10274
10275 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10276 "Expecting default arguments.");
10277
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010278 ODRDiagTemplateError(FirstDecl->getLocation(),
10279 FirstDecl->getSourceRange(),
10280 ParamDifferentDefaultArgument);
10281 ODRDiagTemplateNote(SecondDecl->getLocation(),
10282 SecondDecl->getSourceRange(),
10283 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010284
10285 break;
10286 }
10287 case Decl::TemplateTemplateParm: {
10288 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10289 const auto *SecondParam =
10290 cast<TemplateTemplateParmDecl>(SecondDecl);
10291 const bool HasFirstDefaultArgument =
10292 FirstParam->hasDefaultArgument() &&
10293 !FirstParam->defaultArgumentWasInherited();
10294 const bool HasSecondDefaultArgument =
10295 SecondParam->hasDefaultArgument() &&
10296 !SecondParam->defaultArgumentWasInherited();
10297
10298 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010299 ODRDiagTemplateError(FirstDecl->getLocation(),
10300 FirstDecl->getSourceRange(),
10301 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010302 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010303 ODRDiagTemplateNote(SecondDecl->getLocation(),
10304 SecondDecl->getSourceRange(),
10305 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010306 << HasSecondDefaultArgument;
10307 break;
10308 }
10309
10310 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10311 "Expecting default arguments.");
10312
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010313 ODRDiagTemplateError(FirstDecl->getLocation(),
10314 FirstDecl->getSourceRange(),
10315 ParamDifferentDefaultArgument);
10316 ODRDiagTemplateNote(SecondDecl->getLocation(),
10317 SecondDecl->getSourceRange(),
10318 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010319
10320 break;
10321 }
10322 }
10323
10324 break;
10325 }
10326
10327 if (FirstIt != FirstEnd) {
10328 Diagnosed = true;
10329 break;
10330 }
10331 }
10332
Richard Trieue7f7ed22017-02-22 01:11:25 +000010333 DeclHashes FirstHashes;
10334 DeclHashes SecondHashes;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010335 const DeclContext *DC = FirstRecord;
10336 PopulateHashes(FirstHashes, FirstRecord, DC);
10337 PopulateHashes(SecondHashes, SecondRecord, DC);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010338
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010339 auto DR = FindTypeDiffs(FirstHashes, SecondHashes);
10340 ODRMismatchDecl FirstDiffType = DR.FirstDiffType;
10341 ODRMismatchDecl SecondDiffType = DR.SecondDiffType;
10342 Decl *FirstDecl = DR.FirstDecl;
10343 Decl *SecondDecl = DR.SecondDecl;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010344
10345 if (FirstDiffType == Other || SecondDiffType == Other) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010346 DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord,
10347 SecondModule);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010348 Diagnosed = true;
10349 break;
10350 }
10351
10352 if (FirstDiffType != SecondDiffType) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010353 DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord,
10354 SecondModule);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010355 Diagnosed = true;
10356 break;
10357 }
10358
Richard Trieu639d7b62017-02-22 22:22:42 +000010359 assert(FirstDiffType == SecondDiffType);
10360
Richard Trieu639d7b62017-02-22 22:22:42 +000010361 switch (FirstDiffType) {
10362 case Other:
10363 case EndOfClass:
10364 case PublicSpecifer:
10365 case PrivateSpecifer:
10366 case ProtectedSpecifer:
10367 llvm_unreachable("Invalid diff type");
10368
10369 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010370 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10371 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010372
10373 Expr *FirstExpr = FirstSA->getAssertExpr();
10374 Expr *SecondExpr = SecondSA->getAssertExpr();
10375 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10376 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10377 if (FirstODRHash != SecondODRHash) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010378 ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(),
10379 FirstExpr->getSourceRange(), StaticAssertCondition);
10380 ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(),
10381 SecondExpr->getSourceRange(), StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010382 Diagnosed = true;
10383 break;
10384 }
10385
10386 StringLiteral *FirstStr = FirstSA->getMessage();
10387 StringLiteral *SecondStr = SecondSA->getMessage();
10388 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10389 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10390 SourceLocation FirstLoc, SecondLoc;
10391 SourceRange FirstRange, SecondRange;
10392 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010393 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010394 FirstRange = FirstStr->getSourceRange();
10395 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010396 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010397 FirstRange = FirstSA->getSourceRange();
10398 }
10399 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010400 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010401 SecondRange = SecondStr->getSourceRange();
10402 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010403 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010404 SecondRange = SecondSA->getSourceRange();
10405 }
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010406 ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange,
10407 StaticAssertOnlyMessage)
Richard Trieu639d7b62017-02-22 22:22:42 +000010408 << (FirstStr == nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010409 ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange,
10410 StaticAssertOnlyMessage)
Richard Trieu639d7b62017-02-22 22:22:42 +000010411 << (SecondStr == nullptr);
10412 Diagnosed = true;
10413 break;
10414 }
10415
10416 if (FirstStr && SecondStr &&
10417 FirstStr->getString() != SecondStr->getString()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010418 ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(),
10419 FirstStr->getSourceRange(), StaticAssertMessage);
10420 ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(),
10421 SecondStr->getSourceRange(), StaticAssertMessage);
Richard Trieu639d7b62017-02-22 22:22:42 +000010422 Diagnosed = true;
10423 break;
10424 }
10425 break;
10426 }
Richard Trieud0786092017-02-23 00:23:01 +000010427 case Field: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010428 Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule,
10429 cast<FieldDecl>(FirstDecl),
10430 cast<FieldDecl>(SecondDecl));
Richard Trieud0786092017-02-23 00:23:01 +000010431 break;
10432 }
Richard Trieu48143742017-02-28 21:24:38 +000010433 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010434 enum {
10435 DiagMethod,
10436 DiagConstructor,
10437 DiagDestructor,
10438 } FirstMethodType,
10439 SecondMethodType;
10440 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10441 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10442 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10443 return DiagMethod;
10444 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010445 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10446 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010447 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10448 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010449 auto FirstName = FirstMethod->getDeclName();
10450 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010451 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010452 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10453 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010454 << FirstMethodType << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010455 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10456 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010457 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010458
10459 Diagnosed = true;
10460 break;
10461 }
10462
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010463 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10464 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010465 if (FirstDeleted != SecondDeleted) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010466 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10467 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010468 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010469
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010470 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10471 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010472 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010473 Diagnosed = true;
10474 break;
10475 }
10476
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010477 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10478 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10479 if (FirstDefaulted != SecondDefaulted) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010480 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10481 FirstMethod->getSourceRange(), MethodDefaulted)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010482 << FirstMethodType << FirstName << FirstDefaulted;
10483
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010484 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10485 SecondMethod->getSourceRange(), MethodDefaulted)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010486 << SecondMethodType << SecondName << SecondDefaulted;
10487 Diagnosed = true;
10488 break;
10489 }
10490
Richard Trieu583e2c12017-03-04 00:08:58 +000010491 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10492 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10493 const bool FirstPure = FirstMethod->isPure();
10494 const bool SecondPure = SecondMethod->isPure();
10495 if ((FirstVirtual || SecondVirtual) &&
10496 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010497 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10498 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010499 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010500 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10501 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010502 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010503 Diagnosed = true;
10504 break;
10505 }
10506
10507 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10508 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10509 // class needs to be checked instead.
10510 const auto FirstStorage = FirstMethod->getStorageClass();
10511 const auto SecondStorage = SecondMethod->getStorageClass();
10512 const bool FirstStatic = FirstStorage == SC_Static;
10513 const bool SecondStatic = SecondStorage == SC_Static;
10514 if (FirstStatic != SecondStatic) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010515 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10516 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010517 << FirstMethodType << FirstName << FirstStatic;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010518 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10519 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010520 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010521 Diagnosed = true;
10522 break;
10523 }
10524
10525 const bool FirstVolatile = FirstMethod->isVolatile();
10526 const bool SecondVolatile = SecondMethod->isVolatile();
10527 if (FirstVolatile != SecondVolatile) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010528 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10529 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010530 << FirstMethodType << FirstName << FirstVolatile;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010531 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10532 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010533 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010534 Diagnosed = true;
10535 break;
10536 }
10537
10538 const bool FirstConst = FirstMethod->isConst();
10539 const bool SecondConst = SecondMethod->isConst();
10540 if (FirstConst != SecondConst) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010541 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10542 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010543 << FirstMethodType << FirstName << FirstConst;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010544 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10545 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010546 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010547 Diagnosed = true;
10548 break;
10549 }
10550
10551 const bool FirstInline = FirstMethod->isInlineSpecified();
10552 const bool SecondInline = SecondMethod->isInlineSpecified();
10553 if (FirstInline != SecondInline) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010554 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10555 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010556 << FirstMethodType << FirstName << FirstInline;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010557 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10558 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010559 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010560 Diagnosed = true;
10561 break;
10562 }
10563
Richard Trieu02552272017-05-02 23:58:52 +000010564 const unsigned FirstNumParameters = FirstMethod->param_size();
10565 const unsigned SecondNumParameters = SecondMethod->param_size();
10566 if (FirstNumParameters != SecondNumParameters) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010567 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10568 FirstMethod->getSourceRange(),
10569 MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010570 << FirstMethodType << FirstName << FirstNumParameters;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010571 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10572 SecondMethod->getSourceRange(),
10573 MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010574 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010575 Diagnosed = true;
10576 break;
10577 }
10578
10579 // Need this status boolean to know when break out of the switch.
10580 bool ParameterMismatch = false;
10581 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10582 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10583 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10584
10585 QualType FirstParamType = FirstParam->getType();
10586 QualType SecondParamType = SecondParam->getType();
10587 if (FirstParamType != SecondParamType &&
10588 ComputeQualTypeODRHash(FirstParamType) !=
10589 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010590 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010591 FirstParamType->getAs<DecayedType>()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010592 ODRDiagDeclError(
10593 FirstRecord, FirstModule, FirstMethod->getLocation(),
10594 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010595 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10596 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010597 } else {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010598 ODRDiagDeclError(
10599 FirstRecord, FirstModule, FirstMethod->getLocation(),
10600 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010601 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10602 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010603 }
10604
Vedant Kumar48b4f762018-04-14 01:40:48 +000010605 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010606 SecondParamType->getAs<DecayedType>()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010607 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10608 SecondMethod->getSourceRange(),
10609 MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010610 << SecondMethodType << SecondName << (I + 1)
10611 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010612 << ParamDecayedType->getOriginalType();
10613 } else {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010614 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10615 SecondMethod->getSourceRange(),
10616 MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010617 << SecondMethodType << SecondName << (I + 1)
10618 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010619 }
10620 ParameterMismatch = true;
10621 break;
10622 }
10623
10624 DeclarationName FirstParamName = FirstParam->getDeclName();
10625 DeclarationName SecondParamName = SecondParam->getDeclName();
10626 if (FirstParamName != SecondParamName) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010627 ODRDiagDeclError(FirstRecord, FirstModule,
10628 FirstMethod->getLocation(),
10629 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010630 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010631 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10632 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010633 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010634 ParameterMismatch = true;
10635 break;
10636 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010637
10638 const Expr *FirstInit = FirstParam->getInit();
10639 const Expr *SecondInit = SecondParam->getInit();
10640 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010641 ODRDiagDeclError(FirstRecord, FirstModule,
10642 FirstMethod->getLocation(),
10643 FirstMethod->getSourceRange(),
10644 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010645 << FirstMethodType << FirstName << (I + 1)
10646 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010647 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010648 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10649 SecondMethod->getSourceRange(),
10650 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010651 << SecondMethodType << SecondName << (I + 1)
10652 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010653 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10654 ParameterMismatch = true;
10655 break;
10656 }
10657
10658 if (FirstInit && SecondInit &&
10659 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010660 ODRDiagDeclError(FirstRecord, FirstModule,
10661 FirstMethod->getLocation(),
10662 FirstMethod->getSourceRange(),
10663 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010664 << FirstMethodType << FirstName << (I + 1)
10665 << FirstInit->getSourceRange();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010666 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10667 SecondMethod->getSourceRange(),
10668 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010669 << SecondMethodType << SecondName << (I + 1)
10670 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010671 ParameterMismatch = true;
10672 break;
10673
10674 }
Richard Trieu02552272017-05-02 23:58:52 +000010675 }
10676
10677 if (ParameterMismatch) {
10678 Diagnosed = true;
10679 break;
10680 }
10681
Richard Trieu7282d322018-04-25 00:31:15 +000010682 const auto *FirstTemplateArgs =
10683 FirstMethod->getTemplateSpecializationArgs();
10684 const auto *SecondTemplateArgs =
10685 SecondMethod->getTemplateSpecializationArgs();
10686
10687 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10688 (!FirstTemplateArgs && SecondTemplateArgs)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010689 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10690 FirstMethod->getSourceRange(),
10691 MethodNoTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010692 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010693 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10694 SecondMethod->getSourceRange(),
10695 MethodNoTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010696 << SecondMethodType << SecondName
10697 << (SecondTemplateArgs != nullptr);
10698
10699 Diagnosed = true;
10700 break;
10701 }
10702
10703 if (FirstTemplateArgs && SecondTemplateArgs) {
10704 // Remove pack expansions from argument list.
10705 auto ExpandTemplateArgumentList =
10706 [](const TemplateArgumentList *TAL) {
10707 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10708 for (const TemplateArgument &TA : TAL->asArray()) {
10709 if (TA.getKind() != TemplateArgument::Pack) {
10710 ExpandedList.push_back(&TA);
10711 continue;
10712 }
10713 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10714 ExpandedList.push_back(&PackTA);
10715 }
10716 }
10717 return ExpandedList;
10718 };
10719 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10720 ExpandTemplateArgumentList(FirstTemplateArgs);
10721 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10722 ExpandTemplateArgumentList(SecondTemplateArgs);
10723
10724 if (FirstExpandedList.size() != SecondExpandedList.size()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010725 ODRDiagDeclError(FirstRecord, FirstModule,
10726 FirstMethod->getLocation(),
10727 FirstMethod->getSourceRange(),
10728 MethodDifferentNumberTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010729 << FirstMethodType << FirstName
10730 << (unsigned)FirstExpandedList.size();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010731 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10732 SecondMethod->getSourceRange(),
10733 MethodDifferentNumberTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010734 << SecondMethodType << SecondName
10735 << (unsigned)SecondExpandedList.size();
10736
10737 Diagnosed = true;
10738 break;
10739 }
10740
10741 bool TemplateArgumentMismatch = false;
10742 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10743 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10744 &SecondTA = *SecondExpandedList[i];
10745 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10746 ComputeTemplateArgumentODRHash(SecondTA)) {
10747 continue;
10748 }
10749
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010750 ODRDiagDeclError(
10751 FirstRecord, FirstModule, FirstMethod->getLocation(),
10752 FirstMethod->getSourceRange(), MethodDifferentTemplateArgument)
Richard Trieu7282d322018-04-25 00:31:15 +000010753 << FirstMethodType << FirstName << FirstTA << i + 1;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010754 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10755 SecondMethod->getSourceRange(),
10756 MethodDifferentTemplateArgument)
Richard Trieu7282d322018-04-25 00:31:15 +000010757 << SecondMethodType << SecondName << SecondTA << i + 1;
10758
10759 TemplateArgumentMismatch = true;
10760 break;
10761 }
10762
10763 if (TemplateArgumentMismatch) {
10764 Diagnosed = true;
10765 break;
10766 }
10767 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010768
10769 // Compute the hash of the method as if it has no body.
10770 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10771 Hash.clear();
10772 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10773 return Hash.CalculateHash();
10774 };
10775
10776 // Compare the hash generated to the hash stored. A difference means
10777 // that a body was present in the original source. Due to merging,
10778 // the stardard way of detecting a body will not work.
10779 const bool HasFirstBody =
10780 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10781 const bool HasSecondBody =
10782 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10783
10784 if (HasFirstBody != HasSecondBody) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010785 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10786 FirstMethod->getSourceRange(), MethodSingleBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010787 << FirstMethodType << FirstName << HasFirstBody;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010788 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10789 SecondMethod->getSourceRange(), MethodSingleBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010790 << SecondMethodType << SecondName << HasSecondBody;
10791 Diagnosed = true;
10792 break;
10793 }
10794
10795 if (HasFirstBody && HasSecondBody) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010796 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10797 FirstMethod->getSourceRange(), MethodDifferentBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010798 << FirstMethodType << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010799 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10800 SecondMethod->getSourceRange(), MethodDifferentBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010801 << SecondMethodType << SecondName;
10802 Diagnosed = true;
10803 break;
10804 }
10805
Richard Trieu48143742017-02-28 21:24:38 +000010806 break;
10807 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010808 case TypeAlias:
10809 case TypeDef: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010810 Diagnosed = ODRDiagTypeDefOrAlias(
10811 FirstRecord, FirstModule, SecondModule,
10812 cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl),
10813 FirstDiffType == TypeAlias);
Richard Trieu11d566a2017-06-12 21:58:22 +000010814 break;
10815 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010816 case Var: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010817 Diagnosed =
10818 ODRDiagVar(FirstRecord, FirstModule, SecondModule,
10819 cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl));
Richard Trieu6e13ff32017-06-16 02:44:29 +000010820 break;
10821 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010822 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010823 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10824 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010825
10826 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10827 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10828
10829 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10830 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10831
10832 if (FirstND && SecondND) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010833 ODRDiagDeclError(FirstRecord, FirstModule,
10834 FirstFriend->getFriendLoc(),
10835 FirstFriend->getSourceRange(), FriendFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010836 << FirstND;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010837 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10838 SecondFriend->getSourceRange(), FriendFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010839 << SecondND;
10840
10841 Diagnosed = true;
10842 break;
10843 }
10844
10845 if (FirstTSI && SecondTSI) {
10846 QualType FirstFriendType = FirstTSI->getType();
10847 QualType SecondFriendType = SecondTSI->getType();
10848 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10849 ComputeQualTypeODRHash(SecondFriendType));
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010850 ODRDiagDeclError(FirstRecord, FirstModule,
10851 FirstFriend->getFriendLoc(),
10852 FirstFriend->getSourceRange(), FriendType)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010853 << FirstFriendType;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010854 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10855 SecondFriend->getSourceRange(), FriendType)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010856 << SecondFriendType;
10857 Diagnosed = true;
10858 break;
10859 }
10860
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010861 ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(),
10862 FirstFriend->getSourceRange(), FriendTypeFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010863 << (FirstTSI == nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010864 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10865 SecondFriend->getSourceRange(), FriendTypeFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010866 << (SecondTSI == nullptr);
10867
10868 Diagnosed = true;
10869 break;
10870 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010871 case FunctionTemplate: {
10872 FunctionTemplateDecl *FirstTemplate =
10873 cast<FunctionTemplateDecl>(FirstDecl);
10874 FunctionTemplateDecl *SecondTemplate =
10875 cast<FunctionTemplateDecl>(SecondDecl);
10876
10877 TemplateParameterList *FirstTPL =
10878 FirstTemplate->getTemplateParameters();
10879 TemplateParameterList *SecondTPL =
10880 SecondTemplate->getTemplateParameters();
10881
10882 if (FirstTPL->size() != SecondTPL->size()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010883 ODRDiagDeclError(FirstRecord, FirstModule,
10884 FirstTemplate->getLocation(),
10885 FirstTemplate->getSourceRange(),
10886 FunctionTemplateDifferentNumberParameters)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010887 << FirstTemplate << FirstTPL->size();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010888 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10889 SecondTemplate->getSourceRange(),
10890 FunctionTemplateDifferentNumberParameters)
10891 << SecondTemplate << SecondTPL->size();
Richard Trieu9359e8f2018-05-30 01:12:26 +000010892
10893 Diagnosed = true;
10894 break;
10895 }
10896
10897 bool ParameterMismatch = false;
10898 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10899 NamedDecl *FirstParam = FirstTPL->getParam(i);
10900 NamedDecl *SecondParam = SecondTPL->getParam(i);
10901
10902 if (FirstParam->getKind() != SecondParam->getKind()) {
10903 enum {
10904 TemplateTypeParameter,
10905 NonTypeTemplateParameter,
10906 TemplateTemplateParameter,
10907 };
10908 auto GetParamType = [](NamedDecl *D) {
10909 switch (D->getKind()) {
10910 default:
10911 llvm_unreachable("Unexpected template parameter type");
10912 case Decl::TemplateTypeParm:
10913 return TemplateTypeParameter;
10914 case Decl::NonTypeTemplateParm:
10915 return NonTypeTemplateParameter;
10916 case Decl::TemplateTemplateParm:
10917 return TemplateTemplateParameter;
10918 }
10919 };
10920
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010921 ODRDiagDeclError(FirstRecord, FirstModule,
10922 FirstTemplate->getLocation(),
10923 FirstTemplate->getSourceRange(),
10924 FunctionTemplateParameterDifferentKind)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010925 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010926 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10927 SecondTemplate->getSourceRange(),
10928 FunctionTemplateParameterDifferentKind)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010929 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10930
10931 ParameterMismatch = true;
10932 break;
10933 }
10934
10935 if (FirstParam->getName() != SecondParam->getName()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010936 ODRDiagDeclError(
10937 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10938 FirstTemplate->getSourceRange(), FunctionTemplateParameterName)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010939 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10940 << FirstParam;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010941 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10942 SecondTemplate->getSourceRange(),
10943 FunctionTemplateParameterName)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010944 << SecondTemplate << (i + 1)
10945 << (bool)SecondParam->getIdentifier() << SecondParam;
10946 ParameterMismatch = true;
10947 break;
10948 }
10949
10950 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10951 isa<TemplateTypeParmDecl>(SecondParam)) {
10952 TemplateTypeParmDecl *FirstTTPD =
10953 cast<TemplateTypeParmDecl>(FirstParam);
10954 TemplateTypeParmDecl *SecondTTPD =
10955 cast<TemplateTypeParmDecl>(SecondParam);
10956 bool HasFirstDefaultArgument =
10957 FirstTTPD->hasDefaultArgument() &&
10958 !FirstTTPD->defaultArgumentWasInherited();
10959 bool HasSecondDefaultArgument =
10960 SecondTTPD->hasDefaultArgument() &&
10961 !SecondTTPD->defaultArgumentWasInherited();
10962 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010963 ODRDiagDeclError(FirstRecord, FirstModule,
10964 FirstTemplate->getLocation(),
10965 FirstTemplate->getSourceRange(),
10966 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010967 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010968 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10969 SecondTemplate->getSourceRange(),
10970 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010971 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10972 ParameterMismatch = true;
10973 break;
10974 }
10975
10976 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10977 QualType FirstType = FirstTTPD->getDefaultArgument();
10978 QualType SecondType = SecondTTPD->getDefaultArgument();
10979 if (ComputeQualTypeODRHash(FirstType) !=
10980 ComputeQualTypeODRHash(SecondType)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010981 ODRDiagDeclError(
10982 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10983 FirstTemplate->getSourceRange(),
10984 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010985 << FirstTemplate << (i + 1) << FirstType;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010986 ODRDiagDeclNote(
10987 SecondModule, SecondTemplate->getLocation(),
10988 SecondTemplate->getSourceRange(),
10989 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010990 << SecondTemplate << (i + 1) << SecondType;
10991 ParameterMismatch = true;
10992 break;
10993 }
10994 }
10995
10996 if (FirstTTPD->isParameterPack() !=
10997 SecondTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010998 ODRDiagDeclError(FirstRecord, FirstModule,
10999 FirstTemplate->getLocation(),
11000 FirstTemplate->getSourceRange(),
11001 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011002 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011003 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11004 SecondTemplate->getSourceRange(),
11005 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011006 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11007 ParameterMismatch = true;
11008 break;
11009 }
11010 }
11011
11012 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11013 isa<TemplateTemplateParmDecl>(SecondParam)) {
11014 TemplateTemplateParmDecl *FirstTTPD =
11015 cast<TemplateTemplateParmDecl>(FirstParam);
11016 TemplateTemplateParmDecl *SecondTTPD =
11017 cast<TemplateTemplateParmDecl>(SecondParam);
11018
11019 TemplateParameterList *FirstTPL =
11020 FirstTTPD->getTemplateParameters();
11021 TemplateParameterList *SecondTPL =
11022 SecondTTPD->getTemplateParameters();
11023
11024 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11025 ComputeTemplateParameterListODRHash(SecondTPL)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011026 ODRDiagDeclError(FirstRecord, FirstModule,
11027 FirstTemplate->getLocation(),
11028 FirstTemplate->getSourceRange(),
11029 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011030 << FirstTemplate << (i + 1);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011031 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11032 SecondTemplate->getSourceRange(),
11033 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011034 << SecondTemplate << (i + 1);
11035 ParameterMismatch = true;
11036 break;
11037 }
11038
11039 bool HasFirstDefaultArgument =
11040 FirstTTPD->hasDefaultArgument() &&
11041 !FirstTTPD->defaultArgumentWasInherited();
11042 bool HasSecondDefaultArgument =
11043 SecondTTPD->hasDefaultArgument() &&
11044 !SecondTTPD->defaultArgumentWasInherited();
11045 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011046 ODRDiagDeclError(FirstRecord, FirstModule,
11047 FirstTemplate->getLocation(),
11048 FirstTemplate->getSourceRange(),
11049 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011050 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011051 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11052 SecondTemplate->getSourceRange(),
11053 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011054 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11055 ParameterMismatch = true;
11056 break;
11057 }
11058
11059 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11060 TemplateArgument FirstTA =
11061 FirstTTPD->getDefaultArgument().getArgument();
11062 TemplateArgument SecondTA =
11063 SecondTTPD->getDefaultArgument().getArgument();
11064 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11065 ComputeTemplateArgumentODRHash(SecondTA)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011066 ODRDiagDeclError(
11067 FirstRecord, FirstModule, FirstTemplate->getLocation(),
11068 FirstTemplate->getSourceRange(),
11069 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011070 << FirstTemplate << (i + 1) << FirstTA;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011071 ODRDiagDeclNote(
11072 SecondModule, SecondTemplate->getLocation(),
11073 SecondTemplate->getSourceRange(),
11074 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011075 << SecondTemplate << (i + 1) << SecondTA;
11076 ParameterMismatch = true;
11077 break;
11078 }
11079 }
11080
11081 if (FirstTTPD->isParameterPack() !=
11082 SecondTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011083 ODRDiagDeclError(FirstRecord, FirstModule,
11084 FirstTemplate->getLocation(),
11085 FirstTemplate->getSourceRange(),
11086 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011087 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011088 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11089 SecondTemplate->getSourceRange(),
11090 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011091 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11092 ParameterMismatch = true;
11093 break;
11094 }
11095 }
11096
11097 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11098 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11099 NonTypeTemplateParmDecl *FirstNTTPD =
11100 cast<NonTypeTemplateParmDecl>(FirstParam);
11101 NonTypeTemplateParmDecl *SecondNTTPD =
11102 cast<NonTypeTemplateParmDecl>(SecondParam);
11103
11104 QualType FirstType = FirstNTTPD->getType();
11105 QualType SecondType = SecondNTTPD->getType();
11106 if (ComputeQualTypeODRHash(FirstType) !=
11107 ComputeQualTypeODRHash(SecondType)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011108 ODRDiagDeclError(FirstRecord, FirstModule,
11109 FirstTemplate->getLocation(),
11110 FirstTemplate->getSourceRange(),
11111 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011112 << FirstTemplate << (i + 1);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011113 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11114 SecondTemplate->getSourceRange(),
11115 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011116 << SecondTemplate << (i + 1);
11117 ParameterMismatch = true;
11118 break;
11119 }
11120
11121 bool HasFirstDefaultArgument =
11122 FirstNTTPD->hasDefaultArgument() &&
11123 !FirstNTTPD->defaultArgumentWasInherited();
11124 bool HasSecondDefaultArgument =
11125 SecondNTTPD->hasDefaultArgument() &&
11126 !SecondNTTPD->defaultArgumentWasInherited();
11127 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011128 ODRDiagDeclError(FirstRecord, FirstModule,
11129 FirstTemplate->getLocation(),
11130 FirstTemplate->getSourceRange(),
11131 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011132 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011133 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11134 SecondTemplate->getSourceRange(),
11135 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011136 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11137 ParameterMismatch = true;
11138 break;
11139 }
11140
11141 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11142 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11143 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11144 if (ComputeODRHash(FirstDefaultArgument) !=
11145 ComputeODRHash(SecondDefaultArgument)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011146 ODRDiagDeclError(
11147 FirstRecord, FirstModule, FirstTemplate->getLocation(),
11148 FirstTemplate->getSourceRange(),
11149 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011150 << FirstTemplate << (i + 1) << FirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011151 ODRDiagDeclNote(
11152 SecondModule, SecondTemplate->getLocation(),
11153 SecondTemplate->getSourceRange(),
11154 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011155 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11156 ParameterMismatch = true;
11157 break;
11158 }
11159 }
11160
11161 if (FirstNTTPD->isParameterPack() !=
11162 SecondNTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011163 ODRDiagDeclError(FirstRecord, FirstModule,
11164 FirstTemplate->getLocation(),
11165 FirstTemplate->getSourceRange(),
11166 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011167 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011168 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11169 SecondTemplate->getSourceRange(),
11170 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011171 << SecondTemplate << (i + 1)
11172 << SecondNTTPD->isParameterPack();
11173 ParameterMismatch = true;
11174 break;
11175 }
11176 }
11177 }
11178
11179 if (ParameterMismatch) {
11180 Diagnosed = true;
11181 break;
11182 }
11183
11184 break;
11185 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011186 }
11187
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011188 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011189 continue;
11190
Richard Trieu708859a2017-06-08 00:56:21 +000011191 Diag(FirstDecl->getLocation(),
11192 diag::err_module_odr_violation_mismatch_decl_unknown)
11193 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11194 << FirstDecl->getSourceRange();
11195 Diag(SecondDecl->getLocation(),
11196 diag::note_module_odr_violation_mismatch_decl_unknown)
11197 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011198 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011199 }
11200
11201 if (!Diagnosed) {
11202 // All definitions are updates to the same declaration. This happens if a
11203 // module instantiates the declaration of a class template specialization
11204 // and two or more other modules instantiate its definition.
11205 //
11206 // FIXME: Indicate which modules had instantiations of this definition.
11207 // FIXME: How can this even happen?
11208 Diag(Merge.first->getLocation(),
11209 diag::err_module_odr_violation_different_instantiations)
11210 << Merge.first;
11211 }
11212 }
Richard Trieue6caa262017-12-23 00:41:01 +000011213
11214 // Issue ODR failures diagnostics for functions.
11215 for (auto &Merge : FunctionOdrMergeFailures) {
11216 enum ODRFunctionDifference {
11217 ReturnType,
11218 ParameterName,
11219 ParameterType,
11220 ParameterSingleDefaultArgument,
11221 ParameterDifferentDefaultArgument,
11222 FunctionBody,
11223 };
11224
11225 FunctionDecl *FirstFunction = Merge.first;
11226 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11227
11228 bool Diagnosed = false;
11229 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011230
Richard Trieue6caa262017-12-23 00:41:01 +000011231 if (FirstFunction == SecondFunction)
11232 continue;
11233
11234 std::string SecondModule =
11235 getOwningModuleNameForDiagnostic(SecondFunction);
11236
11237 auto ODRDiagError = [FirstFunction, &FirstModule,
11238 this](SourceLocation Loc, SourceRange Range,
11239 ODRFunctionDifference DiffType) {
11240 return Diag(Loc, diag::err_module_odr_violation_function)
11241 << FirstFunction << FirstModule.empty() << FirstModule << Range
11242 << DiffType;
11243 };
11244 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11245 SourceRange Range,
11246 ODRFunctionDifference DiffType) {
11247 return Diag(Loc, diag::note_module_odr_violation_function)
11248 << SecondModule << Range << DiffType;
11249 };
11250
11251 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11252 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11253 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11254 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11255 << FirstFunction->getReturnType();
11256 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11257 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11258 << SecondFunction->getReturnType();
11259 Diagnosed = true;
11260 break;
11261 }
11262
11263 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11264 "Merged functions with different number of parameters");
11265
11266 auto ParamSize = FirstFunction->param_size();
11267 bool ParameterMismatch = false;
11268 for (unsigned I = 0; I < ParamSize; ++I) {
11269 auto *FirstParam = FirstFunction->getParamDecl(I);
11270 auto *SecondParam = SecondFunction->getParamDecl(I);
11271
11272 assert(getContext().hasSameType(FirstParam->getType(),
11273 SecondParam->getType()) &&
11274 "Merged function has different parameter types.");
11275
11276 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11277 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11278 ParameterName)
11279 << I + 1 << FirstParam->getDeclName();
11280 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11281 ParameterName)
11282 << I + 1 << SecondParam->getDeclName();
11283 ParameterMismatch = true;
11284 break;
11285 };
11286
11287 QualType FirstParamType = FirstParam->getType();
11288 QualType SecondParamType = SecondParam->getType();
11289 if (FirstParamType != SecondParamType &&
11290 ComputeQualTypeODRHash(FirstParamType) !=
11291 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011292 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011293 FirstParamType->getAs<DecayedType>()) {
11294 ODRDiagError(FirstParam->getLocation(),
11295 FirstParam->getSourceRange(), ParameterType)
11296 << (I + 1) << FirstParamType << true
11297 << ParamDecayedType->getOriginalType();
11298 } else {
11299 ODRDiagError(FirstParam->getLocation(),
11300 FirstParam->getSourceRange(), ParameterType)
11301 << (I + 1) << FirstParamType << false;
11302 }
11303
Vedant Kumar48b4f762018-04-14 01:40:48 +000011304 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011305 SecondParamType->getAs<DecayedType>()) {
11306 ODRDiagNote(SecondParam->getLocation(),
11307 SecondParam->getSourceRange(), ParameterType)
11308 << (I + 1) << SecondParamType << true
11309 << ParamDecayedType->getOriginalType();
11310 } else {
11311 ODRDiagNote(SecondParam->getLocation(),
11312 SecondParam->getSourceRange(), ParameterType)
11313 << (I + 1) << SecondParamType << false;
11314 }
11315 ParameterMismatch = true;
11316 break;
11317 }
11318
11319 const Expr *FirstInit = FirstParam->getInit();
11320 const Expr *SecondInit = SecondParam->getInit();
11321 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11322 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11323 ParameterSingleDefaultArgument)
11324 << (I + 1) << (FirstInit == nullptr)
11325 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11326 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11327 ParameterSingleDefaultArgument)
11328 << (I + 1) << (SecondInit == nullptr)
11329 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11330 ParameterMismatch = true;
11331 break;
11332 }
11333
11334 if (FirstInit && SecondInit &&
11335 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11336 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11337 ParameterDifferentDefaultArgument)
11338 << (I + 1) << FirstInit->getSourceRange();
11339 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11340 ParameterDifferentDefaultArgument)
11341 << (I + 1) << SecondInit->getSourceRange();
11342 ParameterMismatch = true;
11343 break;
11344 }
11345
11346 assert(ComputeSubDeclODRHash(FirstParam) ==
11347 ComputeSubDeclODRHash(SecondParam) &&
11348 "Undiagnosed parameter difference.");
11349 }
11350
11351 if (ParameterMismatch) {
11352 Diagnosed = true;
11353 break;
11354 }
11355
11356 // If no error has been generated before now, assume the problem is in
11357 // the body and generate a message.
11358 ODRDiagError(FirstFunction->getLocation(),
11359 FirstFunction->getSourceRange(), FunctionBody);
11360 ODRDiagNote(SecondFunction->getLocation(),
11361 SecondFunction->getSourceRange(), FunctionBody);
11362 Diagnosed = true;
11363 break;
11364 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011365 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011366 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11367 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011368
11369 // Issue ODR failures diagnostics for enums.
11370 for (auto &Merge : EnumOdrMergeFailures) {
11371 enum ODREnumDifference {
11372 SingleScopedEnum,
11373 EnumTagKeywordMismatch,
11374 SingleSpecifiedType,
11375 DifferentSpecifiedTypes,
11376 DifferentNumberEnumConstants,
11377 EnumConstantName,
11378 EnumConstantSingleInitilizer,
11379 EnumConstantDifferentInitilizer,
11380 };
11381
11382 // If we've already pointed out a specific problem with this enum, don't
11383 // bother issuing a general "something's different" diagnostic.
11384 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11385 continue;
11386
11387 EnumDecl *FirstEnum = Merge.first;
11388 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11389
11390 using DeclHashes =
11391 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11392 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11393 DeclHashes &Hashes, EnumDecl *Enum) {
11394 for (auto *D : Enum->decls()) {
11395 // Due to decl merging, the first EnumDecl is the parent of
11396 // Decls in both records.
11397 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11398 continue;
11399 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11400 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11401 ComputeSubDeclODRHash(D));
11402 }
11403 };
11404 DeclHashes FirstHashes;
11405 PopulateHashes(FirstHashes, FirstEnum);
11406 bool Diagnosed = false;
11407 for (auto &SecondEnum : Merge.second) {
11408
11409 if (FirstEnum == SecondEnum)
11410 continue;
11411
11412 std::string SecondModule =
11413 getOwningModuleNameForDiagnostic(SecondEnum);
11414
11415 auto ODRDiagError = [FirstEnum, &FirstModule,
11416 this](SourceLocation Loc, SourceRange Range,
11417 ODREnumDifference DiffType) {
11418 return Diag(Loc, diag::err_module_odr_violation_enum)
11419 << FirstEnum << FirstModule.empty() << FirstModule << Range
11420 << DiffType;
11421 };
11422 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11423 SourceRange Range,
11424 ODREnumDifference DiffType) {
11425 return Diag(Loc, diag::note_module_odr_violation_enum)
11426 << SecondModule << Range << DiffType;
11427 };
11428
11429 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11430 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11431 SingleScopedEnum)
11432 << FirstEnum->isScoped();
11433 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11434 SingleScopedEnum)
11435 << SecondEnum->isScoped();
11436 Diagnosed = true;
11437 continue;
11438 }
11439
11440 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11441 if (FirstEnum->isScopedUsingClassTag() !=
11442 SecondEnum->isScopedUsingClassTag()) {
11443 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11444 EnumTagKeywordMismatch)
11445 << FirstEnum->isScopedUsingClassTag();
11446 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11447 EnumTagKeywordMismatch)
11448 << SecondEnum->isScopedUsingClassTag();
11449 Diagnosed = true;
11450 continue;
11451 }
11452 }
11453
11454 QualType FirstUnderlyingType =
11455 FirstEnum->getIntegerTypeSourceInfo()
11456 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11457 : QualType();
11458 QualType SecondUnderlyingType =
11459 SecondEnum->getIntegerTypeSourceInfo()
11460 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11461 : QualType();
11462 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11463 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11464 SingleSpecifiedType)
11465 << !FirstUnderlyingType.isNull();
11466 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11467 SingleSpecifiedType)
11468 << !SecondUnderlyingType.isNull();
11469 Diagnosed = true;
11470 continue;
11471 }
11472
11473 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11474 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11475 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11476 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11477 DifferentSpecifiedTypes)
11478 << FirstUnderlyingType;
11479 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11480 DifferentSpecifiedTypes)
11481 << SecondUnderlyingType;
11482 Diagnosed = true;
11483 continue;
11484 }
11485 }
11486
11487 DeclHashes SecondHashes;
11488 PopulateHashes(SecondHashes, SecondEnum);
11489
11490 if (FirstHashes.size() != SecondHashes.size()) {
11491 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11492 DifferentNumberEnumConstants)
11493 << (int)FirstHashes.size();
11494 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11495 DifferentNumberEnumConstants)
11496 << (int)SecondHashes.size();
11497 Diagnosed = true;
11498 continue;
11499 }
11500
11501 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11502 if (FirstHashes[I].second == SecondHashes[I].second)
11503 continue;
11504 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11505 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11506
11507 if (FirstEnumConstant->getDeclName() !=
11508 SecondEnumConstant->getDeclName()) {
11509
11510 ODRDiagError(FirstEnumConstant->getLocation(),
11511 FirstEnumConstant->getSourceRange(), EnumConstantName)
11512 << I + 1 << FirstEnumConstant;
11513 ODRDiagNote(SecondEnumConstant->getLocation(),
11514 SecondEnumConstant->getSourceRange(), EnumConstantName)
11515 << I + 1 << SecondEnumConstant;
11516 Diagnosed = true;
11517 break;
11518 }
11519
11520 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11521 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11522 if (!FirstInit && !SecondInit)
11523 continue;
11524
11525 if (!FirstInit || !SecondInit) {
11526 ODRDiagError(FirstEnumConstant->getLocation(),
11527 FirstEnumConstant->getSourceRange(),
11528 EnumConstantSingleInitilizer)
11529 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11530 ODRDiagNote(SecondEnumConstant->getLocation(),
11531 SecondEnumConstant->getSourceRange(),
11532 EnumConstantSingleInitilizer)
11533 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11534 Diagnosed = true;
11535 break;
11536 }
11537
11538 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11539 ODRDiagError(FirstEnumConstant->getLocation(),
11540 FirstEnumConstant->getSourceRange(),
11541 EnumConstantDifferentInitilizer)
11542 << I + 1 << FirstEnumConstant;
11543 ODRDiagNote(SecondEnumConstant->getLocation(),
11544 SecondEnumConstant->getSourceRange(),
11545 EnumConstantDifferentInitilizer)
11546 << I + 1 << SecondEnumConstant;
11547 Diagnosed = true;
11548 break;
11549 }
11550 }
11551 }
11552
11553 (void)Diagnosed;
11554 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11555 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011556}
11557
Richard Smithce18a182015-07-14 00:26:00 +000011558void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011559 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011560 ReadTimer->startTimer();
11561}
11562
Guy Benyei11169dd2012-12-18 14:30:41 +000011563void ASTReader::FinishedDeserializing() {
11564 assert(NumCurrentElementsDeserializing &&
11565 "FinishedDeserializing not paired with StartedDeserializing");
11566 if (NumCurrentElementsDeserializing == 1) {
11567 // We decrease NumCurrentElementsDeserializing only after pending actions
11568 // are finished, to avoid recursively re-calling finishPendingActions().
11569 finishPendingActions();
11570 }
11571 --NumCurrentElementsDeserializing;
11572
Richard Smitha0ce9c42014-07-29 23:23:27 +000011573 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011574 // Propagate exception specification and deduced type updates along
11575 // redeclaration chains.
11576 //
11577 // We do this now rather than in finishPendingActions because we want to
11578 // be able to walk the complete redeclaration chains of the updated decls.
11579 while (!PendingExceptionSpecUpdates.empty() ||
11580 !PendingDeducedTypeUpdates.empty()) {
11581 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011582 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011583 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011584 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011585 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011586 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011587 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011588 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011589 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011590 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011591 }
Richard Smitha62d1982018-08-03 01:00:01 +000011592
11593 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11594 PendingDeducedTypeUpdates.clear();
11595 for (auto Update : DTUpdates) {
11596 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11597 // FIXME: If the return type is already deduced, check that it matches.
11598 getContext().adjustDeducedFunctionResultType(Update.first,
11599 Update.second);
11600 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011601 }
11602
Richard Smithce18a182015-07-14 00:26:00 +000011603 if (ReadTimer)
11604 ReadTimer->stopTimer();
11605
Richard Smith0f4e2c42015-08-06 04:23:48 +000011606 diagnoseOdrViolations();
11607
Richard Smith04d05b52014-03-23 00:27:18 +000011608 // We are not in recursive loading, so it's safe to pass the "interesting"
11609 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011610 if (Consumer)
11611 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011612 }
11613}
11614
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011615void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011616 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11617 // Remove any fake results before adding any real ones.
11618 auto It = PendingFakeLookupResults.find(II);
11619 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011620 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011621 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011622 // FIXME: this works around module+PCH performance issue.
11623 // Rather than erase the result from the map, which is O(n), just clear
11624 // the vector of NamedDecls.
11625 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011626 }
11627 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011628
11629 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11630 SemaObj->TUScope->AddDecl(D);
11631 } else if (SemaObj->TUScope) {
11632 // Adding the decl to IdResolver may have failed because it was already in
11633 // (even though it was not added in scope). If it is already in, make sure
11634 // it gets in the scope as well.
11635 if (std::find(SemaObj->IdResolver.begin(Name),
11636 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11637 SemaObj->TUScope->AddDecl(D);
11638 }
11639}
11640
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011641ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11642 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011643 const PCHContainerReader &PCHContainerRdr,
11644 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11645 StringRef isysroot, bool DisableValidation,
11646 bool AllowASTWithCompilerErrors,
11647 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011648 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
David Blaikie61137e12017-01-05 18:23:18 +000011649 std::unique_ptr<llvm::Timer> ReadTimer)
11650 : Listener(DisableValidation
11651 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11652 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011653 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011654 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011655 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11656 PCHContainerRdr, PP.getHeaderSearchInfo()),
11657 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011658 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011659 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11660 AllowConfigurationMismatch(AllowConfigurationMismatch),
11661 ValidateSystemInputs(ValidateSystemInputs),
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011662 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011663 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011664 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011665
11666 for (const auto &Ext : Extensions) {
11667 auto BlockName = Ext->getExtensionMetadata().BlockName;
11668 auto Known = ModuleFileExtensions.find(BlockName);
11669 if (Known != ModuleFileExtensions.end()) {
11670 Diags.Report(diag::warn_duplicate_module_file_extension)
11671 << BlockName;
11672 continue;
11673 }
11674
11675 ModuleFileExtensions.insert({BlockName, Ext});
11676 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011677}
11678
11679ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011680 if (OwnsDeserializationListener)
11681 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011682}
Richard Smith10379092016-05-06 23:14:07 +000011683
11684IdentifierResolver &ASTReader::getIdResolver() {
11685 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11686}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011687
JF Bastien0e828952019-06-26 19:50:12 +000011688Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11689 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000011690 Idx = 0;
11691 Record.clear();
11692 return Cursor.readRecord(AbbrevID, Record);
11693}
Kelvin Libe286f52018-09-15 13:54:15 +000011694//===----------------------------------------------------------------------===//
11695//// OMPClauseReader implementation
11696////===----------------------------------------------------------------------===//
11697
John McCallc2f18312019-12-14 03:01:28 -050011698// This has to be in namespace clang because it's friended by all
11699// of the OMP clauses.
11700namespace clang {
11701
11702class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11703 ASTRecordReader &Record;
11704 ASTContext &Context;
11705
11706public:
11707 OMPClauseReader(ASTRecordReader &Record)
11708 : Record(Record), Context(Record.getContext()) {}
11709
Johannes Doerfert419a5592020-03-30 19:58:40 -050011710#define OMP_CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
11711#include "llvm/Frontend/OpenMP/OMPKinds.def"
John McCallc2f18312019-12-14 03:01:28 -050011712 OMPClause *readClause();
11713 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11714 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11715};
11716
11717} // end namespace clang
11718
11719OMPClause *ASTRecordReader::readOMPClause() {
11720 return OMPClauseReader(*this).readClause();
11721}
11722
Kelvin Libe286f52018-09-15 13:54:15 +000011723OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011724 OMPClause *C = nullptr;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011725 switch (llvm::omp::Clause(Record.readInt())) {
11726 case llvm::omp::OMPC_if:
Kelvin Libe286f52018-09-15 13:54:15 +000011727 C = new (Context) OMPIfClause();
11728 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011729 case llvm::omp::OMPC_final:
Kelvin Libe286f52018-09-15 13:54:15 +000011730 C = new (Context) OMPFinalClause();
11731 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011732 case llvm::omp::OMPC_num_threads:
Kelvin Libe286f52018-09-15 13:54:15 +000011733 C = new (Context) OMPNumThreadsClause();
11734 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011735 case llvm::omp::OMPC_safelen:
Kelvin Libe286f52018-09-15 13:54:15 +000011736 C = new (Context) OMPSafelenClause();
11737 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011738 case llvm::omp::OMPC_simdlen:
Kelvin Libe286f52018-09-15 13:54:15 +000011739 C = new (Context) OMPSimdlenClause();
11740 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011741 case llvm::omp::OMPC_allocator:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011742 C = new (Context) OMPAllocatorClause();
11743 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011744 case llvm::omp::OMPC_collapse:
Kelvin Libe286f52018-09-15 13:54:15 +000011745 C = new (Context) OMPCollapseClause();
11746 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011747 case llvm::omp::OMPC_default:
Kelvin Libe286f52018-09-15 13:54:15 +000011748 C = new (Context) OMPDefaultClause();
11749 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011750 case llvm::omp::OMPC_proc_bind:
Kelvin Libe286f52018-09-15 13:54:15 +000011751 C = new (Context) OMPProcBindClause();
11752 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011753 case llvm::omp::OMPC_schedule:
Kelvin Libe286f52018-09-15 13:54:15 +000011754 C = new (Context) OMPScheduleClause();
11755 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011756 case llvm::omp::OMPC_ordered:
Kelvin Libe286f52018-09-15 13:54:15 +000011757 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11758 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011759 case llvm::omp::OMPC_nowait:
Kelvin Libe286f52018-09-15 13:54:15 +000011760 C = new (Context) OMPNowaitClause();
11761 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011762 case llvm::omp::OMPC_untied:
Kelvin Libe286f52018-09-15 13:54:15 +000011763 C = new (Context) OMPUntiedClause();
11764 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011765 case llvm::omp::OMPC_mergeable:
Kelvin Libe286f52018-09-15 13:54:15 +000011766 C = new (Context) OMPMergeableClause();
11767 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011768 case llvm::omp::OMPC_read:
Kelvin Libe286f52018-09-15 13:54:15 +000011769 C = new (Context) OMPReadClause();
11770 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011771 case llvm::omp::OMPC_write:
Kelvin Libe286f52018-09-15 13:54:15 +000011772 C = new (Context) OMPWriteClause();
11773 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011774 case llvm::omp::OMPC_update:
Alexey Bataev82f7c202020-03-03 13:22:35 -050011775 C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
Kelvin Libe286f52018-09-15 13:54:15 +000011776 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011777 case llvm::omp::OMPC_capture:
Kelvin Libe286f52018-09-15 13:54:15 +000011778 C = new (Context) OMPCaptureClause();
11779 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011780 case llvm::omp::OMPC_seq_cst:
Kelvin Libe286f52018-09-15 13:54:15 +000011781 C = new (Context) OMPSeqCstClause();
11782 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011783 case llvm::omp::OMPC_acq_rel:
Alexey Bataevea9166b2020-02-06 16:30:23 -050011784 C = new (Context) OMPAcqRelClause();
11785 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011786 case llvm::omp::OMPC_acquire:
Alexey Bataev04a830f2020-02-10 14:30:39 -050011787 C = new (Context) OMPAcquireClause();
11788 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011789 case llvm::omp::OMPC_release:
Alexey Bataev95598342020-02-10 15:49:05 -050011790 C = new (Context) OMPReleaseClause();
11791 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011792 case llvm::omp::OMPC_relaxed:
Alexey Bataev9a8defc2020-02-11 11:10:43 -050011793 C = new (Context) OMPRelaxedClause();
11794 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011795 case llvm::omp::OMPC_threads:
Kelvin Libe286f52018-09-15 13:54:15 +000011796 C = new (Context) OMPThreadsClause();
11797 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011798 case llvm::omp::OMPC_simd:
Kelvin Libe286f52018-09-15 13:54:15 +000011799 C = new (Context) OMPSIMDClause();
11800 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011801 case llvm::omp::OMPC_nogroup:
Kelvin Libe286f52018-09-15 13:54:15 +000011802 C = new (Context) OMPNogroupClause();
11803 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011804 case llvm::omp::OMPC_unified_address:
Kelvin Li1408f912018-09-26 04:28:39 +000011805 C = new (Context) OMPUnifiedAddressClause();
11806 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011807 case llvm::omp::OMPC_unified_shared_memory:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011808 C = new (Context) OMPUnifiedSharedMemoryClause();
11809 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011810 case llvm::omp::OMPC_reverse_offload:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011811 C = new (Context) OMPReverseOffloadClause();
11812 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011813 case llvm::omp::OMPC_dynamic_allocators:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011814 C = new (Context) OMPDynamicAllocatorsClause();
11815 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011816 case llvm::omp::OMPC_atomic_default_mem_order:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011817 C = new (Context) OMPAtomicDefaultMemOrderClause();
11818 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011819 case llvm::omp::OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000011820 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11821 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011822 case llvm::omp::OMPC_firstprivate:
Kelvin Libe286f52018-09-15 13:54:15 +000011823 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11824 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011825 case llvm::omp::OMPC_lastprivate:
Kelvin Libe286f52018-09-15 13:54:15 +000011826 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11827 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011828 case llvm::omp::OMPC_shared:
Kelvin Libe286f52018-09-15 13:54:15 +000011829 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11830 break;
Alexey Bataevbd1c03d2020-05-04 16:19:31 -040011831 case llvm::omp::OMPC_reduction: {
11832 unsigned N = Record.readInt();
11833 auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
11834 C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
Kelvin Libe286f52018-09-15 13:54:15 +000011835 break;
Alexey Bataevbd1c03d2020-05-04 16:19:31 -040011836 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011837 case llvm::omp::OMPC_task_reduction:
Kelvin Libe286f52018-09-15 13:54:15 +000011838 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11839 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011840 case llvm::omp::OMPC_in_reduction:
Kelvin Libe286f52018-09-15 13:54:15 +000011841 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11842 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011843 case llvm::omp::OMPC_linear:
Kelvin Libe286f52018-09-15 13:54:15 +000011844 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11845 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011846 case llvm::omp::OMPC_aligned:
Kelvin Libe286f52018-09-15 13:54:15 +000011847 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11848 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011849 case llvm::omp::OMPC_copyin:
Kelvin Libe286f52018-09-15 13:54:15 +000011850 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11851 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011852 case llvm::omp::OMPC_copyprivate:
Kelvin Libe286f52018-09-15 13:54:15 +000011853 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11854 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011855 case llvm::omp::OMPC_flush:
Kelvin Libe286f52018-09-15 13:54:15 +000011856 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11857 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011858 case llvm::omp::OMPC_depobj:
Alexey Bataevc112e942020-02-28 09:52:15 -050011859 C = OMPDepobjClause::CreateEmpty(Context);
11860 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011861 case llvm::omp::OMPC_depend: {
Kelvin Libe286f52018-09-15 13:54:15 +000011862 unsigned NumVars = Record.readInt();
11863 unsigned NumLoops = Record.readInt();
11864 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11865 break;
11866 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011867 case llvm::omp::OMPC_device:
Kelvin Libe286f52018-09-15 13:54:15 +000011868 C = new (Context) OMPDeviceClause();
11869 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011870 case llvm::omp::OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011871 OMPMappableExprListSizeTy Sizes;
11872 Sizes.NumVars = Record.readInt();
11873 Sizes.NumUniqueDeclarations = Record.readInt();
11874 Sizes.NumComponentLists = Record.readInt();
11875 Sizes.NumComponents = Record.readInt();
11876 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011877 break;
11878 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011879 case llvm::omp::OMPC_num_teams:
Kelvin Libe286f52018-09-15 13:54:15 +000011880 C = new (Context) OMPNumTeamsClause();
11881 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011882 case llvm::omp::OMPC_thread_limit:
Kelvin Libe286f52018-09-15 13:54:15 +000011883 C = new (Context) OMPThreadLimitClause();
11884 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011885 case llvm::omp::OMPC_priority:
Kelvin Libe286f52018-09-15 13:54:15 +000011886 C = new (Context) OMPPriorityClause();
11887 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011888 case llvm::omp::OMPC_grainsize:
Kelvin Libe286f52018-09-15 13:54:15 +000011889 C = new (Context) OMPGrainsizeClause();
11890 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011891 case llvm::omp::OMPC_num_tasks:
Kelvin Libe286f52018-09-15 13:54:15 +000011892 C = new (Context) OMPNumTasksClause();
11893 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011894 case llvm::omp::OMPC_hint:
Kelvin Libe286f52018-09-15 13:54:15 +000011895 C = new (Context) OMPHintClause();
11896 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011897 case llvm::omp::OMPC_dist_schedule:
Kelvin Libe286f52018-09-15 13:54:15 +000011898 C = new (Context) OMPDistScheduleClause();
11899 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011900 case llvm::omp::OMPC_defaultmap:
Kelvin Libe286f52018-09-15 13:54:15 +000011901 C = new (Context) OMPDefaultmapClause();
11902 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011903 case llvm::omp::OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011904 OMPMappableExprListSizeTy Sizes;
11905 Sizes.NumVars = Record.readInt();
11906 Sizes.NumUniqueDeclarations = Record.readInt();
11907 Sizes.NumComponentLists = Record.readInt();
11908 Sizes.NumComponents = Record.readInt();
11909 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011910 break;
11911 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011912 case llvm::omp::OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011913 OMPMappableExprListSizeTy Sizes;
11914 Sizes.NumVars = Record.readInt();
11915 Sizes.NumUniqueDeclarations = Record.readInt();
11916 Sizes.NumComponentLists = Record.readInt();
11917 Sizes.NumComponents = Record.readInt();
11918 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011919 break;
11920 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011921 case llvm::omp::OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011922 OMPMappableExprListSizeTy Sizes;
11923 Sizes.NumVars = Record.readInt();
11924 Sizes.NumUniqueDeclarations = Record.readInt();
11925 Sizes.NumComponentLists = Record.readInt();
11926 Sizes.NumComponents = Record.readInt();
11927 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011928 break;
11929 }
Alexey Bataeva888fc62020-05-21 08:30:23 -040011930 case llvm::omp::OMPC_use_device_addr: {
11931 OMPMappableExprListSizeTy Sizes;
11932 Sizes.NumVars = Record.readInt();
11933 Sizes.NumUniqueDeclarations = Record.readInt();
11934 Sizes.NumComponentLists = Record.readInt();
11935 Sizes.NumComponents = Record.readInt();
11936 C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
11937 break;
11938 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011939 case llvm::omp::OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011940 OMPMappableExprListSizeTy Sizes;
11941 Sizes.NumVars = Record.readInt();
11942 Sizes.NumUniqueDeclarations = Record.readInt();
11943 Sizes.NumComponentLists = Record.readInt();
11944 Sizes.NumComponents = Record.readInt();
11945 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011946 break;
11947 }
Johannes Doerfert419a5592020-03-30 19:58:40 -050011948 case llvm::omp::OMPC_allocate:
Alexey Bataeve04483e2019-03-27 14:14:31 +000011949 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11950 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011951 case llvm::omp::OMPC_nontemporal:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011952 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11953 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011954 case llvm::omp::OMPC_inclusive:
Alexey Bataev06dea732020-03-20 09:41:22 -040011955 C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
11956 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011957 case llvm::omp::OMPC_exclusive:
Alexey Bataev63828a32020-03-23 10:41:08 -040011958 C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
11959 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011960 case llvm::omp::OMPC_order:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011961 C = new (Context) OMPOrderClause();
11962 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011963 case llvm::omp::OMPC_destroy:
Alexey Bataev375437a2020-03-02 14:21:20 -050011964 C = new (Context) OMPDestroyClause();
11965 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011966 case llvm::omp::OMPC_detach:
Alexey Bataev0f0564b2020-03-17 09:17:42 -040011967 C = new (Context) OMPDetachClause();
11968 break;
Alexey Bataevb5be1c52020-04-21 13:21:00 -040011969 case llvm::omp::OMPC_uses_allocators:
11970 C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
11971 break;
Alexey Bataev2e499ee2020-05-18 13:37:53 -040011972 case llvm::omp::OMPC_affinity:
11973 C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
11974 break;
Johannes Doerfert419a5592020-03-30 19:58:40 -050011975#define OMP_CLAUSE_NO_CLASS(Enum, Str) \
11976 case llvm::omp::Enum: \
11977 break;
11978#include "llvm/Frontend/OpenMP/OMPKinds.def"
Kelvin Libe286f52018-09-15 13:54:15 +000011979 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011980 assert(C && "Unknown OMPClause type");
11981
Kelvin Libe286f52018-09-15 13:54:15 +000011982 Visit(C);
11983 C->setLocStart(Record.readSourceLocation());
11984 C->setLocEnd(Record.readSourceLocation());
11985
11986 return C;
11987}
11988
11989void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11990 C->setPreInitStmt(Record.readSubStmt(),
11991 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11992}
11993
11994void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11995 VisitOMPClauseWithPreInit(C);
11996 C->setPostUpdateExpr(Record.readSubExpr());
11997}
11998
11999void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12000 VisitOMPClauseWithPreInit(C);
12001 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12002 C->setNameModifierLoc(Record.readSourceLocation());
12003 C->setColonLoc(Record.readSourceLocation());
12004 C->setCondition(Record.readSubExpr());
12005 C->setLParenLoc(Record.readSourceLocation());
12006}
12007
12008void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +000012009 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012010 C->setCondition(Record.readSubExpr());
12011 C->setLParenLoc(Record.readSourceLocation());
12012}
12013
12014void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12015 VisitOMPClauseWithPreInit(C);
12016 C->setNumThreads(Record.readSubExpr());
12017 C->setLParenLoc(Record.readSourceLocation());
12018}
12019
12020void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12021 C->setSafelen(Record.readSubExpr());
12022 C->setLParenLoc(Record.readSourceLocation());
12023}
12024
12025void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12026 C->setSimdlen(Record.readSubExpr());
12027 C->setLParenLoc(Record.readSourceLocation());
12028}
12029
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012030void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12031 C->setAllocator(Record.readExpr());
12032 C->setLParenLoc(Record.readSourceLocation());
12033}
12034
Kelvin Libe286f52018-09-15 13:54:15 +000012035void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12036 C->setNumForLoops(Record.readSubExpr());
12037 C->setLParenLoc(Record.readSourceLocation());
12038}
12039
12040void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
Atmn Patel577c9b02020-02-14 21:45:49 -060012041 C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
Kelvin Libe286f52018-09-15 13:54:15 +000012042 C->setLParenLoc(Record.readSourceLocation());
12043 C->setDefaultKindKwLoc(Record.readSourceLocation());
12044}
12045
12046void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012047 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
Kelvin Libe286f52018-09-15 13:54:15 +000012048 C->setLParenLoc(Record.readSourceLocation());
12049 C->setProcBindKindKwLoc(Record.readSourceLocation());
12050}
12051
12052void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12053 VisitOMPClauseWithPreInit(C);
12054 C->setScheduleKind(
12055 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12056 C->setFirstScheduleModifier(
12057 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12058 C->setSecondScheduleModifier(
12059 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12060 C->setChunkSize(Record.readSubExpr());
12061 C->setLParenLoc(Record.readSourceLocation());
12062 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12063 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12064 C->setScheduleKindLoc(Record.readSourceLocation());
12065 C->setCommaLoc(Record.readSourceLocation());
12066}
12067
12068void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12069 C->setNumForLoops(Record.readSubExpr());
12070 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12071 C->setLoopNumIterations(I, Record.readSubExpr());
12072 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12073 C->setLoopCounter(I, Record.readSubExpr());
12074 C->setLParenLoc(Record.readSourceLocation());
12075}
12076
Alexey Bataev0f0564b2020-03-17 09:17:42 -040012077void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
12078 C->setEventHandler(Record.readSubExpr());
12079 C->setLParenLoc(Record.readSourceLocation());
12080}
12081
Kelvin Libe286f52018-09-15 13:54:15 +000012082void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12083
12084void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12085
12086void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12087
12088void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12089
12090void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12091
Alexey Bataev82f7c202020-03-03 13:22:35 -050012092void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
12093 if (C->isExtended()) {
12094 C->setLParenLoc(Record.readSourceLocation());
12095 C->setArgumentLoc(Record.readSourceLocation());
12096 C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
12097 }
12098}
Kelvin Libe286f52018-09-15 13:54:15 +000012099
12100void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12101
12102void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12103
Alexey Bataevea9166b2020-02-06 16:30:23 -050012104void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
12105
Alexey Bataev04a830f2020-02-10 14:30:39 -050012106void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
12107
Alexey Bataev95598342020-02-10 15:49:05 -050012108void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
12109
Alexey Bataev9a8defc2020-02-11 11:10:43 -050012110void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
12111
Kelvin Libe286f52018-09-15 13:54:15 +000012112void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12113
12114void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12115
12116void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12117
Alexey Bataev375437a2020-03-02 14:21:20 -050012118void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *) {}
12119
Kelvin Li1408f912018-09-26 04:28:39 +000012120void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12121
Patrick Lyster4a370b92018-10-01 13:47:43 +000012122void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12123 OMPUnifiedSharedMemoryClause *) {}
12124
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012125void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12126
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012127void
12128OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12129}
12130
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012131void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12132 OMPAtomicDefaultMemOrderClause *C) {
12133 C->setAtomicDefaultMemOrderKind(
12134 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12135 C->setLParenLoc(Record.readSourceLocation());
12136 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12137}
12138
Kelvin Libe286f52018-09-15 13:54:15 +000012139void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12140 C->setLParenLoc(Record.readSourceLocation());
12141 unsigned NumVars = C->varlist_size();
12142 SmallVector<Expr *, 16> Vars;
12143 Vars.reserve(NumVars);
12144 for (unsigned i = 0; i != NumVars; ++i)
12145 Vars.push_back(Record.readSubExpr());
12146 C->setVarRefs(Vars);
12147 Vars.clear();
12148 for (unsigned i = 0; i != NumVars; ++i)
12149 Vars.push_back(Record.readSubExpr());
12150 C->setPrivateCopies(Vars);
12151}
12152
12153void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12154 VisitOMPClauseWithPreInit(C);
12155 C->setLParenLoc(Record.readSourceLocation());
12156 unsigned NumVars = C->varlist_size();
12157 SmallVector<Expr *, 16> Vars;
12158 Vars.reserve(NumVars);
12159 for (unsigned i = 0; i != NumVars; ++i)
12160 Vars.push_back(Record.readSubExpr());
12161 C->setVarRefs(Vars);
12162 Vars.clear();
12163 for (unsigned i = 0; i != NumVars; ++i)
12164 Vars.push_back(Record.readSubExpr());
12165 C->setPrivateCopies(Vars);
12166 Vars.clear();
12167 for (unsigned i = 0; i != NumVars; ++i)
12168 Vars.push_back(Record.readSubExpr());
12169 C->setInits(Vars);
12170}
12171
12172void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12173 VisitOMPClauseWithPostUpdate(C);
12174 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012175 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
12176 C->setKindLoc(Record.readSourceLocation());
12177 C->setColonLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000012178 unsigned NumVars = C->varlist_size();
12179 SmallVector<Expr *, 16> Vars;
12180 Vars.reserve(NumVars);
12181 for (unsigned i = 0; i != NumVars; ++i)
12182 Vars.push_back(Record.readSubExpr());
12183 C->setVarRefs(Vars);
12184 Vars.clear();
12185 for (unsigned i = 0; i != NumVars; ++i)
12186 Vars.push_back(Record.readSubExpr());
12187 C->setPrivateCopies(Vars);
12188 Vars.clear();
12189 for (unsigned i = 0; i != NumVars; ++i)
12190 Vars.push_back(Record.readSubExpr());
12191 C->setSourceExprs(Vars);
12192 Vars.clear();
12193 for (unsigned i = 0; i != NumVars; ++i)
12194 Vars.push_back(Record.readSubExpr());
12195 C->setDestinationExprs(Vars);
12196 Vars.clear();
12197 for (unsigned i = 0; i != NumVars; ++i)
12198 Vars.push_back(Record.readSubExpr());
12199 C->setAssignmentOps(Vars);
12200}
12201
12202void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12203 C->setLParenLoc(Record.readSourceLocation());
12204 unsigned NumVars = C->varlist_size();
12205 SmallVector<Expr *, 16> Vars;
12206 Vars.reserve(NumVars);
12207 for (unsigned i = 0; i != NumVars; ++i)
12208 Vars.push_back(Record.readSubExpr());
12209 C->setVarRefs(Vars);
12210}
12211
12212void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12213 VisitOMPClauseWithPostUpdate(C);
12214 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev1236eb62020-03-23 17:30:38 -040012215 C->setModifierLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000012216 C->setColonLoc(Record.readSourceLocation());
12217 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012218 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012219 C->setQualifierLoc(NNSL);
12220 C->setNameInfo(DNI);
12221
12222 unsigned NumVars = C->varlist_size();
12223 SmallVector<Expr *, 16> Vars;
12224 Vars.reserve(NumVars);
12225 for (unsigned i = 0; i != NumVars; ++i)
12226 Vars.push_back(Record.readSubExpr());
12227 C->setVarRefs(Vars);
12228 Vars.clear();
12229 for (unsigned i = 0; i != NumVars; ++i)
12230 Vars.push_back(Record.readSubExpr());
12231 C->setPrivates(Vars);
12232 Vars.clear();
12233 for (unsigned i = 0; i != NumVars; ++i)
12234 Vars.push_back(Record.readSubExpr());
12235 C->setLHSExprs(Vars);
12236 Vars.clear();
12237 for (unsigned i = 0; i != NumVars; ++i)
12238 Vars.push_back(Record.readSubExpr());
12239 C->setRHSExprs(Vars);
12240 Vars.clear();
12241 for (unsigned i = 0; i != NumVars; ++i)
12242 Vars.push_back(Record.readSubExpr());
12243 C->setReductionOps(Vars);
Alexey Bataevbd1c03d2020-05-04 16:19:31 -040012244 if (C->getModifier() == OMPC_REDUCTION_inscan) {
12245 Vars.clear();
12246 for (unsigned i = 0; i != NumVars; ++i)
12247 Vars.push_back(Record.readSubExpr());
12248 C->setInscanCopyOps(Vars);
12249 Vars.clear();
12250 for (unsigned i = 0; i != NumVars; ++i)
12251 Vars.push_back(Record.readSubExpr());
12252 C->setInscanCopyArrayTemps(Vars);
12253 Vars.clear();
12254 for (unsigned i = 0; i != NumVars; ++i)
12255 Vars.push_back(Record.readSubExpr());
12256 C->setInscanCopyArrayElems(Vars);
12257 }
Kelvin Libe286f52018-09-15 13:54:15 +000012258}
12259
12260void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12261 VisitOMPClauseWithPostUpdate(C);
12262 C->setLParenLoc(Record.readSourceLocation());
12263 C->setColonLoc(Record.readSourceLocation());
12264 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012265 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012266 C->setQualifierLoc(NNSL);
12267 C->setNameInfo(DNI);
12268
12269 unsigned NumVars = C->varlist_size();
12270 SmallVector<Expr *, 16> Vars;
12271 Vars.reserve(NumVars);
12272 for (unsigned I = 0; I != NumVars; ++I)
12273 Vars.push_back(Record.readSubExpr());
12274 C->setVarRefs(Vars);
12275 Vars.clear();
12276 for (unsigned I = 0; I != NumVars; ++I)
12277 Vars.push_back(Record.readSubExpr());
12278 C->setPrivates(Vars);
12279 Vars.clear();
12280 for (unsigned I = 0; I != NumVars; ++I)
12281 Vars.push_back(Record.readSubExpr());
12282 C->setLHSExprs(Vars);
12283 Vars.clear();
12284 for (unsigned I = 0; I != NumVars; ++I)
12285 Vars.push_back(Record.readSubExpr());
12286 C->setRHSExprs(Vars);
12287 Vars.clear();
12288 for (unsigned I = 0; I != NumVars; ++I)
12289 Vars.push_back(Record.readSubExpr());
12290 C->setReductionOps(Vars);
12291}
12292
12293void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12294 VisitOMPClauseWithPostUpdate(C);
12295 C->setLParenLoc(Record.readSourceLocation());
12296 C->setColonLoc(Record.readSourceLocation());
12297 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012298 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012299 C->setQualifierLoc(NNSL);
12300 C->setNameInfo(DNI);
12301
12302 unsigned NumVars = C->varlist_size();
12303 SmallVector<Expr *, 16> Vars;
12304 Vars.reserve(NumVars);
12305 for (unsigned I = 0; I != NumVars; ++I)
12306 Vars.push_back(Record.readSubExpr());
12307 C->setVarRefs(Vars);
12308 Vars.clear();
12309 for (unsigned I = 0; I != NumVars; ++I)
12310 Vars.push_back(Record.readSubExpr());
12311 C->setPrivates(Vars);
12312 Vars.clear();
12313 for (unsigned I = 0; I != NumVars; ++I)
12314 Vars.push_back(Record.readSubExpr());
12315 C->setLHSExprs(Vars);
12316 Vars.clear();
12317 for (unsigned I = 0; I != NumVars; ++I)
12318 Vars.push_back(Record.readSubExpr());
12319 C->setRHSExprs(Vars);
12320 Vars.clear();
12321 for (unsigned I = 0; I != NumVars; ++I)
12322 Vars.push_back(Record.readSubExpr());
12323 C->setReductionOps(Vars);
12324 Vars.clear();
12325 for (unsigned I = 0; I != NumVars; ++I)
12326 Vars.push_back(Record.readSubExpr());
12327 C->setTaskgroupDescriptors(Vars);
12328}
12329
12330void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12331 VisitOMPClauseWithPostUpdate(C);
12332 C->setLParenLoc(Record.readSourceLocation());
12333 C->setColonLoc(Record.readSourceLocation());
12334 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12335 C->setModifierLoc(Record.readSourceLocation());
12336 unsigned NumVars = C->varlist_size();
12337 SmallVector<Expr *, 16> Vars;
12338 Vars.reserve(NumVars);
12339 for (unsigned i = 0; i != NumVars; ++i)
12340 Vars.push_back(Record.readSubExpr());
12341 C->setVarRefs(Vars);
12342 Vars.clear();
12343 for (unsigned i = 0; i != NumVars; ++i)
12344 Vars.push_back(Record.readSubExpr());
12345 C->setPrivates(Vars);
12346 Vars.clear();
12347 for (unsigned i = 0; i != NumVars; ++i)
12348 Vars.push_back(Record.readSubExpr());
12349 C->setInits(Vars);
12350 Vars.clear();
12351 for (unsigned i = 0; i != NumVars; ++i)
12352 Vars.push_back(Record.readSubExpr());
12353 C->setUpdates(Vars);
12354 Vars.clear();
12355 for (unsigned i = 0; i != NumVars; ++i)
12356 Vars.push_back(Record.readSubExpr());
12357 C->setFinals(Vars);
12358 C->setStep(Record.readSubExpr());
12359 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012360 Vars.clear();
12361 for (unsigned I = 0; I != NumVars + 1; ++I)
12362 Vars.push_back(Record.readSubExpr());
12363 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012364}
12365
12366void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12367 C->setLParenLoc(Record.readSourceLocation());
12368 C->setColonLoc(Record.readSourceLocation());
12369 unsigned NumVars = C->varlist_size();
12370 SmallVector<Expr *, 16> Vars;
12371 Vars.reserve(NumVars);
12372 for (unsigned i = 0; i != NumVars; ++i)
12373 Vars.push_back(Record.readSubExpr());
12374 C->setVarRefs(Vars);
12375 C->setAlignment(Record.readSubExpr());
12376}
12377
12378void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12379 C->setLParenLoc(Record.readSourceLocation());
12380 unsigned NumVars = C->varlist_size();
12381 SmallVector<Expr *, 16> Exprs;
12382 Exprs.reserve(NumVars);
12383 for (unsigned i = 0; i != NumVars; ++i)
12384 Exprs.push_back(Record.readSubExpr());
12385 C->setVarRefs(Exprs);
12386 Exprs.clear();
12387 for (unsigned i = 0; i != NumVars; ++i)
12388 Exprs.push_back(Record.readSubExpr());
12389 C->setSourceExprs(Exprs);
12390 Exprs.clear();
12391 for (unsigned i = 0; i != NumVars; ++i)
12392 Exprs.push_back(Record.readSubExpr());
12393 C->setDestinationExprs(Exprs);
12394 Exprs.clear();
12395 for (unsigned i = 0; i != NumVars; ++i)
12396 Exprs.push_back(Record.readSubExpr());
12397 C->setAssignmentOps(Exprs);
12398}
12399
12400void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12401 C->setLParenLoc(Record.readSourceLocation());
12402 unsigned NumVars = C->varlist_size();
12403 SmallVector<Expr *, 16> Exprs;
12404 Exprs.reserve(NumVars);
12405 for (unsigned i = 0; i != NumVars; ++i)
12406 Exprs.push_back(Record.readSubExpr());
12407 C->setVarRefs(Exprs);
12408 Exprs.clear();
12409 for (unsigned i = 0; i != NumVars; ++i)
12410 Exprs.push_back(Record.readSubExpr());
12411 C->setSourceExprs(Exprs);
12412 Exprs.clear();
12413 for (unsigned i = 0; i != NumVars; ++i)
12414 Exprs.push_back(Record.readSubExpr());
12415 C->setDestinationExprs(Exprs);
12416 Exprs.clear();
12417 for (unsigned i = 0; i != NumVars; ++i)
12418 Exprs.push_back(Record.readSubExpr());
12419 C->setAssignmentOps(Exprs);
12420}
12421
12422void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12423 C->setLParenLoc(Record.readSourceLocation());
12424 unsigned NumVars = C->varlist_size();
12425 SmallVector<Expr *, 16> Vars;
12426 Vars.reserve(NumVars);
12427 for (unsigned i = 0; i != NumVars; ++i)
12428 Vars.push_back(Record.readSubExpr());
12429 C->setVarRefs(Vars);
12430}
12431
Alexey Bataevc112e942020-02-28 09:52:15 -050012432void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
12433 C->setDepobj(Record.readSubExpr());
12434 C->setLParenLoc(Record.readSourceLocation());
12435}
12436
Kelvin Libe286f52018-09-15 13:54:15 +000012437void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12438 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev13a15042020-04-01 15:06:38 -040012439 C->setModifier(Record.readSubExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012440 C->setDependencyKind(
12441 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12442 C->setDependencyLoc(Record.readSourceLocation());
12443 C->setColonLoc(Record.readSourceLocation());
12444 unsigned NumVars = C->varlist_size();
12445 SmallVector<Expr *, 16> Vars;
12446 Vars.reserve(NumVars);
12447 for (unsigned I = 0; I != NumVars; ++I)
12448 Vars.push_back(Record.readSubExpr());
12449 C->setVarRefs(Vars);
12450 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12451 C->setLoopData(I, Record.readSubExpr());
12452}
12453
12454void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12455 VisitOMPClauseWithPreInit(C);
Alexey Bataev2f8894a2020-03-18 15:01:15 -040012456 C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
Kelvin Libe286f52018-09-15 13:54:15 +000012457 C->setDevice(Record.readSubExpr());
Alexey Bataev2f8894a2020-03-18 15:01:15 -040012458 C->setModifierLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000012459 C->setLParenLoc(Record.readSourceLocation());
12460}
12461
12462void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12463 C->setLParenLoc(Record.readSourceLocation());
Reid Klecknerba1ffd22020-04-03 12:35:30 -070012464 for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
Kelvin Lief579432018-12-18 22:18:41 +000012465 C->setMapTypeModifier(
12466 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12467 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12468 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012469 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012470 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012471 C->setMapType(
12472 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12473 C->setMapLoc(Record.readSourceLocation());
12474 C->setColonLoc(Record.readSourceLocation());
12475 auto NumVars = C->varlist_size();
12476 auto UniqueDecls = C->getUniqueDeclarationsNum();
12477 auto TotalLists = C->getTotalComponentListNum();
12478 auto TotalComponents = C->getTotalComponentsNum();
12479
12480 SmallVector<Expr *, 16> Vars;
12481 Vars.reserve(NumVars);
12482 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012483 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012484 C->setVarRefs(Vars);
12485
Michael Kruse4304e9d2019-02-19 16:38:20 +000012486 SmallVector<Expr *, 16> UDMappers;
12487 UDMappers.reserve(NumVars);
12488 for (unsigned I = 0; I < NumVars; ++I)
12489 UDMappers.push_back(Record.readExpr());
12490 C->setUDMapperRefs(UDMappers);
12491
Kelvin Libe286f52018-09-15 13:54:15 +000012492 SmallVector<ValueDecl *, 16> Decls;
12493 Decls.reserve(UniqueDecls);
12494 for (unsigned i = 0; i < UniqueDecls; ++i)
12495 Decls.push_back(Record.readDeclAs<ValueDecl>());
12496 C->setUniqueDecls(Decls);
12497
12498 SmallVector<unsigned, 16> ListsPerDecl;
12499 ListsPerDecl.reserve(UniqueDecls);
12500 for (unsigned i = 0; i < UniqueDecls; ++i)
12501 ListsPerDecl.push_back(Record.readInt());
12502 C->setDeclNumLists(ListsPerDecl);
12503
12504 SmallVector<unsigned, 32> ListSizes;
12505 ListSizes.reserve(TotalLists);
12506 for (unsigned i = 0; i < TotalLists; ++i)
12507 ListSizes.push_back(Record.readInt());
12508 C->setComponentListSizes(ListSizes);
12509
12510 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12511 Components.reserve(TotalComponents);
12512 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012513 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012514 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12515 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12516 AssociatedExpr, AssociatedDecl));
12517 }
12518 C->setComponents(Components, ListSizes);
12519}
12520
Alexey Bataeve04483e2019-03-27 14:14:31 +000012521void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12522 C->setLParenLoc(Record.readSourceLocation());
12523 C->setColonLoc(Record.readSourceLocation());
12524 C->setAllocator(Record.readSubExpr());
12525 unsigned NumVars = C->varlist_size();
12526 SmallVector<Expr *, 16> Vars;
12527 Vars.reserve(NumVars);
12528 for (unsigned i = 0; i != NumVars; ++i)
12529 Vars.push_back(Record.readSubExpr());
12530 C->setVarRefs(Vars);
12531}
12532
Kelvin Libe286f52018-09-15 13:54:15 +000012533void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12534 VisitOMPClauseWithPreInit(C);
12535 C->setNumTeams(Record.readSubExpr());
12536 C->setLParenLoc(Record.readSourceLocation());
12537}
12538
12539void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12540 VisitOMPClauseWithPreInit(C);
12541 C->setThreadLimit(Record.readSubExpr());
12542 C->setLParenLoc(Record.readSourceLocation());
12543}
12544
12545void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +000012546 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012547 C->setPriority(Record.readSubExpr());
12548 C->setLParenLoc(Record.readSourceLocation());
12549}
12550
12551void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +000012552 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012553 C->setGrainsize(Record.readSubExpr());
12554 C->setLParenLoc(Record.readSourceLocation());
12555}
12556
12557void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +000012558 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012559 C->setNumTasks(Record.readSubExpr());
12560 C->setLParenLoc(Record.readSourceLocation());
12561}
12562
12563void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12564 C->setHint(Record.readSubExpr());
12565 C->setLParenLoc(Record.readSourceLocation());
12566}
12567
12568void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12569 VisitOMPClauseWithPreInit(C);
12570 C->setDistScheduleKind(
12571 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12572 C->setChunkSize(Record.readSubExpr());
12573 C->setLParenLoc(Record.readSourceLocation());
12574 C->setDistScheduleKindLoc(Record.readSourceLocation());
12575 C->setCommaLoc(Record.readSourceLocation());
12576}
12577
12578void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12579 C->setDefaultmapKind(
12580 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12581 C->setDefaultmapModifier(
12582 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12583 C->setLParenLoc(Record.readSourceLocation());
12584 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12585 C->setDefaultmapKindLoc(Record.readSourceLocation());
12586}
12587
12588void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12589 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012590 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012591 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012592 auto NumVars = C->varlist_size();
12593 auto UniqueDecls = C->getUniqueDeclarationsNum();
12594 auto TotalLists = C->getTotalComponentListNum();
12595 auto TotalComponents = C->getTotalComponentsNum();
12596
12597 SmallVector<Expr *, 16> Vars;
12598 Vars.reserve(NumVars);
12599 for (unsigned i = 0; i != NumVars; ++i)
12600 Vars.push_back(Record.readSubExpr());
12601 C->setVarRefs(Vars);
12602
Michael Kruse01f670d2019-02-22 22:29:42 +000012603 SmallVector<Expr *, 16> UDMappers;
12604 UDMappers.reserve(NumVars);
12605 for (unsigned I = 0; I < NumVars; ++I)
12606 UDMappers.push_back(Record.readSubExpr());
12607 C->setUDMapperRefs(UDMappers);
12608
Kelvin Libe286f52018-09-15 13:54:15 +000012609 SmallVector<ValueDecl *, 16> Decls;
12610 Decls.reserve(UniqueDecls);
12611 for (unsigned i = 0; i < UniqueDecls; ++i)
12612 Decls.push_back(Record.readDeclAs<ValueDecl>());
12613 C->setUniqueDecls(Decls);
12614
12615 SmallVector<unsigned, 16> ListsPerDecl;
12616 ListsPerDecl.reserve(UniqueDecls);
12617 for (unsigned i = 0; i < UniqueDecls; ++i)
12618 ListsPerDecl.push_back(Record.readInt());
12619 C->setDeclNumLists(ListsPerDecl);
12620
12621 SmallVector<unsigned, 32> ListSizes;
12622 ListSizes.reserve(TotalLists);
12623 for (unsigned i = 0; i < TotalLists; ++i)
12624 ListSizes.push_back(Record.readInt());
12625 C->setComponentListSizes(ListSizes);
12626
12627 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12628 Components.reserve(TotalComponents);
12629 for (unsigned i = 0; i < TotalComponents; ++i) {
12630 Expr *AssociatedExpr = Record.readSubExpr();
12631 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12632 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12633 AssociatedExpr, AssociatedDecl));
12634 }
12635 C->setComponents(Components, ListSizes);
12636}
12637
12638void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12639 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000012640 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012641 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012642 auto NumVars = C->varlist_size();
12643 auto UniqueDecls = C->getUniqueDeclarationsNum();
12644 auto TotalLists = C->getTotalComponentListNum();
12645 auto TotalComponents = C->getTotalComponentsNum();
12646
12647 SmallVector<Expr *, 16> Vars;
12648 Vars.reserve(NumVars);
12649 for (unsigned i = 0; i != NumVars; ++i)
12650 Vars.push_back(Record.readSubExpr());
12651 C->setVarRefs(Vars);
12652
Michael Kruse0336c752019-02-25 20:34:15 +000012653 SmallVector<Expr *, 16> UDMappers;
12654 UDMappers.reserve(NumVars);
12655 for (unsigned I = 0; I < NumVars; ++I)
12656 UDMappers.push_back(Record.readSubExpr());
12657 C->setUDMapperRefs(UDMappers);
12658
Kelvin Libe286f52018-09-15 13:54:15 +000012659 SmallVector<ValueDecl *, 16> Decls;
12660 Decls.reserve(UniqueDecls);
12661 for (unsigned i = 0; i < UniqueDecls; ++i)
12662 Decls.push_back(Record.readDeclAs<ValueDecl>());
12663 C->setUniqueDecls(Decls);
12664
12665 SmallVector<unsigned, 16> ListsPerDecl;
12666 ListsPerDecl.reserve(UniqueDecls);
12667 for (unsigned i = 0; i < UniqueDecls; ++i)
12668 ListsPerDecl.push_back(Record.readInt());
12669 C->setDeclNumLists(ListsPerDecl);
12670
12671 SmallVector<unsigned, 32> ListSizes;
12672 ListSizes.reserve(TotalLists);
12673 for (unsigned i = 0; i < TotalLists; ++i)
12674 ListSizes.push_back(Record.readInt());
12675 C->setComponentListSizes(ListSizes);
12676
12677 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12678 Components.reserve(TotalComponents);
12679 for (unsigned i = 0; i < TotalComponents; ++i) {
12680 Expr *AssociatedExpr = Record.readSubExpr();
12681 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12682 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12683 AssociatedExpr, AssociatedDecl));
12684 }
12685 C->setComponents(Components, ListSizes);
12686}
12687
12688void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12689 C->setLParenLoc(Record.readSourceLocation());
12690 auto NumVars = C->varlist_size();
12691 auto UniqueDecls = C->getUniqueDeclarationsNum();
12692 auto TotalLists = C->getTotalComponentListNum();
12693 auto TotalComponents = C->getTotalComponentsNum();
12694
12695 SmallVector<Expr *, 16> Vars;
12696 Vars.reserve(NumVars);
12697 for (unsigned i = 0; i != NumVars; ++i)
12698 Vars.push_back(Record.readSubExpr());
12699 C->setVarRefs(Vars);
12700 Vars.clear();
12701 for (unsigned i = 0; i != NumVars; ++i)
12702 Vars.push_back(Record.readSubExpr());
12703 C->setPrivateCopies(Vars);
12704 Vars.clear();
12705 for (unsigned i = 0; i != NumVars; ++i)
12706 Vars.push_back(Record.readSubExpr());
12707 C->setInits(Vars);
12708
12709 SmallVector<ValueDecl *, 16> Decls;
12710 Decls.reserve(UniqueDecls);
12711 for (unsigned i = 0; i < UniqueDecls; ++i)
12712 Decls.push_back(Record.readDeclAs<ValueDecl>());
12713 C->setUniqueDecls(Decls);
12714
12715 SmallVector<unsigned, 16> ListsPerDecl;
12716 ListsPerDecl.reserve(UniqueDecls);
12717 for (unsigned i = 0; i < UniqueDecls; ++i)
12718 ListsPerDecl.push_back(Record.readInt());
12719 C->setDeclNumLists(ListsPerDecl);
12720
12721 SmallVector<unsigned, 32> ListSizes;
12722 ListSizes.reserve(TotalLists);
12723 for (unsigned i = 0; i < TotalLists; ++i)
12724 ListSizes.push_back(Record.readInt());
12725 C->setComponentListSizes(ListSizes);
12726
12727 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12728 Components.reserve(TotalComponents);
12729 for (unsigned i = 0; i < TotalComponents; ++i) {
12730 Expr *AssociatedExpr = Record.readSubExpr();
12731 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12732 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12733 AssociatedExpr, AssociatedDecl));
12734 }
12735 C->setComponents(Components, ListSizes);
12736}
12737
Alexey Bataeva888fc62020-05-21 08:30:23 -040012738void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
12739 C->setLParenLoc(Record.readSourceLocation());
12740 auto NumVars = C->varlist_size();
12741 auto UniqueDecls = C->getUniqueDeclarationsNum();
12742 auto TotalLists = C->getTotalComponentListNum();
12743 auto TotalComponents = C->getTotalComponentsNum();
12744
12745 SmallVector<Expr *, 16> Vars;
12746 Vars.reserve(NumVars);
12747 for (unsigned i = 0; i != NumVars; ++i)
12748 Vars.push_back(Record.readSubExpr());
12749 C->setVarRefs(Vars);
12750
12751 SmallVector<ValueDecl *, 16> Decls;
12752 Decls.reserve(UniqueDecls);
12753 for (unsigned i = 0; i < UniqueDecls; ++i)
12754 Decls.push_back(Record.readDeclAs<ValueDecl>());
12755 C->setUniqueDecls(Decls);
12756
12757 SmallVector<unsigned, 16> ListsPerDecl;
12758 ListsPerDecl.reserve(UniqueDecls);
12759 for (unsigned i = 0; i < UniqueDecls; ++i)
12760 ListsPerDecl.push_back(Record.readInt());
12761 C->setDeclNumLists(ListsPerDecl);
12762
12763 SmallVector<unsigned, 32> ListSizes;
12764 ListSizes.reserve(TotalLists);
12765 for (unsigned i = 0; i < TotalLists; ++i)
12766 ListSizes.push_back(Record.readInt());
12767 C->setComponentListSizes(ListSizes);
12768
12769 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12770 Components.reserve(TotalComponents);
12771 for (unsigned i = 0; i < TotalComponents; ++i) {
12772 Expr *AssociatedExpr = Record.readSubExpr();
12773 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12774 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12775 AssociatedExpr, AssociatedDecl));
12776 }
12777 C->setComponents(Components, ListSizes);
12778}
12779
Kelvin Libe286f52018-09-15 13:54:15 +000012780void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12781 C->setLParenLoc(Record.readSourceLocation());
12782 auto NumVars = C->varlist_size();
12783 auto UniqueDecls = C->getUniqueDeclarationsNum();
12784 auto TotalLists = C->getTotalComponentListNum();
12785 auto TotalComponents = C->getTotalComponentsNum();
12786
12787 SmallVector<Expr *, 16> Vars;
12788 Vars.reserve(NumVars);
12789 for (unsigned i = 0; i != NumVars; ++i)
12790 Vars.push_back(Record.readSubExpr());
12791 C->setVarRefs(Vars);
12792 Vars.clear();
12793
12794 SmallVector<ValueDecl *, 16> Decls;
12795 Decls.reserve(UniqueDecls);
12796 for (unsigned i = 0; i < UniqueDecls; ++i)
12797 Decls.push_back(Record.readDeclAs<ValueDecl>());
12798 C->setUniqueDecls(Decls);
12799
12800 SmallVector<unsigned, 16> ListsPerDecl;
12801 ListsPerDecl.reserve(UniqueDecls);
12802 for (unsigned i = 0; i < UniqueDecls; ++i)
12803 ListsPerDecl.push_back(Record.readInt());
12804 C->setDeclNumLists(ListsPerDecl);
12805
12806 SmallVector<unsigned, 32> ListSizes;
12807 ListSizes.reserve(TotalLists);
12808 for (unsigned i = 0; i < TotalLists; ++i)
12809 ListSizes.push_back(Record.readInt());
12810 C->setComponentListSizes(ListSizes);
12811
12812 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12813 Components.reserve(TotalComponents);
12814 for (unsigned i = 0; i < TotalComponents; ++i) {
12815 Expr *AssociatedExpr = Record.readSubExpr();
12816 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12817 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12818 AssociatedExpr, AssociatedDecl));
12819 }
12820 C->setComponents(Components, ListSizes);
12821}
Alexey Bataevb6e70842019-12-16 15:54:17 -050012822
12823void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12824 C->setLParenLoc(Record.readSourceLocation());
12825 unsigned NumVars = C->varlist_size();
12826 SmallVector<Expr *, 16> Vars;
12827 Vars.reserve(NumVars);
12828 for (unsigned i = 0; i != NumVars; ++i)
12829 Vars.push_back(Record.readSubExpr());
12830 C->setVarRefs(Vars);
Alexey Bataev0860db92019-12-19 10:01:10 -050012831 Vars.clear();
12832 Vars.reserve(NumVars);
12833 for (unsigned i = 0; i != NumVars; ++i)
12834 Vars.push_back(Record.readSubExpr());
12835 C->setPrivateRefs(Vars);
Alexey Bataevb6e70842019-12-16 15:54:17 -050012836}
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012837
Alexey Bataev06dea732020-03-20 09:41:22 -040012838void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
12839 C->setLParenLoc(Record.readSourceLocation());
12840 unsigned NumVars = C->varlist_size();
12841 SmallVector<Expr *, 16> Vars;
12842 Vars.reserve(NumVars);
12843 for (unsigned i = 0; i != NumVars; ++i)
12844 Vars.push_back(Record.readSubExpr());
12845 C->setVarRefs(Vars);
12846}
12847
Alexey Bataev63828a32020-03-23 10:41:08 -040012848void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
12849 C->setLParenLoc(Record.readSourceLocation());
12850 unsigned NumVars = C->varlist_size();
12851 SmallVector<Expr *, 16> Vars;
12852 Vars.reserve(NumVars);
12853 for (unsigned i = 0; i != NumVars; ++i)
12854 Vars.push_back(Record.readSubExpr());
12855 C->setVarRefs(Vars);
12856}
12857
Alexey Bataevb5be1c52020-04-21 13:21:00 -040012858void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
12859 C->setLParenLoc(Record.readSourceLocation());
12860 unsigned NumOfAllocators = C->getNumberOfAllocators();
12861 SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
12862 Data.reserve(NumOfAllocators);
12863 for (unsigned I = 0; I != NumOfAllocators; ++I) {
12864 OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
12865 D.Allocator = Record.readSubExpr();
12866 D.AllocatorTraits = Record.readSubExpr();
12867 D.LParenLoc = Record.readSourceLocation();
12868 D.RParenLoc = Record.readSourceLocation();
12869 }
12870 C->setAllocatorsData(Data);
12871}
12872
Alexey Bataev2e499ee2020-05-18 13:37:53 -040012873void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
12874 C->setLParenLoc(Record.readSourceLocation());
12875 C->setModifier(Record.readSubExpr());
12876 C->setColonLoc(Record.readSourceLocation());
12877 unsigned NumOfLocators = C->varlist_size();
12878 SmallVector<Expr *, 4> Locators;
12879 Locators.reserve(NumOfLocators);
12880 for (unsigned I = 0; I != NumOfLocators; ++I)
12881 Locators.push_back(Record.readSubExpr());
12882 C->setVarRefs(Locators);
12883}
12884
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012885void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12886 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12887 C->setLParenLoc(Record.readSourceLocation());
12888 C->setKindKwLoc(Record.readSourceLocation());
12889}
Johannes Doerfert1228d422019-12-19 20:42:12 -060012890
Johannes Doerfert55eca282020-03-13 23:42:05 -050012891OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
12892 OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
Johannes Doerfertb86bf832020-02-15 18:07:42 -060012893 TI.Sets.resize(readUInt32());
12894 for (auto &Set : TI.Sets) {
Johannes Doerfert1228d422019-12-19 20:42:12 -060012895 Set.Kind = readEnum<llvm::omp::TraitSet>();
12896 Set.Selectors.resize(readUInt32());
12897 for (auto &Selector : Set.Selectors) {
12898 Selector.Kind = readEnum<llvm::omp::TraitSelector>();
12899 Selector.ScoreOrCondition = nullptr;
12900 if (readBool())
12901 Selector.ScoreOrCondition = readExprRef();
12902 Selector.Properties.resize(readUInt32());
12903 for (auto &Property : Selector.Properties)
12904 Property.Kind = readEnum<llvm::omp::TraitProperty>();
12905 }
12906 }
Johannes Doerfert55eca282020-03-13 23:42:05 -050012907 return &TI;
Johannes Doerfert1228d422019-12-19 20:42:12 -060012908}