blob: 0921190e637d3b1ba295ee3b96b647a30dda1260 [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"
92#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000093#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000094#include "llvm/ADT/IntrusiveRefCntPtr.h"
95#include "llvm/ADT/None.h"
96#include "llvm/ADT/Optional.h"
97#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000098#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000099#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000100#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000101#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +0000102#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000103#include "llvm/ADT/StringMap.h"
104#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000105#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000106#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000107#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000108#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000109#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000110#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000111#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000112#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000113#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000114#include "llvm/Support/ErrorHandling.h"
115#include "llvm/Support/FileSystem.h"
116#include "llvm/Support/MemoryBuffer.h"
117#include "llvm/Support/Path.h"
118#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000119#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000120#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000121#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000122#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000123#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000124#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000125#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000126#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000127#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000128#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000129#include <limits>
130#include <map>
131#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000132#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000133#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000134#include <tuple>
135#include <utility>
136#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000137
138using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000139using namespace clang::serialization;
140using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000141using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000142
Ben Langmuircb69b572014-03-07 06:40:32 +0000143//===----------------------------------------------------------------------===//
144// ChainedASTReaderListener implementation
145//===----------------------------------------------------------------------===//
146
147bool
148ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
149 return First->ReadFullVersionInformation(FullVersion) ||
150 Second->ReadFullVersionInformation(FullVersion);
151}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000152
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000153void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
154 First->ReadModuleName(ModuleName);
155 Second->ReadModuleName(ModuleName);
156}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000157
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000158void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
159 First->ReadModuleMapFile(ModuleMapPath);
160 Second->ReadModuleMapFile(ModuleMapPath);
161}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000162
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000163bool
164ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
165 bool Complain,
166 bool AllowCompatibleDifferences) {
167 return First->ReadLanguageOptions(LangOpts, Complain,
168 AllowCompatibleDifferences) ||
169 Second->ReadLanguageOptions(LangOpts, Complain,
170 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000171}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000172
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000173bool ChainedASTReaderListener::ReadTargetOptions(
174 const TargetOptions &TargetOpts, bool Complain,
175 bool AllowCompatibleDifferences) {
176 return First->ReadTargetOptions(TargetOpts, Complain,
177 AllowCompatibleDifferences) ||
178 Second->ReadTargetOptions(TargetOpts, Complain,
179 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000180}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000181
Ben Langmuircb69b572014-03-07 06:40:32 +0000182bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000183 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000184 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
185 Second->ReadDiagnosticOptions(DiagOpts, Complain);
186}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000187
Ben Langmuircb69b572014-03-07 06:40:32 +0000188bool
189ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
190 bool Complain) {
191 return First->ReadFileSystemOptions(FSOpts, Complain) ||
192 Second->ReadFileSystemOptions(FSOpts, Complain);
193}
194
195bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000196 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
197 bool Complain) {
198 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
199 Complain) ||
200 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
201 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000202}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000203
Ben Langmuircb69b572014-03-07 06:40:32 +0000204bool ChainedASTReaderListener::ReadPreprocessorOptions(
205 const PreprocessorOptions &PPOpts, bool Complain,
206 std::string &SuggestedPredefines) {
207 return First->ReadPreprocessorOptions(PPOpts, Complain,
208 SuggestedPredefines) ||
209 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
210}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000211
Ben Langmuircb69b572014-03-07 06:40:32 +0000212void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
213 unsigned Value) {
214 First->ReadCounter(M, Value);
215 Second->ReadCounter(M, Value);
216}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000217
Ben Langmuircb69b572014-03-07 06:40:32 +0000218bool ChainedASTReaderListener::needsInputFileVisitation() {
219 return First->needsInputFileVisitation() ||
220 Second->needsInputFileVisitation();
221}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000222
Ben Langmuircb69b572014-03-07 06:40:32 +0000223bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
224 return First->needsSystemInputFileVisitation() ||
225 Second->needsSystemInputFileVisitation();
226}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000227
Richard Smith216a3bd2015-08-13 17:57:10 +0000228void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
229 ModuleKind Kind) {
230 First->visitModuleFile(Filename, Kind);
231 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000232}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000233
Ben Langmuircb69b572014-03-07 06:40:32 +0000234bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000235 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000236 bool isOverridden,
237 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000238 bool Continue = false;
239 if (First->needsInputFileVisitation() &&
240 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000241 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
242 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000243 if (Second->needsInputFileVisitation() &&
244 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000245 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
246 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000247 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000248}
249
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000250void ChainedASTReaderListener::readModuleFileExtension(
251 const ModuleFileExtensionMetadata &Metadata) {
252 First->readModuleFileExtension(Metadata);
253 Second->readModuleFileExtension(Metadata);
254}
255
Guy Benyei11169dd2012-12-18 14:30:41 +0000256//===----------------------------------------------------------------------===//
257// PCH validator implementation
258//===----------------------------------------------------------------------===//
259
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000260ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000263/// language options.
264///
265/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000266/// \param AllowCompatibleDifferences If true, differences between compatible
267/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000268///
269/// \returns true if the languagae options mis-match, false otherwise.
270static bool checkLanguageOptions(const LangOptions &LangOpts,
271 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000272 DiagnosticsEngine *Diags,
273 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000274#define LANGOPT(Name, Bits, Default, Description) \
275 if (ExistingLangOpts.Name != LangOpts.Name) { \
276 if (Diags) \
277 Diags->Report(diag::err_pch_langopt_mismatch) \
278 << Description << LangOpts.Name << ExistingLangOpts.Name; \
279 return true; \
280 }
281
282#define VALUE_LANGOPT(Name, Bits, Default, Description) \
283 if (ExistingLangOpts.Name != LangOpts.Name) { \
284 if (Diags) \
285 Diags->Report(diag::err_pch_langopt_value_mismatch) \
286 << Description; \
287 return true; \
288 }
289
290#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
291 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
292 if (Diags) \
293 Diags->Report(diag::err_pch_langopt_value_mismatch) \
294 << Description; \
295 return true; \
296 }
297
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000298#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
299 if (!AllowCompatibleDifferences) \
300 LANGOPT(Name, Bits, Default, Description)
301
302#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
303 if (!AllowCompatibleDifferences) \
304 ENUM_LANGOPT(Name, Bits, Default, Description)
305
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000306#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
307 if (!AllowCompatibleDifferences) \
308 VALUE_LANGOPT(Name, Bits, Default, Description)
309
Guy Benyei11169dd2012-12-18 14:30:41 +0000310#define BENIGN_LANGOPT(Name, Bits, Default, Description)
311#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000312#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000313#include "clang/Basic/LangOptions.def"
314
Ben Langmuircd98cb72015-06-23 18:20:18 +0000315 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
316 if (Diags)
317 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
318 return true;
319 }
320
Guy Benyei11169dd2012-12-18 14:30:41 +0000321 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
322 if (Diags)
323 Diags->Report(diag::err_pch_langopt_value_mismatch)
324 << "target Objective-C runtime";
325 return true;
326 }
327
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000328 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
329 LangOpts.CommentOpts.BlockCommandNames) {
330 if (Diags)
331 Diags->Report(diag::err_pch_langopt_value_mismatch)
332 << "block command names";
333 return true;
334 }
335
Vedant Kumar85a83c22017-06-01 20:01:01 +0000336 // Sanitizer feature mismatches are treated as compatible differences. If
337 // compatible differences aren't allowed, we still only want to check for
338 // mismatches of non-modular sanitizers (the only ones which can affect AST
339 // generation).
340 if (!AllowCompatibleDifferences) {
341 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
342 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
343 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
344 ExistingSanitizers.clear(ModularSanitizers);
345 ImportedSanitizers.clear(ModularSanitizers);
346 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
347 const std::string Flag = "-fsanitize=";
348 if (Diags) {
349#define SANITIZER(NAME, ID) \
350 { \
351 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
352 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
353 if (InExistingModule != InImportedModule) \
354 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
355 << InExistingModule << (Flag + NAME); \
356 }
357#include "clang/Basic/Sanitizers.def"
358 }
359 return true;
360 }
361 }
362
Guy Benyei11169dd2012-12-18 14:30:41 +0000363 return false;
364}
365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000367/// target options.
368///
369/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
370///
371/// \returns true if the target options mis-match, false otherwise.
372static bool checkTargetOptions(const TargetOptions &TargetOpts,
373 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000374 DiagnosticsEngine *Diags,
375 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000376#define CHECK_TARGET_OPT(Field, Name) \
377 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
378 if (Diags) \
379 Diags->Report(diag::err_pch_targetopt_mismatch) \
380 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
381 return true; \
382 }
383
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000384 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000385 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000387
388 // We can tolerate different CPUs in many cases, notably when one CPU
389 // supports a strict superset of another. When allowing compatible
390 // differences skip this check.
391 if (!AllowCompatibleDifferences)
392 CHECK_TARGET_OPT(CPU, "target CPU");
393
Guy Benyei11169dd2012-12-18 14:30:41 +0000394#undef CHECK_TARGET_OPT
395
396 // Compare feature sets.
397 SmallVector<StringRef, 4> ExistingFeatures(
398 ExistingTargetOpts.FeaturesAsWritten.begin(),
399 ExistingTargetOpts.FeaturesAsWritten.end());
400 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
401 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000402 llvm::sort(ExistingFeatures);
403 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000404
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000405 // We compute the set difference in both directions explicitly so that we can
406 // diagnose the differences differently.
407 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
408 std::set_difference(
409 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
410 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
411 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
412 ExistingFeatures.begin(), ExistingFeatures.end(),
413 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000414
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000415 // If we are allowing compatible differences and the read feature set is
416 // a strict subset of the existing feature set, there is nothing to diagnose.
417 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
418 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000419
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000420 if (Diags) {
421 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000422 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000423 << /* is-existing-feature */ false << Feature;
424 for (StringRef Feature : UnmatchedExistingFeatures)
425 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
426 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000427 }
428
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000429 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000430}
431
432bool
433PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000434 bool Complain,
435 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000436 const LangOptions &ExistingLangOpts = PP.getLangOpts();
437 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000438 Complain ? &Reader.Diags : nullptr,
439 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000440}
441
442bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000443 bool Complain,
444 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000445 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
446 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000447 Complain ? &Reader.Diags : nullptr,
448 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000449}
450
451namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000452
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000453using MacroDefinitionsMap =
454 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
455using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000456
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000457} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000458
Ben Langmuirb92de022014-04-29 16:25:26 +0000459static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
460 DiagnosticsEngine &Diags,
461 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000462 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000463
464 // Check current mappings for new -Werror mappings, and the stored mappings
465 // for cases that were explicitly mapped to *not* be errors that are now
466 // errors because of options like -Werror.
467 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
468
Vedant Kumar48b4f762018-04-14 01:40:48 +0000469 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000470 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
471 diag::kind DiagID = DiagIDMappingPair.first;
472 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
473 if (CurLevel < DiagnosticsEngine::Error)
474 continue; // not significant
475 Level StoredLevel =
476 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
477 if (StoredLevel < DiagnosticsEngine::Error) {
478 if (Complain)
479 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
480 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
481 return true;
482 }
483 }
484 }
485
486 return false;
487}
488
Alp Tokerac4e8e52014-06-22 21:58:33 +0000489static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
490 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
491 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
492 return true;
493 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000494}
495
496static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
497 DiagnosticsEngine &Diags,
498 bool IsSystem, bool Complain) {
499 // Top-level options
500 if (IsSystem) {
501 if (Diags.getSuppressSystemWarnings())
502 return false;
503 // If -Wsystem-headers was not enabled before, be conservative
504 if (StoredDiags.getSuppressSystemWarnings()) {
505 if (Complain)
506 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
507 return true;
508 }
509 }
510
511 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
512 if (Complain)
513 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
514 return true;
515 }
516
517 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
518 !StoredDiags.getEnableAllWarnings()) {
519 if (Complain)
520 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
521 return true;
522 }
523
524 if (isExtHandlingFromDiagsError(Diags) &&
525 !isExtHandlingFromDiagsError(StoredDiags)) {
526 if (Complain)
527 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
528 return true;
529 }
530
531 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
532}
533
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000534/// Return the top import module if it is implicit, nullptr otherwise.
535static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
536 Preprocessor &PP) {
537 // If the original import came from a file explicitly generated by the user,
538 // don't check the diagnostic mappings.
539 // FIXME: currently this is approximated by checking whether this is not a
540 // module import of an implicitly-loaded module file.
541 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
542 // the transitive closure of its imports, since unrelated modules cannot be
543 // imported until after this module finishes validation.
544 ModuleFile *TopImport = &*ModuleMgr.rbegin();
545 while (!TopImport->ImportedBy.empty())
546 TopImport = TopImport->ImportedBy[0];
547 if (TopImport->Kind != MK_ImplicitModule)
548 return nullptr;
549
550 StringRef ModuleName = TopImport->ModuleName;
551 assert(!ModuleName.empty() && "diagnostic options read before module name");
552
553 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
554 assert(M && "missing module");
555 return M;
556}
557
Ben Langmuirb92de022014-04-29 16:25:26 +0000558bool PCHValidator::ReadDiagnosticOptions(
559 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
560 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
561 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
562 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000563 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000564 // This should never fail, because we would have processed these options
565 // before writing them to an ASTFile.
566 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
567
568 ModuleManager &ModuleMgr = Reader.getModuleManager();
569 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
570
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000571 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
572 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000573 return false;
574
Ben Langmuirb92de022014-04-29 16:25:26 +0000575 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
576 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000577 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
578 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000579}
580
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000581/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000582/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000583static void
584collectMacroDefinitions(const PreprocessorOptions &PPOpts,
585 MacroDefinitionsMap &Macros,
586 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000587 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
588 StringRef Macro = PPOpts.Macros[I].first;
589 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000590
591 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
592 StringRef MacroName = MacroPair.first;
593 StringRef MacroBody = MacroPair.second;
594
595 // For an #undef'd macro, we only care about the name.
596 if (IsUndef) {
597 if (MacroNames && !Macros.count(MacroName))
598 MacroNames->push_back(MacroName);
599
600 Macros[MacroName] = std::make_pair("", true);
601 continue;
602 }
603
604 // For a #define'd macro, figure out the actual definition.
605 if (MacroName.size() == Macro.size())
606 MacroBody = "1";
607 else {
608 // Note: GCC drops anything following an end-of-line character.
609 StringRef::size_type End = MacroBody.find_first_of("\n\r");
610 MacroBody = MacroBody.substr(0, End);
611 }
612
613 if (MacroNames && !Macros.count(MacroName))
614 MacroNames->push_back(MacroName);
615 Macros[MacroName] = std::make_pair(MacroBody, false);
616 }
617}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000619/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000620/// against the preprocessor options in an existing preprocessor.
621///
622/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000623/// \param Validate If true, validate preprocessor options. If false, allow
624/// macros defined by \p ExistingPPOpts to override those defined by
625/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000626static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
627 const PreprocessorOptions &ExistingPPOpts,
628 DiagnosticsEngine *Diags,
629 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000630 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000631 const LangOptions &LangOpts,
632 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000633 // Check macro definitions.
634 MacroDefinitionsMap ASTFileMacros;
635 collectMacroDefinitions(PPOpts, ASTFileMacros);
636 MacroDefinitionsMap ExistingMacros;
637 SmallVector<StringRef, 4> ExistingMacroNames;
638 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
639
Vedant Kumar48b4f762018-04-14 01:40:48 +0000640 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000642 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000643 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
644
645 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000646 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
647 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000648 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000649 // FIXME: Check whether this identifier was referenced anywhere in the
650 // AST file. If so, we should reject the AST file. Unfortunately, this
651 // information isn't in the control block. What shall we do about it?
652
653 if (Existing.second) {
654 SuggestedPredefines += "#undef ";
655 SuggestedPredefines += MacroName.str();
656 SuggestedPredefines += '\n';
657 } else {
658 SuggestedPredefines += "#define ";
659 SuggestedPredefines += MacroName.str();
660 SuggestedPredefines += ' ';
661 SuggestedPredefines += Existing.first.str();
662 SuggestedPredefines += '\n';
663 }
664 continue;
665 }
666
667 // If the macro was defined in one but undef'd in the other, we have a
668 // conflict.
669 if (Existing.second != Known->second.second) {
670 if (Diags) {
671 Diags->Report(diag::err_pch_macro_def_undef)
672 << MacroName << Known->second.second;
673 }
674 return true;
675 }
676
677 // If the macro was #undef'd in both, or if the macro bodies are identical,
678 // it's fine.
679 if (Existing.second || Existing.first == Known->second.first)
680 continue;
681
682 // The macro bodies differ; complain.
683 if (Diags) {
684 Diags->Report(diag::err_pch_macro_def_conflict)
685 << MacroName << Known->second.first << Existing.first;
686 }
687 return true;
688 }
689
690 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000691 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000692 if (Diags) {
693 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
694 }
695 return true;
696 }
697
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000698 // Detailed record is important since it is used for the module cache hash.
699 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000700 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000701 if (Diags) {
702 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
703 }
704 return true;
705 }
706
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000708 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
709 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000710
711 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
712 !ExistingPPOpts.PCHThroughHeader.empty()) {
713 // In case the through header is an include, we must add all the includes
714 // to the predefines so the start point can be determined.
715 SuggestedPredefines += "#include \"";
716 SuggestedPredefines += File;
717 SuggestedPredefines += "\"\n";
718 continue;
719 }
720
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 if (File == ExistingPPOpts.ImplicitPCHInclude)
722 continue;
723
724 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
725 != PPOpts.Includes.end())
726 continue;
727
728 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000729 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 SuggestedPredefines += "\"\n";
731 }
732
Vedant Kumar48b4f762018-04-14 01:40:48 +0000733 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
734 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
736 File)
737 != PPOpts.MacroIncludes.end())
738 continue;
739
740 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000741 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 SuggestedPredefines += "\"\n##\n";
743 }
744
745 return false;
746}
747
748bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
749 bool Complain,
750 std::string &SuggestedPredefines) {
751 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
752
753 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000754 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000755 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000756 SuggestedPredefines,
757 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000758}
759
Yaxun Liu43712e02016-09-07 18:40:20 +0000760bool SimpleASTReaderListener::ReadPreprocessorOptions(
761 const PreprocessorOptions &PPOpts,
762 bool Complain,
763 std::string &SuggestedPredefines) {
764 return checkPreprocessorOptions(PPOpts,
765 PP.getPreprocessorOpts(),
766 nullptr,
767 PP.getFileManager(),
768 SuggestedPredefines,
769 PP.getLangOpts(),
770 false);
771}
772
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000773/// Check the header search options deserialized from the control block
774/// against the header search options in an existing preprocessor.
775///
776/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
777static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
778 StringRef SpecificModuleCachePath,
779 StringRef ExistingModuleCachePath,
780 DiagnosticsEngine *Diags,
781 const LangOptions &LangOpts) {
782 if (LangOpts.Modules) {
783 if (SpecificModuleCachePath != ExistingModuleCachePath) {
784 if (Diags)
785 Diags->Report(diag::err_pch_modulecache_mismatch)
786 << SpecificModuleCachePath << ExistingModuleCachePath;
787 return true;
788 }
789 }
790
791 return false;
792}
793
794bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
795 StringRef SpecificModuleCachePath,
796 bool Complain) {
797 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
798 PP.getHeaderSearchInfo().getModuleCachePath(),
799 Complain ? &Reader.Diags : nullptr,
800 PP.getLangOpts());
801}
802
Guy Benyei11169dd2012-12-18 14:30:41 +0000803void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
804 PP.setCounterValue(Value);
805}
806
807//===----------------------------------------------------------------------===//
808// AST reader implementation
809//===----------------------------------------------------------------------===//
810
Nico Weber824285e2014-05-08 04:26:47 +0000811void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
812 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000814 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000815}
816
Guy Benyei11169dd2012-12-18 14:30:41 +0000817unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
818 return serialization::ComputeHash(Sel);
819}
820
Guy Benyei11169dd2012-12-18 14:30:41 +0000821std::pair<unsigned, unsigned>
822ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000823 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000824
Justin Bogner57ba0b22014-03-28 22:03:24 +0000825 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
826 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000827 return std::make_pair(KeyLen, DataLen);
828}
829
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000830ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000831ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000833
Guy Benyei11169dd2012-12-18 14:30:41 +0000834 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000835 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
836 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
837 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000838 if (N == 0)
839 return SelTable.getNullarySelector(FirstII);
840 else if (N == 1)
841 return SelTable.getUnarySelector(FirstII);
842
843 SmallVector<IdentifierInfo *, 16> Args;
844 Args.push_back(FirstII);
845 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000846 Args.push_back(Reader.getLocalIdentifier(
847 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000848
849 return SelTable.getSelector(N, Args.data());
850}
851
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000852ASTSelectorLookupTrait::data_type
853ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000854 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000855 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000856
857 data_type Result;
858
Justin Bogner57ba0b22014-03-28 22:03:24 +0000859 Result.ID = Reader.getGlobalSelectorID(
860 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000861 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
862 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
863 Result.InstanceBits = FullInstanceBits & 0x3;
864 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
865 Result.FactoryBits = FullFactoryBits & 0x3;
866 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
867 unsigned NumInstanceMethods = FullInstanceBits >> 3;
868 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000869
870 // Load instance methods
871 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000872 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000873 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 Result.Instance.push_back(Method);
875 }
876
877 // Load factory methods
878 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000879 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000880 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 Result.Factory.push_back(Method);
882 }
883
884 return Result;
885}
886
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000887unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000888 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000889}
890
891std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000892ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000893 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000894
Justin Bogner57ba0b22014-03-28 22:03:24 +0000895 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
896 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 return std::make_pair(KeyLen, DataLen);
898}
899
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000900ASTIdentifierLookupTraitBase::internal_key_type
901ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000902 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000903 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000904}
905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000906/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000907static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
908 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000909 return II.hadMacroDefinition() ||
910 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000911 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000912 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000913 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000914 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000915}
916
Richard Smith76c2f2c2015-07-17 20:09:43 +0000917static bool readBit(unsigned &Bits) {
918 bool Value = Bits & 0x1;
919 Bits >>= 1;
920 return Value;
921}
922
Richard Smith79bf9202015-08-24 03:33:22 +0000923IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
924 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000925
Richard Smith79bf9202015-08-24 03:33:22 +0000926 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
927 return Reader.getGlobalIdentifierID(F, RawID >> 1);
928}
929
Richard Smitheb4b58f62016-02-05 01:40:54 +0000930static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
931 if (!II.isFromAST()) {
932 II.setIsFromAST();
933 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
934 if (isInterestingIdentifier(Reader, II, IsModule))
935 II.setChangedSinceDeserialization();
936 }
937}
938
Guy Benyei11169dd2012-12-18 14:30:41 +0000939IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
940 const unsigned char* d,
941 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000942 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000943
Justin Bogner57ba0b22014-03-28 22:03:24 +0000944 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 bool IsInteresting = RawID & 0x01;
946
947 // Wipe out the "is interesting" bit.
948 RawID = RawID >> 1;
949
Richard Smith76c2f2c2015-07-17 20:09:43 +0000950 // Build the IdentifierInfo and link the identifier ID with it.
951 IdentifierInfo *II = KnownII;
952 if (!II) {
953 II = &Reader.getIdentifierTable().getOwn(k);
954 KnownII = II;
955 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000956 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000957 Reader.markIdentifierUpToDate(II);
958
Guy Benyei11169dd2012-12-18 14:30:41 +0000959 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
960 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000961 // For uninteresting identifiers, there's nothing else to do. Just notify
962 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 return II;
965 }
966
Justin Bogner57ba0b22014-03-28 22:03:24 +0000967 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
968 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000969 bool CPlusPlusOperatorKeyword = readBit(Bits);
970 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000971 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000972 bool Poisoned = readBit(Bits);
973 bool ExtensionToken = readBit(Bits);
974 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000975
976 assert(Bits == 0 && "Extra bits in the identifier?");
977 DataLen -= 8;
978
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 // Set or check the various bits in the IdentifierInfo structure.
980 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000981 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000982 II->revertTokenIDToIdentifier();
983 if (!F.isModule())
984 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
985 else if (HasRevertedBuiltin && II->getBuiltinID()) {
986 II->revertBuiltin();
987 assert((II->hasRevertedBuiltin() ||
988 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
989 "Incorrect ObjC keyword or builtin ID");
990 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000991 assert(II->isExtensionToken() == ExtensionToken &&
992 "Incorrect extension token flag");
993 (void)ExtensionToken;
994 if (Poisoned)
995 II->setIsPoisoned(true);
996 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
997 "Incorrect C++ operator keyword flag");
998 (void)CPlusPlusOperatorKeyword;
999
1000 // If this identifier is a macro, deserialize the macro
1001 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +00001002 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001003 uint32_t MacroDirectivesOffset =
1004 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001005 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001006
Richard Smithd7329392015-04-21 21:46:32 +00001007 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001008 }
1009
1010 Reader.SetIdentifierInfo(ID, II);
1011
1012 // Read all of the declarations visible at global scope with this
1013 // name.
1014 if (DataLen > 0) {
1015 SmallVector<uint32_t, 4> DeclIDs;
1016 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001017 DeclIDs.push_back(Reader.getGlobalDeclID(
1018 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001019 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1020 }
1021
1022 return II;
1023}
1024
Richard Smitha06c7e62015-08-26 23:55:49 +00001025DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1026 : Kind(Name.getNameKind()) {
1027 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001029 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 break;
1031 case DeclarationName::ObjCZeroArgSelector:
1032 case DeclarationName::ObjCOneArgSelector:
1033 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001034 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 break;
1036 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001037 Data = Name.getCXXOverloadedOperator();
1038 break;
1039 case DeclarationName::CXXLiteralOperatorName:
1040 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1041 break;
Richard Smith35845152017-02-07 01:37:30 +00001042 case DeclarationName::CXXDeductionGuideName:
1043 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1044 ->getDeclName().getAsIdentifierInfo();
1045 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001046 case DeclarationName::CXXConstructorName:
1047 case DeclarationName::CXXDestructorName:
1048 case DeclarationName::CXXConversionFunctionName:
1049 case DeclarationName::CXXUsingDirective:
1050 Data = 0;
1051 break;
1052 }
1053}
1054
1055unsigned DeclarationNameKey::getHash() const {
1056 llvm::FoldingSetNodeID ID;
1057 ID.AddInteger(Kind);
1058
1059 switch (Kind) {
1060 case DeclarationName::Identifier:
1061 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001062 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001063 ID.AddString(((IdentifierInfo*)Data)->getName());
1064 break;
1065 case DeclarationName::ObjCZeroArgSelector:
1066 case DeclarationName::ObjCOneArgSelector:
1067 case DeclarationName::ObjCMultiArgSelector:
1068 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1069 break;
1070 case DeclarationName::CXXOperatorName:
1071 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001072 break;
1073 case DeclarationName::CXXConstructorName:
1074 case DeclarationName::CXXDestructorName:
1075 case DeclarationName::CXXConversionFunctionName:
1076 case DeclarationName::CXXUsingDirective:
1077 break;
1078 }
1079
1080 return ID.ComputeHash();
1081}
1082
Richard Smithd88a7f12015-09-01 20:35:42 +00001083ModuleFile *
1084ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1085 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001086
Richard Smithd88a7f12015-09-01 20:35:42 +00001087 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1088 return Reader.getLocalModuleFile(F, ModuleFileID);
1089}
1090
Guy Benyei11169dd2012-12-18 14:30:41 +00001091std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001092ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001093 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001094
Justin Bogner57ba0b22014-03-28 22:03:24 +00001095 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1096 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 return std::make_pair(KeyLen, DataLen);
1098}
1099
Richard Smitha06c7e62015-08-26 23:55:49 +00001100ASTDeclContextNameLookupTrait::internal_key_type
1101ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001102 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001103
Vedant Kumar48b4f762018-04-14 01:40:48 +00001104 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001105 uint64_t Data;
1106 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001108 case DeclarationName::CXXLiteralOperatorName:
1109 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001110 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001111 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 break;
1113 case DeclarationName::ObjCZeroArgSelector:
1114 case DeclarationName::ObjCOneArgSelector:
1115 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001116 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001117 (uint64_t)Reader.getLocalSelector(
1118 F, endian::readNext<uint32_t, little, unaligned>(
1119 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 break;
1121 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001122 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001124 case DeclarationName::CXXConstructorName:
1125 case DeclarationName::CXXDestructorName:
1126 case DeclarationName::CXXConversionFunctionName:
1127 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001128 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001129 break;
1130 }
1131
Richard Smitha06c7e62015-08-26 23:55:49 +00001132 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001133}
1134
Richard Smithd88a7f12015-09-01 20:35:42 +00001135void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1136 const unsigned char *d,
1137 unsigned DataLen,
1138 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001139 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001140
Richard Smithd88a7f12015-09-01 20:35:42 +00001141 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1142 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1143 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1144 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001145}
1146
Richard Smith0f4e2c42015-08-06 04:23:48 +00001147bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1148 BitstreamCursor &Cursor,
1149 uint64_t Offset,
1150 DeclContext *DC) {
1151 assert(Offset != 0);
1152
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001154 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1155 Error(std::move(Err));
1156 return true;
1157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001158
Richard Smith0f4e2c42015-08-06 04:23:48 +00001159 RecordData Record;
1160 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001161 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1162 if (!MaybeCode) {
1163 Error(MaybeCode.takeError());
1164 return true;
1165 }
1166 unsigned Code = MaybeCode.get();
1167
1168 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1169 if (!MaybeRecCode) {
1170 Error(MaybeRecCode.takeError());
1171 return true;
1172 }
1173 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001174 if (RecCode != DECL_CONTEXT_LEXICAL) {
1175 Error("Expected lexical block");
1176 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 }
1178
Richard Smith82f8fcd2015-08-06 22:07:25 +00001179 assert(!isa<TranslationUnitDecl>(DC) &&
1180 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001181 // If we are handling a C++ class template instantiation, we can see multiple
1182 // lexical updates for the same record. It's important that we select only one
1183 // of them, so that field numbering works properly. Just pick the first one we
1184 // see.
1185 auto &Lex = LexicalDecls[DC];
1186 if (!Lex.first) {
1187 Lex = std::make_pair(
1188 &M, llvm::makeArrayRef(
1189 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1190 Blob.data()),
1191 Blob.size() / 4));
1192 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001193 DC->setHasExternalLexicalStorage(true);
1194 return false;
1195}
Guy Benyei11169dd2012-12-18 14:30:41 +00001196
Richard Smith0f4e2c42015-08-06 04:23:48 +00001197bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1198 BitstreamCursor &Cursor,
1199 uint64_t Offset,
1200 DeclID ID) {
1201 assert(Offset != 0);
1202
1203 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001204 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1205 Error(std::move(Err));
1206 return true;
1207 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001208
1209 RecordData Record;
1210 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001211 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1212 if (!MaybeCode) {
1213 Error(MaybeCode.takeError());
1214 return true;
1215 }
1216 unsigned Code = MaybeCode.get();
1217
1218 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1219 if (!MaybeRecCode) {
1220 Error(MaybeRecCode.takeError());
1221 return true;
1222 }
1223 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001224 if (RecCode != DECL_CONTEXT_VISIBLE) {
1225 Error("Expected visible lookup table block");
1226 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001227 }
1228
Richard Smith0f4e2c42015-08-06 04:23:48 +00001229 // We can't safely determine the primary context yet, so delay attaching the
1230 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001231 auto *Data = (const unsigned char*)Blob.data();
1232 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001233 return false;
1234}
1235
Richard Smith37a93df2017-02-18 00:32:02 +00001236void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001238 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001239 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001240 Diag(diag::note_module_cache_path)
1241 << PP.getHeaderSearchInfo().getModuleCachePath();
1242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001243}
1244
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001245void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1246 StringRef Arg3) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001247 if (Diags.isDiagnosticInFlight())
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001248 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
Guy Benyei11169dd2012-12-18 14:30:41 +00001249 else
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08001250 Diag(DiagID) << Arg1 << Arg2 << Arg3;
Guy Benyei11169dd2012-12-18 14:30:41 +00001251}
1252
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00001253void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
1254 unsigned Select) const {
1255 if (!Diags.isDiagnosticInFlight())
1256 Diag(DiagID) << Arg1 << Arg2 << Select;
1257}
1258
JF Bastien0e828952019-06-26 19:50:12 +00001259void ASTReader::Error(llvm::Error &&Err) const {
1260 Error(toString(std::move(Err)));
1261}
1262
Guy Benyei11169dd2012-12-18 14:30:41 +00001263//===----------------------------------------------------------------------===//
1264// Source Manager Deserialization
1265//===----------------------------------------------------------------------===//
1266
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001267/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001268/// \returns true if there was an error.
1269bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001270 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001271 unsigned Idx = 0;
1272 LineTableInfo &LineTable = SourceMgr.getLineTable();
1273
1274 // Parse the file names
1275 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001276 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001277 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001278 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001279 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001280 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1281 }
Richard Smith63078492015-09-01 07:41:55 +00001282 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001283
1284 // Parse the line entries
1285 std::vector<LineEntry> Entries;
1286 while (Idx < Record.size()) {
1287 int FID = Record[Idx++];
1288 assert(FID >= 0 && "Serialized line entries for non-local file.");
1289 // Remap FileID from 1-based old view.
1290 FID += F.SLocEntryBaseID - 1;
1291
1292 // Extract the line entries
1293 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001294 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 Entries.clear();
1296 Entries.reserve(NumEntries);
1297 for (unsigned I = 0; I != NumEntries; ++I) {
1298 unsigned FileOffset = Record[Idx++];
1299 unsigned LineNo = Record[Idx++];
1300 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001301 SrcMgr::CharacteristicKind FileKind
1302 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001303 unsigned IncludeOffset = Record[Idx++];
1304 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1305 FileKind, IncludeOffset));
1306 }
1307 LineTable.AddEntry(FileID::get(FID), Entries);
1308 }
1309
1310 return false;
1311}
1312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001313/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001314bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1315 using namespace SrcMgr;
1316
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001317 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001318
1319 // Set the source-location entry cursor to the current position in
1320 // the stream. This cursor will be used to read the contents of the
1321 // source manager block initially, and then lazily read
1322 // source-location entries as needed.
1323 SLocEntryCursor = F.Stream;
1324
1325 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001326 if (llvm::Error Err = F.Stream.SkipBlock()) {
1327 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 return true;
1329 }
1330
1331 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001332 if (llvm::Error Err =
1333 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1334 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001335 return true;
1336 }
1337
1338 RecordData Record;
1339 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001340 Expected<llvm::BitstreamEntry> MaybeE =
1341 SLocEntryCursor.advanceSkippingSubblocks();
1342 if (!MaybeE) {
1343 Error(MaybeE.takeError());
1344 return true;
1345 }
1346 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001347
Chris Lattnere7b154b2013-01-19 21:39:22 +00001348 switch (E.Kind) {
1349 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1350 case llvm::BitstreamEntry::Error:
1351 Error("malformed block record in AST file");
1352 return true;
1353 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001354 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001355 case llvm::BitstreamEntry::Record:
1356 // The interesting case.
1357 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001359
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001362 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001363 Expected<unsigned> MaybeRecord =
1364 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1365 if (!MaybeRecord) {
1366 Error(MaybeRecord.takeError());
1367 return true;
1368 }
1369 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 default: // Default behavior: ignore.
1371 break;
1372
1373 case SM_SLOC_FILE_ENTRY:
1374 case SM_SLOC_BUFFER_ENTRY:
1375 case SM_SLOC_EXPANSION_ENTRY:
1376 // Once we hit one of the source location entries, we're done.
1377 return false;
1378 }
1379 }
1380}
1381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001382/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001383/// and the PCH file was moved from its original location, try to resolve the
1384/// file by assuming that header+PCH were moved together and the header is in
1385/// the same place relative to the PCH.
1386static std::string
1387resolveFileRelativeToOriginalDir(const std::string &Filename,
1388 const std::string &OriginalDir,
1389 const std::string &CurrDir) {
1390 assert(OriginalDir != CurrDir &&
1391 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001392
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001394
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 SmallString<128> filePath(Filename);
1396 fs::make_absolute(filePath);
1397 assert(path::is_absolute(OriginalDir));
1398 SmallString<128> currPCHPath(CurrDir);
1399
1400 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1401 fileDirE = path::end(path::parent_path(filePath));
1402 path::const_iterator origDirI = path::begin(OriginalDir),
1403 origDirE = path::end(OriginalDir);
1404 // Skip the common path components from filePath and OriginalDir.
1405 while (fileDirI != fileDirE && origDirI != origDirE &&
1406 *fileDirI == *origDirI) {
1407 ++fileDirI;
1408 ++origDirI;
1409 }
1410 for (; origDirI != origDirE; ++origDirI)
1411 path::append(currPCHPath, "..");
1412 path::append(currPCHPath, fileDirI, fileDirE);
1413 path::append(currPCHPath, path::filename(Filename));
Benjamin Krameradcd0262020-01-28 20:23:46 +01001414 return std::string(currPCHPath.str());
Guy Benyei11169dd2012-12-18 14:30:41 +00001415}
1416
1417bool ASTReader::ReadSLocEntry(int ID) {
1418 if (ID == 0)
1419 return false;
1420
1421 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1422 Error("source location entry ID out-of-range for AST file");
1423 return true;
1424 }
1425
Richard Smithaada85c2016-02-06 02:06:43 +00001426 // Local helper to read the (possibly-compressed) buffer data following the
1427 // entry record.
1428 auto ReadBuffer = [this](
1429 BitstreamCursor &SLocEntryCursor,
1430 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1431 RecordData Record;
1432 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001433 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1434 if (!MaybeCode) {
1435 Error(MaybeCode.takeError());
1436 return nullptr;
1437 }
1438 unsigned Code = MaybeCode.get();
1439
1440 Expected<unsigned> MaybeRecCode =
1441 SLocEntryCursor.readRecord(Code, Record, &Blob);
1442 if (!MaybeRecCode) {
1443 Error(MaybeRecCode.takeError());
1444 return nullptr;
1445 }
1446 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001447
1448 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001449 if (!llvm::zlib::isAvailable()) {
1450 Error("zlib is not available");
1451 return nullptr;
1452 }
Richard Smithaada85c2016-02-06 02:06:43 +00001453 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001454 if (llvm::Error E =
1455 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1456 Error("could not decompress embedded file contents: " +
1457 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001458 return nullptr;
1459 }
1460 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1461 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1462 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1463 } else {
1464 Error("AST record has invalid code");
1465 return nullptr;
1466 }
1467 };
1468
Guy Benyei11169dd2012-12-18 14:30:41 +00001469 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001470 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1471 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1472 Error(std::move(Err));
1473 return true;
1474 }
1475
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001476 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 unsigned BaseOffset = F->SLocEntryBaseOffset;
1478
1479 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001480 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1481 if (!MaybeEntry) {
1482 Error(MaybeEntry.takeError());
1483 return true;
1484 }
1485 llvm::BitstreamEntry Entry = MaybeEntry.get();
1486
Chris Lattnere7b154b2013-01-19 21:39:22 +00001487 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 Error("incorrectly-formatted source location entry in AST file");
1489 return true;
1490 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001491
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001493 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001494 Expected<unsigned> MaybeSLOC =
1495 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1496 if (!MaybeSLOC) {
1497 Error(MaybeSLOC.takeError());
1498 return true;
1499 }
1500 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001501 default:
1502 Error("incorrectly-formatted source location entry in AST file");
1503 return true;
1504
1505 case SM_SLOC_FILE_ENTRY: {
1506 // We will detect whether a file changed and return 'Failure' for it, but
1507 // we will also try to fail gracefully by setting up the SLocEntry.
1508 unsigned InputID = Record[4];
1509 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001510 const FileEntry *File = IF.getFile();
1511 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001512
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001513 // Note that we only check if a File was returned. If it was out-of-date
1514 // we have complained but we will continue creating a FileID to recover
1515 // gracefully.
1516 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 return true;
1518
1519 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1520 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1521 // This is the module's main file.
1522 IncludeLoc = getImportLocation(F);
1523 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001524 SrcMgr::CharacteristicKind
1525 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001526 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1528 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001529 SrcMgr::FileInfo &FileInfo =
1530 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 FileInfo.NumCreatedFIDs = Record[5];
1532 if (Record[3])
1533 FileInfo.setHasLineDirectives();
1534
Guy Benyei11169dd2012-12-18 14:30:41 +00001535 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001536 if (NumFileDecls && ContextObj) {
Roman Lebedevbf4f1e02019-10-10 12:22:42 +00001537 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1539 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1540 NumFileDecls));
1541 }
Richard Smithaada85c2016-02-06 02:06:43 +00001542
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001544 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001546 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1547 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001548 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1549 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001551 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001552 }
1553
1554 break;
1555 }
1556
1557 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001558 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001559 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001560 SrcMgr::CharacteristicKind
1561 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001563 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001564 IncludeLoc = getImportLocation(F);
1565 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001566
Richard Smithaada85c2016-02-06 02:06:43 +00001567 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1568 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001570 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001571 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 break;
1573 }
1574
1575 case SM_SLOC_EXPANSION_ENTRY: {
1576 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1577 SourceMgr.createExpansionLoc(SpellingLoc,
1578 ReadSourceLocation(*F, Record[2]),
1579 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001580 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001581 Record[4],
1582 ID,
1583 BaseOffset + Record[0]);
1584 break;
1585 }
1586 }
1587
1588 return false;
1589}
1590
1591std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1592 if (ID == 0)
1593 return std::make_pair(SourceLocation(), "");
1594
1595 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1596 Error("source location entry ID out-of-range for AST file");
1597 return std::make_pair(SourceLocation(), "");
1598 }
1599
1600 // Find which module file this entry lands in.
1601 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001602 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 return std::make_pair(SourceLocation(), "");
1604
1605 // FIXME: Can we map this down to a particular submodule? That would be
1606 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001607 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001608}
1609
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001610/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001611SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1612 if (F->ImportLoc.isValid())
1613 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001614
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 // Otherwise we have a PCH. It's considered to be "imported" at the first
1616 // location of its includer.
1617 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001618 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001619 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001620 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001621 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001622 return F->ImportedBy[0]->FirstLoc;
1623}
1624
JF Bastien0e828952019-06-26 19:50:12 +00001625/// Enter a subblock of the specified BlockID with the specified cursor. Read
1626/// the abbreviations that are at the top of the block and then leave the cursor
1627/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001628bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001629 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1630 // FIXME this drops errors on the floor.
1631 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001632 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001633 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001634
1635 while (true) {
1636 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001637 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1638 if (!MaybeCode) {
1639 // FIXME this drops errors on the floor.
1640 consumeError(MaybeCode.takeError());
1641 return true;
1642 }
1643 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001644
1645 // We expect all abbrevs to be at the start of the block.
1646 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001647 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1648 // FIXME this drops errors on the floor.
1649 consumeError(std::move(Err));
1650 return true;
1651 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 return false;
1653 }
JF Bastien0e828952019-06-26 19:50:12 +00001654 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1655 // FIXME this drops errors on the floor.
1656 consumeError(std::move(Err));
1657 return true;
1658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 }
1660}
1661
Richard Smithe40f2ba2013-08-07 21:41:30 +00001662Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001663 unsigned &Idx) {
1664 Token Tok;
1665 Tok.startToken();
1666 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1667 Tok.setLength(Record[Idx++]);
1668 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1669 Tok.setIdentifierInfo(II);
1670 Tok.setKind((tok::TokenKind)Record[Idx++]);
1671 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1672 return Tok;
1673}
1674
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001675MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001676 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001677
1678 // Keep track of where we are in the stream, then jump back there
1679 // after reading this macro.
1680 SavedStreamPosition SavedPosition(Stream);
1681
JF Bastien0e828952019-06-26 19:50:12 +00001682 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1683 // FIXME this drops errors on the floor.
1684 consumeError(std::move(Err));
1685 return nullptr;
1686 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001687 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001688 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001689 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001690
Guy Benyei11169dd2012-12-18 14:30:41 +00001691 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001692 // Advance to the next record, but if we get to the end of the block, don't
1693 // pop it (removing all the abbreviations from the cursor) since we want to
1694 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001695 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001696 Expected<llvm::BitstreamEntry> MaybeEntry =
1697 Stream.advanceSkippingSubblocks(Flags);
1698 if (!MaybeEntry) {
1699 Error(MaybeEntry.takeError());
1700 return Macro;
1701 }
1702 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001703
Chris Lattnerefa77172013-01-20 00:00:22 +00001704 switch (Entry.Kind) {
1705 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1706 case llvm::BitstreamEntry::Error:
1707 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001708 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001709 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001710 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001711 case llvm::BitstreamEntry::Record:
1712 // The interesting case.
1713 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 }
1715
1716 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001717 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001718 PreprocessorRecordTypes RecType;
1719 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1720 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1721 else {
1722 Error(MaybeRecType.takeError());
1723 return Macro;
1724 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001725 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001726 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727 case PP_MACRO_DIRECTIVE_HISTORY:
1728 return Macro;
1729
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 case PP_MACRO_OBJECT_LIKE:
1731 case PP_MACRO_FUNCTION_LIKE: {
1732 // If we already have a macro, that means that we've hit the end
1733 // of the definition of the macro we were looking for. We're
1734 // done.
1735 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001736 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001737
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001738 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001740 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001741 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001743 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001744
Guy Benyei11169dd2012-12-18 14:30:41 +00001745 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1746 // Decode function-like macro info.
1747 bool isC99VarArgs = Record[NextIndex++];
1748 bool isGNUVarArgs = Record[NextIndex++];
1749 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001750 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001751 unsigned NumArgs = Record[NextIndex++];
1752 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001753 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001754
1755 // Install function-like macro info.
1756 MI->setIsFunctionLike();
1757 if (isC99VarArgs) MI->setIsC99Varargs();
1758 if (isGNUVarArgs) MI->setIsGNUVarargs();
1759 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001760 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001761 }
1762
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 // Remember that we saw this macro last so that we add the tokens that
1764 // form its body to it.
1765 Macro = MI;
1766
1767 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1768 Record[NextIndex]) {
1769 // We have a macro definition. Register the association
1770 PreprocessedEntityID
1771 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1772 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001773 PreprocessingRecord::PPEntityID PPID =
1774 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001775 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001776 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001777 if (PPDef)
1778 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 }
1780
1781 ++NumMacrosRead;
1782 break;
1783 }
1784
1785 case PP_TOKEN: {
1786 // If we see a TOKEN before a PP_MACRO_*, then the file is
1787 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001788 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001789
John McCallf413f5e2013-05-03 00:10:13 +00001790 unsigned Idx = 0;
1791 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 Macro->AddTokenToBody(Tok);
1793 break;
1794 }
1795 }
1796 }
1797}
1798
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001799PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001800ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1801 unsigned LocalID) const {
1802 if (!M.ModuleOffsetMap.empty())
1803 ReadModuleOffsetMap(M);
1804
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001805 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001807 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001809
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 return LocalID + I->second;
1811}
1812
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001813unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1814 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001815}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001816
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001817HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001818HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001819 internal_key_type ikey = {FE->getSize(),
1820 M.HasTimestamps ? FE->getModificationTime() : 0,
1821 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001822 return ikey;
1823}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001824
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001825bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001826 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 return false;
1828
Mehdi Amini004b9c72016-10-10 22:52:47 +00001829 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001830 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001831
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001833 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001834 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001835 if (!Key.Imported) {
1836 if (auto File = FileMgr.getFile(Key.Filename))
1837 return *File;
1838 return nullptr;
1839 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001840
Benjamin Krameradcd0262020-01-28 20:23:46 +01001841 std::string Resolved = std::string(Key.Filename);
Richard Smith7ed1bc92014-12-05 22:42:13 +00001842 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001843 if (auto File = FileMgr.getFile(Resolved))
1844 return *File;
1845 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001846 };
1847
1848 const FileEntry *FEA = GetFile(a);
1849 const FileEntry *FEB = GetFile(b);
1850 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001851}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001852
Guy Benyei11169dd2012-12-18 14:30:41 +00001853std::pair<unsigned, unsigned>
1854HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001855 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001856
Vedant Kumar48b4f762018-04-14 01:40:48 +00001857 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1858 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001859 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001860}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001861
1862HeaderFileInfoTrait::internal_key_type
1863HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001864 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001865
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001866 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001867 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1868 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001869 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001870 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001871 return ikey;
1872}
1873
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001874HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001875HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001877 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001878
1879 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 HeaderFileInfo HFI;
1881 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001882 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001883 HFI.isImport |= (Flags >> 5) & 0x01;
1884 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1885 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001887 // FIXME: Find a better way to handle this. Maybe just store a
1888 // "has been included" flag?
1889 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1890 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001891 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1892 M, endian::readNext<uint32_t, little, unaligned>(d));
1893 if (unsigned FrameworkOffset =
1894 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001895 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001896 // since 0 is used as an indicator for "no framework name".
1897 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1898 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1899 }
Richard Smith386bb072015-08-18 23:42:23 +00001900
1901 assert((End - d) % 4 == 0 &&
1902 "Wrong data length in HeaderFileInfo deserialization");
1903 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001904 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001905 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1906 LocalSMID >>= 2;
1907
1908 // This header is part of a module. Associate it with the module to enable
1909 // implicit module import.
1910 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1911 Module *Mod = Reader.getSubmodule(GlobalSMID);
1912 FileManager &FileMgr = Reader.getFileManager();
1913 ModuleMap &ModMap =
1914 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1915
Benjamin Krameradcd0262020-01-28 20:23:46 +01001916 std::string Filename = std::string(key.Filename);
Richard Smith386bb072015-08-18 23:42:23 +00001917 if (key.Imported)
1918 Reader.ResolveImportedPath(M, Filename);
1919 // FIXME: This is not always the right filename-as-written, but we're not
1920 // going to use this information to rebuild the module, so it doesn't make
1921 // a lot of difference.
Benjamin Krameradcd0262020-01-28 20:23:46 +01001922 Module::Header H = {std::string(key.Filename), *FileMgr.getFile(Filename)};
Richard Smithd8879c82015-08-24 21:59:32 +00001923 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1924 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001925 }
1926
Guy Benyei11169dd2012-12-18 14:30:41 +00001927 // This HeaderFileInfo was externally loaded.
1928 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001929 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001930 return HFI;
1931}
1932
Richard Smithd7329392015-04-21 21:46:32 +00001933void ASTReader::addPendingMacro(IdentifierInfo *II,
1934 ModuleFile *M,
1935 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001936 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1937 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001938}
1939
1940void ASTReader::ReadDefinedMacros() {
1941 // Note that we are loading defined macros.
1942 Deserializing Macros(this);
1943
Vedant Kumar48b4f762018-04-14 01:40:48 +00001944 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001945 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001946
1947 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001948 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001949 continue;
1950
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001951 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001952 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1953 Error(std::move(Err));
1954 return;
1955 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001956
1957 RecordData Record;
1958 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001959 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1960 if (!MaybeE) {
1961 Error(MaybeE.takeError());
1962 return;
1963 }
1964 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001965
Chris Lattnere7b154b2013-01-19 21:39:22 +00001966 switch (E.Kind) {
1967 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1968 case llvm::BitstreamEntry::Error:
1969 Error("malformed block record in AST file");
1970 return;
1971 case llvm::BitstreamEntry::EndBlock:
1972 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001973
JF Bastien0e828952019-06-26 19:50:12 +00001974 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001975 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001976 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1977 if (!MaybeRecord) {
1978 Error(MaybeRecord.takeError());
1979 return;
1980 }
1981 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001982 default: // Default behavior: ignore.
1983 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001984
Chris Lattnere7b154b2013-01-19 21:39:22 +00001985 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001986 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001987 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001988 if (II->isOutOfDate())
1989 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001990 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001991 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001992
Chris Lattnere7b154b2013-01-19 21:39:22 +00001993 case PP_TOKEN:
1994 // Ignore tokens.
1995 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001997 break;
1998 }
JF Bastien0e828952019-06-26 19:50:12 +00001999 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002000 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002001 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 }
2003}
2004
2005namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002006
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002007 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 class IdentifierLookupVisitor {
2009 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002010 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002011 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002012 unsigned &NumIdentifierLookups;
2013 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002014 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002015
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002017 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2018 unsigned &NumIdentifierLookups,
2019 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002020 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2021 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002022 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002023 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002024
2025 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002027 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002028 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002029
Vedant Kumar48b4f762018-04-14 01:40:48 +00002030 ASTIdentifierLookupTable *IdTable
2031 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002032 if (!IdTable)
2033 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002034
2035 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002036 Found);
2037 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002038 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002039 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 if (Pos == IdTable->end())
2041 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002042
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 // Dereferencing the iterator has the effect of building the
2044 // IdentifierInfo node and populating it with the various
2045 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002046 ++NumIdentifierLookupHits;
2047 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002048 return true;
2049 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002051 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002052 // files.
2053 IdentifierInfo *getIdentifierInfo() const { return Found; }
2054 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002055
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002056} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002057
2058void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2059 // Note that we are loading an identifier.
2060 Deserializing AnIdentifier(this);
2061
2062 unsigned PriorGeneration = 0;
2063 if (getContext().getLangOpts().Modules)
2064 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002065
2066 // If there is a global index, look there first to determine which modules
2067 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002068 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002069 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002070 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002071 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2072 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002073 }
2074 }
2075
Douglas Gregor7211ac12013-01-25 23:32:03 +00002076 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002077 NumIdentifierLookups,
2078 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002079 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002080 markIdentifierUpToDate(&II);
2081}
2082
2083void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2084 if (!II)
2085 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002086
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 II->setOutOfDate(false);
2088
2089 // Update the generation for this identifier.
2090 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002091 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002092}
2093
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002094void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2095 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002096 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002097
2098 BitstreamCursor &Cursor = M.MacroCursor;
2099 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002100 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2101 Error(std::move(Err));
2102 return;
2103 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002104
Richard Smith713369b2015-04-23 20:40:50 +00002105 struct ModuleMacroRecord {
2106 SubmoduleID SubModID;
2107 MacroInfo *MI;
2108 SmallVector<SubmoduleID, 8> Overrides;
2109 };
2110 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002111
Richard Smithd7329392015-04-21 21:46:32 +00002112 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2113 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2114 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002115 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002116 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002117 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002118 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002119 if (!MaybeEntry) {
2120 Error(MaybeEntry.takeError());
2121 return;
2122 }
2123 llvm::BitstreamEntry Entry = MaybeEntry.get();
2124
Richard Smithd7329392015-04-21 21:46:32 +00002125 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2126 Error("malformed block record in AST file");
2127 return;
2128 }
2129
2130 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002131 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2132 if (!MaybePP) {
2133 Error(MaybePP.takeError());
2134 return;
2135 }
2136 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002137 case PP_MACRO_DIRECTIVE_HISTORY:
2138 break;
2139
2140 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002141 ModuleMacros.push_back(ModuleMacroRecord());
2142 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002143 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2144 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002145 for (int I = 2, N = Record.size(); I != N; ++I)
2146 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002147 continue;
2148 }
2149
2150 default:
2151 Error("malformed block record in AST file");
2152 return;
2153 }
2154
2155 // We found the macro directive history; that's the last record
2156 // for this macro.
2157 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002158 }
2159
Richard Smithd7329392015-04-21 21:46:32 +00002160 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002161 {
2162 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002163 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002164 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002165 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002166 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002167 Module *Mod = getSubmodule(ModID);
2168 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002169 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002170 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002171 }
2172
2173 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002174 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002175 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002176 }
2177 }
2178
2179 // Don't read the directive history for a module; we don't have anywhere
2180 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002181 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002182 return;
2183
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002184 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002185 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002186 unsigned Idx = 0, N = Record.size();
2187 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002188 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002189 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002190 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002191 switch (K) {
2192 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002193 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002194 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002195 break;
2196 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002197 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002198 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002199 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002200 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002201 bool isPublic = Record[Idx++];
2202 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2203 break;
2204 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002205
2206 if (!Latest)
2207 Latest = MD;
2208 if (Earliest)
2209 Earliest->setPrevious(MD);
2210 Earliest = MD;
2211 }
2212
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002213 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002214 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002215}
2216
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002217ASTReader::InputFileInfo
2218ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002219 // Go find this input file.
2220 BitstreamCursor &Cursor = F.InputFilesCursor;
2221 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002222 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2223 // FIXME this drops errors on the floor.
2224 consumeError(std::move(Err));
2225 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002226
JF Bastien0e828952019-06-26 19:50:12 +00002227 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2228 if (!MaybeCode) {
2229 // FIXME this drops errors on the floor.
2230 consumeError(MaybeCode.takeError());
2231 }
2232 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002233 RecordData Record;
2234 StringRef Blob;
2235
JF Bastien0e828952019-06-26 19:50:12 +00002236 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2237 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2238 "invalid record type for input file");
2239 else {
2240 // FIXME this drops errors on the floor.
2241 consumeError(Maybe.takeError());
2242 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002243
2244 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002245 InputFileInfo R;
2246 R.StoredSize = static_cast<off_t>(Record[1]);
2247 R.StoredTime = static_cast<time_t>(Record[2]);
2248 R.Overridden = static_cast<bool>(Record[3]);
2249 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002250 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002251 R.Filename = std::string(Blob);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002252 ResolveImportedPath(F, R.Filename);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002253
2254 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
2255 if (!MaybeEntry) // FIXME this drops errors on the floor.
2256 consumeError(MaybeEntry.takeError());
2257 llvm::BitstreamEntry Entry = MaybeEntry.get();
2258 assert(Entry.Kind == llvm::BitstreamEntry::Record &&
2259 "expected record type for input file hash");
2260
2261 Record.clear();
2262 if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
2263 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
2264 "invalid record type for input file hash");
2265 else {
2266 // FIXME this drops errors on the floor.
2267 consumeError(Maybe.takeError());
2268 }
2269 R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
2270 static_cast<uint64_t>(Record[0]);
Hans Wennborg73945142014-03-14 17:45:06 +00002271 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002272}
2273
Manman Renc8c94152016-10-21 23:35:03 +00002274static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002275InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 // If this ID is bogus, just return an empty input file.
2277 if (ID == 0 || ID > F.InputFilesLoaded.size())
2278 return InputFile();
2279
2280 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002281 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 return F.InputFilesLoaded[ID-1];
2283
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002284 if (F.InputFilesLoaded[ID-1].isNotFound())
2285 return InputFile();
2286
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002288 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002290 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2291 // FIXME this drops errors on the floor.
2292 consumeError(std::move(Err));
2293 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002294
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002295 InputFileInfo FI = readInputFileInfo(F, ID);
2296 off_t StoredSize = FI.StoredSize;
2297 time_t StoredTime = FI.StoredTime;
2298 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002299 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002300 StringRef Filename = FI.Filename;
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002301 uint64_t StoredContentHash = FI.ContentHash;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002302
Harlan Haskins8d323d12019-08-01 21:31:56 +00002303 const FileEntry *File = nullptr;
2304 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2305 File = *FE;
2306
Ben Langmuir198c1682014-03-07 07:27:49 +00002307 // If we didn't find the file, resolve it relative to the
2308 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002309 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2310 F.OriginalDir != F.BaseDirectory) {
2311 std::string Resolved = resolveFileRelativeToOriginalDir(
Benjamin Krameradcd0262020-01-28 20:23:46 +01002312 std::string(Filename), F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002313 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002314 if (auto FE = FileMgr.getFile(Resolved))
2315 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002316 }
2317
2318 // For an overridden file, create a virtual file with the stored
2319 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002320 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002321 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002322
Craig Toppera13603a2014-05-22 05:54:18 +00002323 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002324 if (Complain) {
2325 std::string ErrorStr = "could not find file '";
2326 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002327 ErrorStr += "' referenced by AST file '";
2328 ErrorStr += F.FileName;
2329 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002330 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002332 // Record that we didn't find the file.
2333 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2334 return InputFile();
2335 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002336
Ben Langmuir198c1682014-03-07 07:27:49 +00002337 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002338 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002339 // can lead to problems when lexing using the source locations from the
2340 // PCH.
2341 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002342 // FIXME: Reject if the overrides are different.
2343 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002344 if (Complain)
2345 Error(diag::err_fe_pch_file_overridden, Filename);
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25 +00002346
2347 // After emitting the diagnostic, bypass the overriding file to recover
2348 // (this creates a separate FileEntry).
2349 File = SM.bypassFileContentsOverride(*File);
2350 if (!File) {
2351 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2352 return InputFile();
2353 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002354 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002355
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002356 enum ModificationType {
2357 Size,
2358 ModTime,
2359 Content,
2360 None,
2361 };
2362 auto HasInputFileChanged = [&]() {
2363 if (StoredSize != File->getSize())
2364 return ModificationType::Size;
2365 if (!DisableValidation && StoredTime &&
2366 StoredTime != File->getModificationTime()) {
2367 // In case the modification time changes but not the content,
2368 // accept the cached file as legit.
2369 if (ValidateASTInputFilesContent &&
2370 StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
2371 auto MemBuffOrError = FileMgr.getBufferForFile(File);
2372 if (!MemBuffOrError) {
2373 if (!Complain)
2374 return ModificationType::ModTime;
2375 std::string ErrorStr = "could not get buffer for file '";
2376 ErrorStr += File->getName();
2377 ErrorStr += "'";
2378 Error(ErrorStr);
2379 return ModificationType::ModTime;
2380 }
Eric Christopher3be91692019-10-14 23:14:24 +00002381
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002382 auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
2383 if (StoredContentHash == static_cast<uint64_t>(ContentHash))
2384 return ModificationType::None;
2385 return ModificationType::Content;
2386 }
2387 return ModificationType::ModTime;
2388 }
2389 return ModificationType::None;
2390 };
2391
2392 bool IsOutOfDate = false;
2393 auto FileChange = HasInputFileChanged();
Ben Langmuir198c1682014-03-07 07:27:49 +00002394 // For an overridden file, there is nothing to validate.
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002395 if (!Overridden && FileChange != ModificationType::None) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002396 if (Complain) {
2397 // Build a list of the PCH imports that got us here (in reverse).
2398 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002399 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002400 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002401
Ben Langmuir198c1682014-03-07 07:27:49 +00002402 // The top-level PCH is stale.
2403 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002404 unsigned DiagnosticKind =
2405 moduleKindForDiagnostic(ImportStack.back()->Kind);
Manman Renc8c94152016-10-21 23:35:03 +00002406 if (DiagnosticKind == 0)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002407 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName,
2408 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002409 else if (DiagnosticKind == 1)
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002410 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName,
2411 (unsigned)FileChange);
Manman Renc8c94152016-10-21 23:35:03 +00002412 else
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00002413 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName,
2414 (unsigned)FileChange);
Ben Langmuire82630d2014-01-17 00:19:09 +00002415
Ben Langmuir198c1682014-03-07 07:27:49 +00002416 // Print the import stack.
2417 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2418 Diag(diag::note_pch_required_by)
2419 << Filename << ImportStack[0]->FileName;
2420 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002421 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002422 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002423 }
2424
Ben Langmuir198c1682014-03-07 07:27:49 +00002425 if (!Diags.isDiagnosticInFlight())
2426 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 }
2428
Ben Langmuir198c1682014-03-07 07:27:49 +00002429 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002430 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002431 // FIXME: If the file is overridden and we've already opened it,
2432 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002433
Richard Smitha8cfffa2015-11-26 02:04:16 +00002434 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002435
2436 // Note that we've loaded this input file.
2437 F.InputFilesLoaded[ID-1] = IF;
2438 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439}
2440
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002441/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002442/// is not an absolute path, add the system or module root to the beginning of
2443/// the file name.
2444void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2445 // Resolve relative to the base directory, if we have one.
2446 if (!M.BaseDirectory.empty())
2447 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002448}
2449
Richard Smith7ed1bc92014-12-05 22:42:13 +00002450void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002451 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2452 return;
2453
Richard Smith7ed1bc92014-12-05 22:42:13 +00002454 SmallString<128> Buffer;
2455 llvm::sys::path::append(Buffer, Prefix, Filename);
2456 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002457}
2458
Richard Smith0f99d6a2015-08-09 08:48:41 +00002459static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2460 switch (ARR) {
2461 case ASTReader::Failure: return true;
2462 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2463 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2464 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2465 case ASTReader::ConfigurationMismatch:
2466 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2467 case ASTReader::HadErrors: return true;
2468 case ASTReader::Success: return false;
2469 }
2470
2471 llvm_unreachable("unknown ASTReadResult");
2472}
2473
Richard Smith0516b182015-09-08 19:40:14 +00002474ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2475 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2476 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002477 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002478 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2479 // FIXME this drops errors on the floor.
2480 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002481 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002482 }
Richard Smith0516b182015-09-08 19:40:14 +00002483
2484 // Read all of the records in the options block.
2485 RecordData Record;
2486 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002487 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002488 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2489 if (!MaybeEntry) {
2490 // FIXME this drops errors on the floor.
2491 consumeError(MaybeEntry.takeError());
2492 return Failure;
2493 }
2494 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002495
Richard Smith0516b182015-09-08 19:40:14 +00002496 switch (Entry.Kind) {
2497 case llvm::BitstreamEntry::Error:
2498 case llvm::BitstreamEntry::SubBlock:
2499 return Failure;
2500
2501 case llvm::BitstreamEntry::EndBlock:
2502 return Result;
2503
2504 case llvm::BitstreamEntry::Record:
2505 // The interesting case.
2506 break;
2507 }
2508
2509 // Read and process a record.
2510 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002511 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2512 if (!MaybeRecordType) {
2513 // FIXME this drops errors on the floor.
2514 consumeError(MaybeRecordType.takeError());
2515 return Failure;
2516 }
2517 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002518 case LANGUAGE_OPTIONS: {
2519 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2520 if (ParseLanguageOptions(Record, Complain, Listener,
2521 AllowCompatibleConfigurationMismatch))
2522 Result = ConfigurationMismatch;
2523 break;
2524 }
2525
2526 case TARGET_OPTIONS: {
2527 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2528 if (ParseTargetOptions(Record, Complain, Listener,
2529 AllowCompatibleConfigurationMismatch))
2530 Result = ConfigurationMismatch;
2531 break;
2532 }
2533
Richard Smith0516b182015-09-08 19:40:14 +00002534 case FILE_SYSTEM_OPTIONS: {
2535 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2536 if (!AllowCompatibleConfigurationMismatch &&
2537 ParseFileSystemOptions(Record, Complain, Listener))
2538 Result = ConfigurationMismatch;
2539 break;
2540 }
2541
2542 case HEADER_SEARCH_OPTIONS: {
2543 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2544 if (!AllowCompatibleConfigurationMismatch &&
2545 ParseHeaderSearchOptions(Record, Complain, Listener))
2546 Result = ConfigurationMismatch;
2547 break;
2548 }
2549
2550 case PREPROCESSOR_OPTIONS:
2551 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2552 if (!AllowCompatibleConfigurationMismatch &&
2553 ParsePreprocessorOptions(Record, Complain, Listener,
2554 SuggestedPredefines))
2555 Result = ConfigurationMismatch;
2556 break;
2557 }
2558 }
2559}
2560
Guy Benyei11169dd2012-12-18 14:30:41 +00002561ASTReader::ASTReadResult
2562ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002563 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002564 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002565 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002566 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002567
JF Bastien0e828952019-06-26 19:50:12 +00002568 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2569 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002570 return Failure;
2571 }
2572
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002573 // Lambda to read the unhashed control block the first time it's called.
2574 //
2575 // For PCM files, the unhashed control block cannot be read until after the
2576 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2577 // need to look ahead before reading the IMPORTS record. For consistency,
2578 // this block is always read somehow (see BitstreamEntry::EndBlock).
2579 bool HasReadUnhashedControlBlock = false;
2580 auto readUnhashedControlBlockOnce = [&]() {
2581 if (!HasReadUnhashedControlBlock) {
2582 HasReadUnhashedControlBlock = true;
2583 if (ASTReadResult Result =
2584 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2585 return Result;
2586 }
2587 return Success;
2588 };
2589
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 // Read all of the records and blocks in the control block.
2591 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002592 unsigned NumInputs = 0;
2593 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002594 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002595 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002596 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2597 if (!MaybeEntry) {
2598 Error(MaybeEntry.takeError());
2599 return Failure;
2600 }
2601 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002602
Chris Lattnere7b154b2013-01-19 21:39:22 +00002603 switch (Entry.Kind) {
2604 case llvm::BitstreamEntry::Error:
2605 Error("malformed block record in AST file");
2606 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002607 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002608 // Validate the module before returning. This call catches an AST with
2609 // no module name and no imports.
2610 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2611 return Result;
2612
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002613 // Validate input files.
2614 const HeaderSearchOptions &HSOpts =
2615 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002616
Richard Smitha1825302014-10-23 22:18:29 +00002617 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002618 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2619 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002620 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2621 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002623
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002624 // If we are reading a module, we will create a verification timestamp,
2625 // so we verify all input files. Otherwise, verify only user input
2626 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002627
2628 unsigned N = NumUserInputs;
2629 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002630 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002631 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002632 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002633 N = NumInputs;
2634
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002635 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002636 InputFile IF = getInputFile(F, I+1, Complain);
2637 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002639 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002641
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002642 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002643 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002644
Ben Langmuircb69b572014-03-07 06:40:32 +00002645 if (Listener && Listener->needsInputFileVisitation()) {
2646 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2647 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002648 for (unsigned I = 0; I < N; ++I) {
2649 bool IsSystem = I >= NumUserInputs;
2650 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002651 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002652 F.Kind == MK_ExplicitModule ||
2653 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002654 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002655 }
2656
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002657 return Success;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002658 }
2659
Chris Lattnere7b154b2013-01-19 21:39:22 +00002660 case llvm::BitstreamEntry::SubBlock:
2661 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 case INPUT_FILES_BLOCK_ID:
2663 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002664 if (llvm::Error Err = Stream.SkipBlock()) {
2665 Error(std::move(Err));
2666 return Failure;
2667 }
2668 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 Error("malformed block record in AST file");
2670 return Failure;
2671 }
2672 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002673
2674 case OPTIONS_BLOCK_ID:
2675 // If we're reading the first module for this group, check its options
2676 // are compatible with ours. For modules it imports, no further checking
2677 // is required, because we checked them when we built it.
2678 if (Listener && !ImportedBy) {
2679 // Should we allow the configuration of the module file to differ from
2680 // the configuration of the current translation unit in a compatible
2681 // way?
2682 //
2683 // FIXME: Allow this for files explicitly specified with -include-pch.
2684 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002685 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002686
Duncan P. N. Exon Smith69242e92019-11-19 14:44:22 -08002687 ASTReadResult Result =
2688 ReadOptionsBlock(Stream, ClientLoadCapabilities,
2689 AllowCompatibleConfigurationMismatch, *Listener,
2690 SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002691 if (Result == Failure) {
2692 Error("malformed block record in AST file");
2693 return Result;
2694 }
2695
Richard Smith8a308ec2015-11-05 00:54:55 +00002696 if (DisableValidation ||
2697 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2698 Result = Success;
2699
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002700 // If we can't load the module, exit early since we likely
2701 // will rebuild the module anyway. The stream may be in the
2702 // middle of a block.
2703 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002704 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002705 } else if (llvm::Error Err = Stream.SkipBlock()) {
2706 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002707 return Failure;
2708 }
2709 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002710
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 default:
JF Bastien0e828952019-06-26 19:50:12 +00002712 if (llvm::Error Err = Stream.SkipBlock()) {
2713 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002714 return Failure;
2715 }
2716 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002718
Chris Lattnere7b154b2013-01-19 21:39:22 +00002719 case llvm::BitstreamEntry::Record:
2720 // The interesting case.
2721 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 }
2723
2724 // Read and process a record.
2725 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002726 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002727 Expected<unsigned> MaybeRecordType =
2728 Stream.readRecord(Entry.ID, Record, &Blob);
2729 if (!MaybeRecordType) {
2730 Error(MaybeRecordType.takeError());
2731 return Failure;
2732 }
2733 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 case METADATA: {
2735 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2736 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002737 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2738 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002739 return VersionMismatch;
2740 }
2741
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002742 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2744 Diag(diag::err_pch_with_compiler_errors);
2745 return HadErrors;
2746 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002747 if (hasErrors) {
2748 Diags.ErrorOccurred = true;
2749 Diags.UncompilableErrorOccurred = true;
2750 Diags.UnrecoverableErrorOccurred = true;
2751 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002752
2753 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002754 // Relative paths in a relocatable PCH are relative to our sysroot.
2755 if (F.RelocatablePCH)
2756 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002757
Richard Smithe75ee0f2015-08-17 07:13:32 +00002758 F.HasTimestamps = Record[5];
2759
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002760 F.PCHHasObjectFile = Record[6];
2761
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002763 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2765 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002766 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 return VersionMismatch;
2768 }
2769 break;
2770 }
2771
2772 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002773 // Validate the AST before processing any imports (otherwise, untangling
2774 // them can be error-prone and expensive). A module will have a name and
2775 // will already have been validated, but this catches the PCH case.
2776 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2777 return Result;
2778
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002779 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 unsigned Idx = 0, N = Record.size();
2781 while (Idx < N) {
2782 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002783 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 // The import location will be the local one for now; we will adjust
2785 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002786 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002787 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002788 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002789 off_t StoredSize = (off_t)Record[Idx++];
2790 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002791 ASTFileSignature StoredSignature = {
2792 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2793 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2794 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002795
2796 std::string ImportedName = ReadString(Record, Idx);
2797 std::string ImportedFile;
2798
2799 // For prebuilt and explicit modules first consult the file map for
2800 // an override. Note that here we don't search prebuilt module
2801 // directories, only the explicit name to file mappings. Also, we will
2802 // still verify the size/signature making sure it is essentially the
2803 // same file but perhaps in a different location.
2804 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2805 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2806 ImportedName, /*FileMapOnly*/ true);
2807
2808 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002809 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2810 // ModuleCache as when writing.
2811 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002812 else
2813 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002814
Richard Smith0f99d6a2015-08-09 08:48:41 +00002815 // If our client can't cope with us being out of date, we can't cope with
2816 // our dependency being missing.
2817 unsigned Capabilities = ClientLoadCapabilities;
2818 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2819 Capabilities &= ~ARR_Missing;
2820
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002822 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2823 Loaded, StoredSize, StoredModTime,
2824 StoredSignature, Capabilities);
2825
2826 // If we diagnosed a problem, produce a backtrace.
2827 if (isDiagnosedResult(Result, Capabilities))
2828 Diag(diag::note_module_file_imported_by)
2829 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2830
2831 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 case Failure: return Failure;
2833 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002834 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 case OutOfDate: return OutOfDate;
2836 case VersionMismatch: return VersionMismatch;
2837 case ConfigurationMismatch: return ConfigurationMismatch;
2838 case HadErrors: return HadErrors;
2839 case Success: break;
2840 }
2841 }
2842 break;
2843 }
2844
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 case ORIGINAL_FILE:
2846 F.OriginalSourceFileID = FileID::get(Record[0]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01002847 F.ActualOriginalSourceFileName = std::string(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002849 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 break;
2851
2852 case ORIGINAL_FILE_ID:
2853 F.OriginalSourceFileID = FileID::get(Record[0]);
2854 break;
2855
2856 case ORIGINAL_PCH_DIR:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002857 F.OriginalDir = std::string(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 break;
2859
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002860 case MODULE_NAME:
Benjamin Krameradcd0262020-01-28 20:23:46 +01002861 F.ModuleName = std::string(Blob);
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002862 Diag(diag::remark_module_import)
2863 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2864 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002865 if (Listener)
2866 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002867
2868 // Validate the AST as soon as we have a name so we can exit early on
2869 // failure.
2870 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2871 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002872
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002873 break;
2874
Richard Smith223d3f22014-12-06 03:21:08 +00002875 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002876 // Save the BaseDirectory as written in the PCM for computing the module
2877 // filename for the ModuleCache.
2878 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002879 assert(!F.ModuleName.empty() &&
2880 "MODULE_DIRECTORY found before MODULE_NAME");
2881 // If we've already loaded a module map file covering this module, we may
2882 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002883 Module *M = PP.getHeaderSearchInfo().lookupModule(
2884 F.ModuleName, /*AllowSearch*/ true,
2885 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002886 if (M && M->Directory) {
2887 // If we're implicitly loading a module, the base directory can't
2888 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002889 // Don't emit module relocation error if we have -fno-validate-pch
2890 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2891 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002892 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2893 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002894 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2895 Diag(diag::err_imported_module_relocated)
2896 << F.ModuleName << Blob << M->Directory->getName();
2897 return OutOfDate;
2898 }
2899 }
Benjamin Krameradcd0262020-01-28 20:23:46 +01002900 F.BaseDirectory = std::string(M->Directory->getName());
Richard Smith223d3f22014-12-06 03:21:08 +00002901 } else {
Benjamin Krameradcd0262020-01-28 20:23:46 +01002902 F.BaseDirectory = std::string(Blob);
Richard Smith223d3f22014-12-06 03:21:08 +00002903 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002904 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002905 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002906
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002907 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002908 if (ASTReadResult Result =
2909 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2910 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002911 break;
2912
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002913 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002914 NumInputs = Record[0];
2915 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002916 F.InputFileOffsets =
2917 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002918 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002919 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 break;
2921 }
2922 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002923}
2924
Ben Langmuir2c9af442014-04-10 17:57:43 +00002925ASTReader::ASTReadResult
2926ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002927 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002928
JF Bastien0e828952019-06-26 19:50:12 +00002929 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2930 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002931 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 }
2933
2934 // Read all of the records and blocks for the AST file.
2935 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002936 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002937 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2938 if (!MaybeEntry) {
2939 Error(MaybeEntry.takeError());
2940 return Failure;
2941 }
2942 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002943
Chris Lattnere7b154b2013-01-19 21:39:22 +00002944 switch (Entry.Kind) {
2945 case llvm::BitstreamEntry::Error:
2946 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002947 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002948 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002949 // Outside of C++, we do not store a lookup map for the translation unit.
2950 // Instead, mark it as needing a lookup map to be built if this module
2951 // contains any declarations lexically within it (which it always does!).
2952 // This usually has no cost, since we very rarely need the lookup map for
2953 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002954 if (ASTContext *Ctx = ContextObj) {
2955 DeclContext *DC = Ctx->getTranslationUnitDecl();
2956 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2957 DC->setMustBuildLookupTable();
2958 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002959
Ben Langmuir2c9af442014-04-10 17:57:43 +00002960 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002961 case llvm::BitstreamEntry::SubBlock:
2962 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 case DECLTYPES_BLOCK_ID:
2964 // We lazily load the decls block, but we want to set up the
2965 // DeclsCursor cursor to point into it. Clone our current bitcode
2966 // cursor to it, enter the block and read the abbrevs in that block.
2967 // With the main cursor, we just skip over it.
2968 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002969 if (llvm::Error Err = Stream.SkipBlock()) {
2970 Error(std::move(Err));
2971 return Failure;
2972 }
2973 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002975 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 }
2977 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002978
Guy Benyei11169dd2012-12-18 14:30:41 +00002979 case PREPROCESSOR_BLOCK_ID:
2980 F.MacroCursor = Stream;
2981 if (!PP.getExternalSource())
2982 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002983
JF Bastien0e828952019-06-26 19:50:12 +00002984 if (llvm::Error Err = Stream.SkipBlock()) {
2985 Error(std::move(Err));
2986 return Failure;
2987 }
2988 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002990 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 }
2992 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2993 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002994
Guy Benyei11169dd2012-12-18 14:30:41 +00002995 case PREPROCESSOR_DETAIL_BLOCK_ID:
2996 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002997
2998 if (llvm::Error Err = Stream.SkipBlock()) {
2999 Error(std::move(Err));
3000 return Failure;
3001 }
3002 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00003004 Error("malformed preprocessor detail record in AST file");
3005 return Failure;
3006 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00003008 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003009
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 if (!PP.getPreprocessingRecord())
3011 PP.createPreprocessingRecord();
3012 if (!PP.getPreprocessingRecord()->getExternalSource())
3013 PP.getPreprocessingRecord()->SetExternalSource(*this);
3014 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003015
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 case SOURCE_MANAGER_BLOCK_ID:
3017 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003018 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003020
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00003022 if (ASTReadResult Result =
3023 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003024 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003026
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003028 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00003029
3030 if (llvm::Error Err = Stream.SkipBlock()) {
3031 Error(std::move(Err));
3032 return Failure;
3033 }
3034 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003036 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 }
3038 CommentsCursors.push_back(std::make_pair(C, &F));
3039 break;
3040 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003041
Guy Benyei11169dd2012-12-18 14:30:41 +00003042 default:
JF Bastien0e828952019-06-26 19:50:12 +00003043 if (llvm::Error Err = Stream.SkipBlock()) {
3044 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00003045 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00003046 }
3047 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 }
3049 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003050
Chris Lattnere7b154b2013-01-19 21:39:22 +00003051 case llvm::BitstreamEntry::Record:
3052 // The interesting case.
3053 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 }
3055
3056 // Read and process a record.
3057 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00003058 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00003059 Expected<unsigned> MaybeRecordType =
3060 Stream.readRecord(Entry.ID, Record, &Blob);
3061 if (!MaybeRecordType) {
3062 Error(MaybeRecordType.takeError());
3063 return Failure;
3064 }
3065 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003066
3067 // If we're not loading an AST context, we don't care about most records.
3068 if (!ContextObj) {
3069 switch (RecordType) {
3070 case IDENTIFIER_TABLE:
3071 case IDENTIFIER_OFFSET:
3072 case INTERESTING_IDENTIFIERS:
3073 case STATISTICS:
3074 case PP_CONDITIONAL_STACK:
3075 case PP_COUNTER_VALUE:
3076 case SOURCE_LOCATION_OFFSETS:
3077 case MODULE_OFFSET_MAP:
3078 case SOURCE_MANAGER_LINE_TABLE:
3079 case SOURCE_LOCATION_PRELOADS:
3080 case PPD_ENTITIES_OFFSETS:
3081 case HEADER_SEARCH_TABLE:
3082 case IMPORTED_MODULES:
3083 case MACRO_OFFSET:
3084 break;
3085 default:
3086 continue;
3087 }
3088 }
3089
3090 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 default: // Default behavior: ignore.
3092 break;
3093
3094 case TYPE_OFFSET: {
3095 if (F.LocalNumTypes != 0) {
3096 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003097 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003098 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003099 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 F.LocalNumTypes = Record[0];
3101 unsigned LocalBaseTypeIndex = Record[1];
3102 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003103
Guy Benyei11169dd2012-12-18 14:30:41 +00003104 if (F.LocalNumTypes > 0) {
3105 // Introduce the global -> local mapping for types within this module.
3106 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003107
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 // Introduce the local -> global mapping for types within this module.
3109 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003110 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003112
3113 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 }
3115 break;
3116 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003117
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 case DECL_OFFSET: {
3119 if (F.LocalNumDecls != 0) {
3120 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003121 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003122 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003123 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 F.LocalNumDecls = Record[0];
3125 unsigned LocalBaseDeclID = Record[1];
3126 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003129 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 // module.
3131 GlobalDeclMap.insert(
3132 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003133
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 // Introduce the local -> global mapping for declarations within this
3135 // module.
3136 F.DeclRemap.insertOrReplace(
3137 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003138
Guy Benyei11169dd2012-12-18 14:30:41 +00003139 // Introduce the global -> local mapping for declarations within this
3140 // module.
3141 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003142
Ben Langmuir52ca6782014-10-20 16:27:32 +00003143 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3144 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 break;
3146 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003147
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003149 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003150 LexicalContents Contents(
3151 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3152 Blob.data()),
3153 static_cast<unsigned int>(Blob.size() / 4));
3154 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 TU->setHasExternalLexicalStorage(true);
3156 break;
3157 }
3158
3159 case UPDATE_VISIBLE: {
3160 unsigned Idx = 0;
3161 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003162 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003163 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003164 // If we've already loaded the decl, perform the updates when we finish
3165 // loading this block.
3166 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003167 PendingUpdateRecords.push_back(
3168 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003169 break;
3170 }
3171
3172 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003173 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003175 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3176 (const unsigned char *)F.IdentifierTableData + Record[0],
3177 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3178 (const unsigned char *)F.IdentifierTableData,
3179 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003180
Guy Benyei11169dd2012-12-18 14:30:41 +00003181 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3182 }
3183 break;
3184
3185 case IDENTIFIER_OFFSET: {
3186 if (F.LocalNumIdentifiers != 0) {
3187 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003188 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003189 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003190 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 F.LocalNumIdentifiers = Record[0];
3192 unsigned LocalBaseIdentifierID = Record[1];
3193 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003194
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 if (F.LocalNumIdentifiers > 0) {
3196 // Introduce the global -> local mapping for identifiers within this
3197 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003198 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003200
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 // Introduce the local -> global mapping for identifiers within this
3202 // module.
3203 F.IdentifierRemap.insertOrReplace(
3204 std::make_pair(LocalBaseIdentifierID,
3205 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003206
Ben Langmuir52ca6782014-10-20 16:27:32 +00003207 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3208 + F.LocalNumIdentifiers);
3209 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 break;
3211 }
3212
Richard Smith33e0f7e2015-07-22 02:08:40 +00003213 case INTERESTING_IDENTIFIERS:
3214 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3215 break;
3216
Ben Langmuir332aafe2014-01-31 01:06:56 +00003217 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003218 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3219 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003221 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 break;
3223
David Blaikie9ffe5a32017-01-30 05:00:26 +00003224 case MODULAR_CODEGEN_DECLS:
3225 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3226 // them (ie: if we're not codegenerating this module).
Luboš Luňákcbc9d222019-11-03 21:15:03 +01003227 if (F.Kind == MK_MainFile ||
3228 getContext().getLangOpts().BuildingPCHWithObjectFile)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003229 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3230 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3231 break;
3232
Guy Benyei11169dd2012-12-18 14:30:41 +00003233 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003234 if (SpecialTypes.empty()) {
3235 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3236 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3237 break;
3238 }
3239
3240 if (SpecialTypes.size() != Record.size()) {
3241 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003242 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003243 }
3244
3245 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3246 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3247 if (!SpecialTypes[I])
3248 SpecialTypes[I] = ID;
3249 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3250 // merge step?
3251 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 break;
3253
3254 case STATISTICS:
3255 TotalNumStatements += Record[0];
3256 TotalNumMacros += Record[1];
3257 TotalLexicalDeclContexts += Record[2];
3258 TotalVisibleDeclContexts += Record[3];
3259 break;
3260
3261 case UNUSED_FILESCOPED_DECLS:
3262 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3264 break;
3265
3266 case DELEGATING_CTORS:
3267 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3268 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3269 break;
3270
3271 case WEAK_UNDECLARED_IDENTIFIERS:
3272 if (Record.size() % 4 != 0) {
3273 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003274 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003276
3277 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 // files. This isn't the way to do it :)
3279 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003280
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 // Translate the weak, undeclared identifiers into global IDs.
3282 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3283 WeakUndeclaredIdentifiers.push_back(
3284 getGlobalIdentifierID(F, Record[I++]));
3285 WeakUndeclaredIdentifiers.push_back(
3286 getGlobalIdentifierID(F, Record[I++]));
3287 WeakUndeclaredIdentifiers.push_back(
3288 ReadSourceLocation(F, Record, I).getRawEncoding());
3289 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3290 }
3291 break;
3292
Guy Benyei11169dd2012-12-18 14:30:41 +00003293 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003294 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 F.LocalNumSelectors = Record[0];
3296 unsigned LocalBaseSelectorID = Record[1];
3297 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003298
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003300 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003301 // module.
3302 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003303
3304 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 // module.
3306 F.SelectorRemap.insertOrReplace(
3307 std::make_pair(LocalBaseSelectorID,
3308 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003309
3310 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 }
3312 break;
3313 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003314
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003316 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003317 if (Record[0])
3318 F.SelectorLookupTable
3319 = ASTSelectorLookupTable::Create(
3320 F.SelectorLookupTableData + Record[0],
3321 F.SelectorLookupTableData,
3322 ASTSelectorLookupTrait(*this, F));
3323 TotalNumMethodPoolEntries += Record[1];
3324 break;
3325
3326 case REFERENCED_SELECTOR_POOL:
3327 if (!Record.empty()) {
3328 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003329 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 Record[Idx++]));
3331 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3332 getRawEncoding());
3333 }
3334 }
3335 break;
3336
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003337 case PP_CONDITIONAL_STACK:
3338 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003339 unsigned Idx = 0, End = Record.size() - 1;
3340 bool ReachedEOFWhileSkipping = Record[Idx++];
3341 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3342 if (ReachedEOFWhileSkipping) {
3343 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3344 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3345 bool FoundNonSkipPortion = Record[Idx++];
3346 bool FoundElse = Record[Idx++];
3347 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3348 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3349 FoundElse, ElseLoc);
3350 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003351 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003352 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003353 auto Loc = ReadSourceLocation(F, Record, Idx);
3354 bool WasSkipping = Record[Idx++];
3355 bool FoundNonSkip = Record[Idx++];
3356 bool FoundElse = Record[Idx++];
3357 ConditionalStack.push_back(
3358 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3359 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003360 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003361 }
3362 break;
3363
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 case PP_COUNTER_VALUE:
3365 if (!Record.empty() && Listener)
3366 Listener->ReadCounter(F, Record[0]);
3367 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003368
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003370 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003371 F.NumFileSortedDecls = Record[0];
3372 break;
3373
3374 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003375 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003376 F.LocalNumSLocEntries = Record[0];
3377 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003378 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003379 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003380 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003381 if (!F.SLocEntryBaseID) {
3382 Error("ran out of source locations");
3383 break;
3384 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003385 // Make our entry in the range map. BaseID is negative and growing, so
3386 // we invert it. Because we invert it, though, we need the other end of
3387 // the range.
3388 unsigned RangeStart =
3389 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3390 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3391 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3392
3393 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3394 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3395 GlobalSLocOffsetMap.insert(
3396 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3397 - SLocSpaceSize,&F));
3398
3399 // Initialize the remapping table.
3400 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003401 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003402 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003403 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003404 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003405
Guy Benyei11169dd2012-12-18 14:30:41 +00003406 TotalNumSLocEntries += F.LocalNumSLocEntries;
3407 break;
3408 }
3409
Richard Smith37a93df2017-02-18 00:32:02 +00003410 case MODULE_OFFSET_MAP:
3411 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003412 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003413
3414 case SOURCE_MANAGER_LINE_TABLE:
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003415 if (ParseLineTable(F, Record)) {
3416 Error("malformed SOURCE_MANAGER_LINE_TABLE in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003417 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08003418 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003419 break;
3420
3421 case SOURCE_LOCATION_PRELOADS: {
3422 // Need to transform from the local view (1-based IDs) to the global view,
3423 // which is based off F.SLocEntryBaseID.
3424 if (!F.PreloadSLocEntries.empty()) {
3425 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003426 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003428
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 F.PreloadSLocEntries.swap(Record);
3430 break;
3431 }
3432
3433 case EXT_VECTOR_DECLS:
3434 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3435 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3436 break;
3437
3438 case VTABLE_USES:
3439 if (Record.size() % 3 != 0) {
3440 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003441 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003443
Guy Benyei11169dd2012-12-18 14:30:41 +00003444 // Later tables overwrite earlier ones.
3445 // FIXME: Modules will have some trouble with this. This is clearly not
3446 // the right way to do this.
3447 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003448
Guy Benyei11169dd2012-12-18 14:30:41 +00003449 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3450 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3451 VTableUses.push_back(
3452 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3453 VTableUses.push_back(Record[Idx++]);
3454 }
3455 break;
3456
Guy Benyei11169dd2012-12-18 14:30:41 +00003457 case PENDING_IMPLICIT_INSTANTIATIONS:
3458 if (PendingInstantiations.size() % 2 != 0) {
3459 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003460 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003461 }
3462
3463 if (Record.size() % 2 != 0) {
3464 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003465 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003466 }
3467
3468 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3469 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3470 PendingInstantiations.push_back(
3471 ReadSourceLocation(F, Record, I).getRawEncoding());
3472 }
3473 break;
3474
3475 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003476 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003477 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003478 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003479 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003480 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3481 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3482 break;
3483
3484 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003485 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3486 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3487 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003488
3489 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003490
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 unsigned StartingID;
3492 if (!PP.getPreprocessingRecord())
3493 PP.createPreprocessingRecord();
3494 if (!PP.getPreprocessingRecord()->getExternalSource())
3495 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003496 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003498 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 F.BasePreprocessedEntityID = StartingID;
3500
3501 if (F.NumPreprocessedEntities > 0) {
3502 // Introduce the global -> local mapping for preprocessed entities in
3503 // this module.
3504 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003505
Guy Benyei11169dd2012-12-18 14:30:41 +00003506 // Introduce the local -> global mapping for preprocessed entities in
3507 // this module.
3508 F.PreprocessedEntityRemap.insertOrReplace(
3509 std::make_pair(LocalBasePreprocessedEntityID,
3510 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3511 }
3512
3513 break;
3514 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003515
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003516 case PPD_SKIPPED_RANGES: {
3517 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3518 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3519 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3520
3521 if (!PP.getPreprocessingRecord())
3522 PP.createPreprocessingRecord();
3523 if (!PP.getPreprocessingRecord()->getExternalSource())
3524 PP.getPreprocessingRecord()->SetExternalSource(*this);
3525 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3526 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003527
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003528 if (F.NumPreprocessedSkippedRanges > 0)
3529 GlobalSkippedRangeMap.insert(
3530 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3531 break;
3532 }
3533
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003534 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003535 if (Record.size() % 2 != 0) {
3536 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003538 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003539 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3540 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3541 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3542
3543 // If we've already loaded the decl, perform the updates when we finish
3544 // loading this block.
3545 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003546 PendingUpdateRecords.push_back(
3547 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003548 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003550
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003551 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 if (F.LocalNumObjCCategoriesInMap != 0) {
3553 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003554 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003555 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003556
Guy Benyei11169dd2012-12-18 14:30:41 +00003557 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003558 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003559 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003560
Guy Benyei11169dd2012-12-18 14:30:41 +00003561 case OBJC_CATEGORIES:
3562 F.ObjCCategories.swap(Record);
3563 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003564
Guy Benyei11169dd2012-12-18 14:30:41 +00003565 case CUDA_SPECIAL_DECL_REFS:
3566 // Later tables overwrite earlier ones.
3567 // FIXME: Modules will have trouble with this.
3568 CUDASpecialDeclRefs.clear();
3569 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3570 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3571 break;
3572
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003573 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003574 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003575 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003576 if (Record[0]) {
3577 F.HeaderFileInfoTable
3578 = HeaderFileInfoLookupTable::Create(
3579 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3580 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003581 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003583 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003584
Guy Benyei11169dd2012-12-18 14:30:41 +00003585 PP.getHeaderSearchInfo().SetExternalSource(this);
3586 if (!PP.getHeaderSearchInfo().getExternalLookup())
3587 PP.getHeaderSearchInfo().SetExternalLookup(this);
3588 }
3589 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003590
Guy Benyei11169dd2012-12-18 14:30:41 +00003591 case FP_PRAGMA_OPTIONS:
3592 // Later tables overwrite earlier ones.
3593 FPPragmaOptions.swap(Record);
3594 break;
3595
3596 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003597 for (unsigned I = 0, E = Record.size(); I != E; ) {
3598 auto Name = ReadString(Record, I);
3599 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003600 Opt.Supported = Record[I++] != 0;
3601 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003602 Opt.Avail = Record[I++];
3603 Opt.Core = Record[I++];
3604 }
3605 break;
3606
3607 case OPENCL_EXTENSION_TYPES:
3608 for (unsigned I = 0, E = Record.size(); I != E;) {
3609 auto TypeID = static_cast<::TypeID>(Record[I++]);
3610 auto *Type = GetType(TypeID).getTypePtr();
3611 auto NumExt = static_cast<unsigned>(Record[I++]);
3612 for (unsigned II = 0; II != NumExt; ++II) {
3613 auto Ext = ReadString(Record, I);
3614 OpenCLTypeExtMap[Type].insert(Ext);
3615 }
3616 }
3617 break;
3618
3619 case OPENCL_EXTENSION_DECLS:
3620 for (unsigned I = 0, E = Record.size(); I != E;) {
3621 auto DeclID = static_cast<::DeclID>(Record[I++]);
3622 auto *Decl = GetDecl(DeclID);
3623 auto NumExt = static_cast<unsigned>(Record[I++]);
3624 for (unsigned II = 0; II != NumExt; ++II) {
3625 auto Ext = ReadString(Record, I);
3626 OpenCLDeclExtMap[Decl].insert(Ext);
3627 }
3628 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003629 break;
3630
3631 case TENTATIVE_DEFINITIONS:
3632 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3633 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3634 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003635
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 case KNOWN_NAMESPACES:
3637 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3638 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3639 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003640
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003641 case UNDEFINED_BUT_USED:
3642 if (UndefinedButUsed.size() % 2 != 0) {
3643 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003644 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003645 }
3646
3647 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003648 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003649 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003650 }
3651 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003652 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3653 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003654 ReadSourceLocation(F, Record, I).getRawEncoding());
3655 }
3656 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003657
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003658 case DELETE_EXPRS_TO_ANALYZE:
3659 for (unsigned I = 0, N = Record.size(); I != N;) {
3660 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3661 const uint64_t Count = Record[I++];
3662 DelayedDeleteExprs.push_back(Count);
3663 for (uint64_t C = 0; C < Count; ++C) {
3664 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3665 bool IsArrayForm = Record[I++] == 1;
3666 DelayedDeleteExprs.push_back(IsArrayForm);
3667 }
3668 }
3669 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003670
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003671 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003672 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003673 // If we aren't loading a module (which has its own exports), make
3674 // all of the imported modules visible.
3675 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003676 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3677 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3678 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003679 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003680 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003681 if (DeserializationListener)
3682 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3683 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003684 }
3685 }
3686 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003687
Guy Benyei11169dd2012-12-18 14:30:41 +00003688 case MACRO_OFFSET: {
3689 if (F.LocalNumMacros != 0) {
3690 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003691 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003692 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003693 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003694 F.LocalNumMacros = Record[0];
3695 unsigned LocalBaseMacroID = Record[1];
3696 F.BaseMacroID = getTotalNumMacros();
3697
3698 if (F.LocalNumMacros > 0) {
3699 // Introduce the global -> local mapping for macros within this module.
3700 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3701
3702 // Introduce the local -> global mapping for macros within this module.
3703 F.MacroRemap.insertOrReplace(
3704 std::make_pair(LocalBaseMacroID,
3705 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003706
3707 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 }
3709 break;
3710 }
3711
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003712 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003713 LateParsedTemplates.append(Record.begin(), Record.end());
3714 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003715
3716 case OPTIMIZE_PRAGMA_OPTIONS:
3717 if (Record.size() != 1) {
3718 Error("invalid pragma optimize record");
3719 return Failure;
3720 }
3721 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3722 break;
Nico Weber72889432014-09-06 01:25:55 +00003723
Nico Weber779355f2016-03-02 23:22:00 +00003724 case MSSTRUCT_PRAGMA_OPTIONS:
3725 if (Record.size() != 1) {
3726 Error("invalid pragma ms_struct record");
3727 return Failure;
3728 }
3729 PragmaMSStructState = Record[0];
3730 break;
3731
Nico Weber42932312016-03-03 00:17:35 +00003732 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3733 if (Record.size() != 2) {
3734 Error("invalid pragma ms_struct record");
3735 return Failure;
3736 }
3737 PragmaMSPointersToMembersState = Record[0];
3738 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3739 break;
3740
Nico Weber72889432014-09-06 01:25:55 +00003741 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3742 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3743 UnusedLocalTypedefNameCandidates.push_back(
3744 getGlobalDeclID(F, Record[I]));
3745 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003746
3747 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3748 if (Record.size() != 1) {
3749 Error("invalid cuda pragma options record");
3750 return Failure;
3751 }
3752 ForceCUDAHostDeviceDepth = Record[0];
3753 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003754
3755 case PACK_PRAGMA_OPTIONS: {
3756 if (Record.size() < 3) {
3757 Error("invalid pragma pack record");
3758 return Failure;
3759 }
3760 PragmaPackCurrentValue = Record[0];
3761 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3762 unsigned NumStackEntries = Record[2];
3763 unsigned Idx = 3;
3764 // Reset the stack when importing a new module.
3765 PragmaPackStack.clear();
3766 for (unsigned I = 0; I < NumStackEntries; ++I) {
3767 PragmaPackStackEntry Entry;
3768 Entry.Value = Record[Idx++];
3769 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003770 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003771 PragmaPackStrings.push_back(ReadString(Record, Idx));
3772 Entry.SlotLabel = PragmaPackStrings.back();
3773 PragmaPackStack.push_back(Entry);
3774 }
3775 break;
3776 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003777 }
3778 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003779}
3780
Richard Smith37a93df2017-02-18 00:32:02 +00003781void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3782 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3783
3784 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003785 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003786 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3787 F.ModuleOffsetMap = StringRef();
3788
3789 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3790 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3791 F.SLocRemap.insert(std::make_pair(0U, 0));
3792 F.SLocRemap.insert(std::make_pair(2U, 1));
3793 }
3794
3795 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003796 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003797 RemapBuilder SLocRemap(F.SLocRemap);
3798 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3799 RemapBuilder MacroRemap(F.MacroRemap);
3800 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3801 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3802 RemapBuilder SelectorRemap(F.SelectorRemap);
3803 RemapBuilder DeclRemap(F.DeclRemap);
3804 RemapBuilder TypeRemap(F.TypeRemap);
3805
3806 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003807 // FIXME: Looking up dependency modules by filename is horrible. Let's
3808 // start fixing this with prebuilt and explicit modules and see how it
3809 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003810 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003811 ModuleKind Kind = static_cast<ModuleKind>(
3812 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003813 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3814 StringRef Name = StringRef((const char*)Data, Len);
3815 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003816 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3817 ? ModuleMgr.lookupByModuleName(Name)
3818 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003819 if (!OM) {
3820 std::string Msg =
3821 "SourceLocation remap refers to unknown module, cannot find ";
Benjamin Krameradcd0262020-01-28 20:23:46 +01003822 Msg.append(std::string(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003823 Error(Msg);
3824 return;
3825 }
3826
3827 uint32_t SLocOffset =
3828 endian::readNext<uint32_t, little, unaligned>(Data);
3829 uint32_t IdentifierIDOffset =
3830 endian::readNext<uint32_t, little, unaligned>(Data);
3831 uint32_t MacroIDOffset =
3832 endian::readNext<uint32_t, little, unaligned>(Data);
3833 uint32_t PreprocessedEntityIDOffset =
3834 endian::readNext<uint32_t, little, unaligned>(Data);
3835 uint32_t SubmoduleIDOffset =
3836 endian::readNext<uint32_t, little, unaligned>(Data);
3837 uint32_t SelectorIDOffset =
3838 endian::readNext<uint32_t, little, unaligned>(Data);
3839 uint32_t DeclIDOffset =
3840 endian::readNext<uint32_t, little, unaligned>(Data);
3841 uint32_t TypeIndexOffset =
3842 endian::readNext<uint32_t, little, unaligned>(Data);
3843
3844 uint32_t None = std::numeric_limits<uint32_t>::max();
3845
3846 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3847 RemapBuilder &Remap) {
3848 if (Offset != None)
3849 Remap.insert(std::make_pair(Offset,
3850 static_cast<int>(BaseOffset - Offset)));
3851 };
3852 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3853 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3854 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3855 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3856 PreprocessedEntityRemap);
3857 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3858 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3859 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3860 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3861
3862 // Global -> local mappings.
3863 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3864 }
3865}
3866
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003867ASTReader::ASTReadResult
3868ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3869 const ModuleFile *ImportedBy,
3870 unsigned ClientLoadCapabilities) {
3871 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003872 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003873
3874 // Try to resolve ModuleName in the current header search context and
3875 // verify that it is found in the same module map file as we saved. If the
3876 // top-level AST file is a main file, skip this check because there is no
3877 // usable header search context.
3878 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003879 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003880 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003881 // An implicitly-loaded module file should have its module listed in some
3882 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003883 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003884 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3885 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003886 // Don't emit module relocation error if we have -fno-validate-pch
3887 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003888 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003889 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003890 // This module was defined by an imported (explicit) module.
3891 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3892 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003893 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003894 // This module was built with a different module map.
3895 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003896 << F.ModuleName << F.FileName
3897 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3898 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003899 // In case it was imported by a PCH, there's a chance the user is
3900 // just missing to include the search path to the directory containing
3901 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003902 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003903 Diag(diag::note_imported_by_pch_module_not_found)
3904 << llvm::sys::path::parent_path(F.ModuleMapPath);
3905 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003906 }
3907 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003908 }
3909
Richard Smithe842a472014-10-22 02:05:46 +00003910 assert(M->Name == F.ModuleName && "found module with different name");
3911
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003912 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003913 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3914 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003915 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003916 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3917 "top-level import should be verified");
3918 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003919 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3920 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003921 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3922 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003923 return OutOfDate;
3924 }
3925
3926 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3927 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3928 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003929 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003930 auto F = FileMgr.getFile(Filename, false, false);
3931 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003932 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3933 Error("could not find file '" + Filename +"' referenced by AST file");
3934 return OutOfDate;
3935 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003936 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003937 }
3938
3939 // Check any additional module map files (e.g. module.private.modulemap)
3940 // that are not in the pcm.
3941 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003942 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003943 // Remove files that match
3944 // Note: SmallPtrSet::erase is really remove
3945 if (!AdditionalStoredMaps.erase(ModMap)) {
3946 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3947 Diag(diag::err_module_different_modmap)
3948 << F.ModuleName << /*new*/0 << ModMap->getName();
3949 return OutOfDate;
3950 }
3951 }
3952 }
3953
3954 // Check any additional module map files that are in the pcm, but not
3955 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003956 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003957 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3958 Diag(diag::err_module_different_modmap)
3959 << F.ModuleName << /*not new*/1 << ModMap->getName();
3960 return OutOfDate;
3961 }
3962 }
3963
3964 if (Listener)
3965 Listener->ReadModuleMapFile(F.ModuleMapPath);
3966 return Success;
3967}
3968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003969/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003970static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3971 // Find the entry for this selector in the method pool.
3972 Sema::GlobalMethodPool::iterator Known
3973 = S.MethodPool.find(Method->getSelector());
3974 if (Known == S.MethodPool.end())
3975 return;
3976
3977 // Retrieve the appropriate method list.
3978 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3979 : Known->second.second;
3980 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003981 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003982 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003983 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003984 Found = true;
3985 } else {
3986 // Keep searching.
3987 continue;
3988 }
3989 }
3990
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003991 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003992 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003993 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003994 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003995 }
3996}
3997
Richard Smithde711422015-04-23 21:20:19 +00003998void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003999 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00004000 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00004001 bool wasHidden = D->isHidden();
4002 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00004003
Vedant Kumar48b4f762018-04-14 01:40:48 +00004004 if (wasHidden && SemaObj) {
4005 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00004006 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004007 }
4008 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 }
4010}
4011
Richard Smith49f906a2014-03-01 00:08:04 +00004012void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004013 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004014 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004015 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004016 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004017 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004018 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004019 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00004020
4021 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00004022 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 // there is nothing more to do.
4024 continue;
4025 }
Richard Smith49f906a2014-03-01 00:08:04 +00004026
Guy Benyei11169dd2012-12-18 14:30:41 +00004027 if (!Mod->isAvailable()) {
4028 // Modules that aren't available cannot be made visible.
4029 continue;
4030 }
4031
4032 // Update the module's name visibility.
4033 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00004034
Guy Benyei11169dd2012-12-18 14:30:41 +00004035 // If we've already deserialized any names from this module,
4036 // mark them as visible.
4037 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
4038 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00004039 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00004041 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00004042 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
4043 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00004044 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00004045
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004047 SmallVector<Module *, 16> Exports;
4048 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004049 for (SmallVectorImpl<Module *>::iterator
4050 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
4051 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00004052 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00004053 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004054 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004055 }
4056}
4057
Richard Smith6561f922016-09-12 21:06:40 +00004058/// We've merged the definition \p MergedDef into the existing definition
4059/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
4060/// visible.
4061void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
4062 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00004063 if (Def->isHidden()) {
4064 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004065 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00004066 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004067 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004068 getContext().mergeDefinitionIntoModule(
4069 Def, MergedDef->getImportedOwningModule(),
4070 /*NotifyListeners*/ false);
4071 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004072 }
Richard Smith6561f922016-09-12 21:06:40 +00004073 }
4074}
4075
Douglas Gregore060e572013-01-25 01:03:03 +00004076bool ASTReader::loadGlobalIndex() {
4077 if (GlobalIndex)
4078 return false;
4079
4080 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004081 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004082 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004083
Douglas Gregore060e572013-01-25 01:03:03 +00004084 // Try to load the global index.
4085 TriedLoadingGlobalIndex = true;
4086 StringRef ModuleCachePath
4087 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004088 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4089 GlobalModuleIndex::readIndex(ModuleCachePath);
4090 if (llvm::Error Err = std::move(Result.second)) {
4091 assert(!Result.first);
4092 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004093 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004094 }
Douglas Gregore060e572013-01-25 01:03:03 +00004095
4096 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004097 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004098 return false;
4099}
4100
4101bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004102 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004103 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4104}
4105
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004106static void updateModuleTimestamp(ModuleFile &MF) {
4107 // Overwrite the timestamp file contents so that file's mtime changes.
4108 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004109 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004110 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004111 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004112 return;
4113 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004114 OS.close();
4115 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004116}
4117
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004118/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004119/// cursor into the start of the given block ID, returning false on success and
4120/// true on failure.
4121static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004122 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004123 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4124 if (!MaybeEntry) {
4125 // FIXME this drops errors on the floor.
4126 consumeError(MaybeEntry.takeError());
4127 return true;
4128 }
4129 llvm::BitstreamEntry Entry = MaybeEntry.get();
4130
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004131 switch (Entry.Kind) {
4132 case llvm::BitstreamEntry::Error:
4133 case llvm::BitstreamEntry::EndBlock:
4134 return true;
4135
4136 case llvm::BitstreamEntry::Record:
4137 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004138 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4139 break;
4140 else {
4141 // FIXME this drops errors on the floor.
4142 consumeError(Skipped.takeError());
4143 return true;
4144 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004145
4146 case llvm::BitstreamEntry::SubBlock:
4147 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004148 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4149 // FIXME this drops the error on the floor.
4150 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004151 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004152 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004153 // Found it!
4154 return false;
4155 }
4156
JF Bastien0e828952019-06-26 19:50:12 +00004157 if (llvm::Error Err = Cursor.SkipBlock()) {
4158 // FIXME this drops the error on the floor.
4159 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004160 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004161 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004162 }
4163 }
4164}
4165
Benjamin Kramer0772c422016-02-13 13:42:54 +00004166ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 ModuleKind Type,
4168 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004169 unsigned ClientLoadCapabilities,
4170 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004171 llvm::SaveAndRestore<SourceLocation>
4172 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4173
Richard Smithd1c46742014-04-30 02:24:17 +00004174 // Defer any pending actions until we get to the end of reading the AST file.
4175 Deserializing AnASTFile(this);
4176
Guy Benyei11169dd2012-12-18 14:30:41 +00004177 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004178 unsigned PreviousGeneration = 0;
4179 if (ContextObj)
4180 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004181
4182 unsigned NumModules = ModuleMgr.size();
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004183 auto removeModulesAndReturn = [&](ASTReadResult ReadResult) {
4184 assert(ReadResult && "expected to return error");
Duncan P. N. Exon Smith8e9e4332019-11-10 10:31:03 -08004185 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004186 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004187 ? &PP.getHeaderSearchInfo().getModuleMap()
4188 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004189
4190 // If we find that any modules are unusable, the global index is going
4191 // to be out-of-date. Just remove it.
4192 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004193 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004194 return ReadResult;
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004195 };
4196
4197 SmallVector<ImportedModule, 4> Loaded;
4198 switch (ASTReadResult ReadResult =
4199 ReadASTCore(FileName, Type, ImportLoc,
4200 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4201 ASTFileSignature(), ClientLoadCapabilities)) {
4202 case Failure:
4203 case Missing:
4204 case OutOfDate:
4205 case VersionMismatch:
4206 case ConfigurationMismatch:
4207 case HadErrors:
4208 return removeModulesAndReturn(ReadResult);
Guy Benyei11169dd2012-12-18 14:30:41 +00004209 case Success:
4210 break;
4211 }
4212
4213 // Here comes stuff that we only do once the entire chain is loaded.
4214
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004215 // Load the AST blocks of all of the modules that we loaded. We can still
4216 // hit errors parsing the ASTs at this point.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004217 for (ImportedModule &M : Loaded) {
4218 ModuleFile &F = *M.Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004219
4220 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004221 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004222 return removeModulesAndReturn(Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00004223
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08004224 // The AST block should always have a definition for the main module.
4225 if (F.isModule() && !F.DidReadTopLevelSubmodule) {
4226 Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
4227 return removeModulesAndReturn(Failure);
4228 }
4229
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004230 // Read the extension blocks.
4231 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4232 if (ASTReadResult Result = ReadExtensionBlock(F))
Duncan P. N. Exon Smithc46b3a22019-11-10 10:42:29 -08004233 return removeModulesAndReturn(Result);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004234 }
4235
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004236 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004237 // bits of all files we've seen.
4238 F.GlobalBitOffset = TotalModulesSizeInBits;
4239 TotalModulesSizeInBits += F.SizeInBits;
4240 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
Duncan P. N. Exon Smith01782c32019-11-10 10:50:12 -08004241 }
4242
4243 // Preload source locations and interesting indentifiers.
4244 for (ImportedModule &M : Loaded) {
4245 ModuleFile &F = *M.Mod;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004246
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004248 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4249 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 // Load it through the SourceManager and don't call ReadSLocEntry()
4251 // directly because the entry may have already been loaded in which case
4252 // calling ReadSLocEntry() directly would trigger an assertion in
4253 // SourceManager.
4254 SourceMgr.getLoadedSLocEntryByID(Index);
4255 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004256
Richard Smithea741482017-05-01 22:10:47 +00004257 // Map the original source file ID into the ID space of the current
4258 // compilation.
4259 if (F.OriginalSourceFileID.isValid()) {
4260 F.OriginalSourceFileID = FileID::get(
4261 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4262 }
4263
Richard Smith33e0f7e2015-07-22 02:08:40 +00004264 // Preload all the pending interesting identifiers by marking them out of
4265 // date.
4266 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004267 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004268 F.IdentifierTableData + Offset);
4269
4270 ASTIdentifierLookupTrait Trait(*this, F);
4271 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4272 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004273 auto &II = PP.getIdentifierTable().getOwn(Key);
4274 II.setOutOfDate(true);
4275
4276 // Mark this identifier as being from an AST file so that we can track
4277 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004278 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004279
4280 // Associate the ID with the identifier so that the writer can reuse it.
4281 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4282 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004283 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 }
4285
Douglas Gregor603cd862013-03-22 18:50:14 +00004286 // Setup the import locations and notify the module manager that we've
4287 // committed to these module files.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004288 for (ImportedModule &M : Loaded) {
4289 ModuleFile &F = *M.Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004290
4291 ModuleMgr.moduleFileAccepted(&F);
4292
4293 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004294 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004295 // FIXME: We assume that locations from PCH / preamble do not need
4296 // any translation.
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004297 if (!M.ImportedBy)
4298 F.ImportLoc = M.ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 else
Duncan P. N. Exon Smithbfd58fc2019-11-11 15:42:25 -08004300 F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004301 }
4302
Richard Smithdbafb6c2017-06-29 23:23:46 +00004303 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004304 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4305 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004306 // Mark all of the identifiers in the identifier table as being out of date,
4307 // so that various accessors know to check the loaded modules when the
4308 // identifier is used.
4309 //
4310 // For C++ modules, we don't need information on many identifiers (just
4311 // those that provide macros or are poisoned), so we mark all of
4312 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004313 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4314 IdEnd = PP.getIdentifierTable().end();
4315 Id != IdEnd; ++Id)
4316 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004317 }
Manman Rena0f31a02016-04-29 19:04:05 +00004318 // Mark selectors as out of date.
4319 for (auto Sel : SelectorGeneration)
4320 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004321
Guy Benyei11169dd2012-12-18 14:30:41 +00004322 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004323 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4324 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004325 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4326 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004327
4328 switch (Unresolved.Kind) {
4329 case UnresolvedModuleRef::Conflict:
4330 if (ResolvedMod) {
4331 Module::Conflict Conflict;
4332 Conflict.Other = ResolvedMod;
4333 Conflict.Message = Unresolved.String.str();
4334 Unresolved.Mod->Conflicts.push_back(Conflict);
4335 }
4336 continue;
4337
4338 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004340 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004342
Douglas Gregorfb912652013-03-20 21:10:35 +00004343 case UnresolvedModuleRef::Export:
4344 if (ResolvedMod || Unresolved.IsWildcard)
4345 Unresolved.Mod->Exports.push_back(
4346 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4347 continue;
4348 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004350 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004351
Graydon Hoaree7196af2016-12-09 21:45:49 +00004352 if (Imported)
4353 Imported->append(ImportedModules.begin(),
4354 ImportedModules.end());
4355
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004356 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4357 // Might be unnecessary as use declarations are only used to build the
4358 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004359
Richard Smithdbafb6c2017-06-29 23:23:46 +00004360 if (ContextObj)
4361 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004362
Richard Smith3d8e97e2013-10-18 06:54:39 +00004363 if (SemaObj)
4364 UpdateSema();
4365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 if (DeserializationListener)
4367 DeserializationListener->ReaderInitialized(this);
4368
4369 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004370 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 // If this AST file is a precompiled preamble, then set the
4372 // preamble file ID of the source manager to the file source file
4373 // from which the preamble was built.
4374 if (Type == MK_Preamble) {
4375 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4376 } else if (Type == MK_MainFile) {
4377 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4378 }
4379 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004380
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 // For any Objective-C class definitions we have already loaded, make sure
4382 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004383 if (ContextObj) {
4384 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4385 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4386 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004387 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004388 }
4389 }
Douglas Gregore060e572013-01-25 01:03:03 +00004390
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004391 if (PP.getHeaderSearchInfo()
4392 .getHeaderSearchOpts()
4393 .ModulesValidateOncePerBuildSession) {
4394 // Now we are certain that the module and all modules it depends on are
4395 // up to date. Create or update timestamp files for modules that are
4396 // located in the module cache (not for PCH files that could be anywhere
4397 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004398 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4399 ImportedModule &M = Loaded[I];
4400 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004401 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004402 }
4403 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004404 }
4405
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 return Success;
4407}
4408
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004409static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004410
JF Bastien0e828952019-06-26 19:50:12 +00004411/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4412static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4413 // FIXME checking magic headers is done in other places such as
4414 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4415 // always done the same. Unify it all with a helper.
4416 if (!Stream.canSkipToPos(4))
4417 return llvm::createStringError(std::errc::illegal_byte_sequence,
4418 "file too small to contain AST file magic");
4419 for (unsigned C : {'C', 'P', 'C', 'H'})
4420 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4421 if (Res.get() != C)
4422 return llvm::createStringError(
4423 std::errc::illegal_byte_sequence,
4424 "file doesn't start with AST file magic");
4425 } else
4426 return Res.takeError();
4427 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004428}
4429
Richard Smith0f99d6a2015-08-09 08:48:41 +00004430static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4431 switch (Kind) {
4432 case MK_PCH:
4433 return 0; // PCH
4434 case MK_ImplicitModule:
4435 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004436 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004437 return 1; // module
4438 case MK_MainFile:
4439 case MK_Preamble:
4440 return 2; // main source file
4441 }
4442 llvm_unreachable("unknown module kind");
4443}
4444
Guy Benyei11169dd2012-12-18 14:30:41 +00004445ASTReader::ASTReadResult
4446ASTReader::ReadASTCore(StringRef FileName,
4447 ModuleKind Type,
4448 SourceLocation ImportLoc,
4449 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004450 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004451 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004452 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004453 unsigned ClientLoadCapabilities) {
4454 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004455 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004456 ModuleManager::AddModuleResult AddResult
4457 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004458 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004459 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004460 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004461
Douglas Gregor7029ce12013-03-19 00:28:20 +00004462 switch (AddResult) {
4463 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004464 Diag(diag::remark_module_import)
4465 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4466 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004467 return Success;
4468
4469 case ModuleManager::NewlyLoaded:
4470 // Load module file below.
4471 break;
4472
4473 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004474 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004475 // it.
4476 if (ClientLoadCapabilities & ARR_Missing)
4477 return Missing;
4478
4479 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004480 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004481 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004482 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004483 return Failure;
4484
4485 case ModuleManager::OutOfDate:
4486 // We couldn't load the module file because it is out-of-date. If the
4487 // client can handle out-of-date, return it.
4488 if (ClientLoadCapabilities & ARR_OutOfDate)
4489 return OutOfDate;
4490
4491 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004492 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004493 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004494 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 return Failure;
4496 }
4497
Douglas Gregor7029ce12013-03-19 00:28:20 +00004498 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004499
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004500 bool ShouldFinalizePCM = false;
4501 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4502 auto &MC = getModuleManager().getModuleCache();
4503 if (ShouldFinalizePCM)
4504 MC.finalizePCM(FileName);
4505 else
Volodymyr Sapsai83f4c3a2020-01-16 17:12:41 -08004506 MC.tryToRemovePCM(FileName);
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004507 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004509 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004510 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004511 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004512
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004514 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4515 Diag(diag::err_module_file_invalid)
4516 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 return Failure;
4518 }
4519
4520 // This is used for compatibility with older PCH formats.
4521 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004522 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004523 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4524 if (!MaybeEntry) {
4525 Error(MaybeEntry.takeError());
4526 return Failure;
4527 }
4528 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004529
Chris Lattnerefa77172013-01-20 00:00:22 +00004530 switch (Entry.Kind) {
4531 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004532 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004533 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004534 Error("invalid record at top-level of AST file");
4535 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004536
Chris Lattnerefa77172013-01-20 00:00:22 +00004537 case llvm::BitstreamEntry::SubBlock:
4538 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 }
4540
Chris Lattnerefa77172013-01-20 00:00:22 +00004541 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 case CONTROL_BLOCK_ID:
4543 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004544 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004546 // Check that we didn't try to load a non-module AST file as a module.
4547 //
4548 // FIXME: Should we also perform the converse check? Loading a module as
4549 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004550 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4551 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004552 F.ModuleName.empty()) {
4553 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4554 if (Result != OutOfDate ||
4555 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4556 Diag(diag::err_module_file_not_module) << FileName;
4557 return Result;
4558 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 break;
4560
4561 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004562 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 case OutOfDate: return OutOfDate;
4564 case VersionMismatch: return VersionMismatch;
4565 case ConfigurationMismatch: return ConfigurationMismatch;
4566 case HadErrors: return HadErrors;
4567 }
4568 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004569
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 case AST_BLOCK_ID:
4571 if (!HaveReadControlBlock) {
4572 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004573 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 return VersionMismatch;
4575 }
4576
4577 // Record that we've loaded this module.
4578 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004579 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 return Success;
4581
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004582 case UNHASHED_CONTROL_BLOCK_ID:
4583 // This block is handled using look-ahead during ReadControlBlock. We
4584 // shouldn't get here!
4585 Error("malformed block record in AST file");
4586 return Failure;
4587
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 default:
JF Bastien0e828952019-06-26 19:50:12 +00004589 if (llvm::Error Err = Stream.SkipBlock()) {
4590 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004591 return Failure;
4592 }
4593 break;
4594 }
4595 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004596
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004597 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004598}
4599
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004600ASTReader::ASTReadResult
4601ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4602 unsigned ClientLoadCapabilities) {
4603 const HeaderSearchOptions &HSOpts =
4604 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4605 bool AllowCompatibleConfigurationMismatch =
4606 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4607
4608 ASTReadResult Result = readUnhashedControlBlockImpl(
4609 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4610 Listener.get(),
4611 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4612
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004613 // If F was directly imported by another module, it's implicitly validated by
4614 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004615 if (DisableValidation || WasImportedBy ||
4616 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4617 return Success;
4618
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004619 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004620 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004621 return Failure;
4622 }
4623
4624 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004625 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004626 // with it; we can only load a single version of each module.
4627 //
4628 // This can happen when a module is imported in two contexts: in one, as a
4629 // user module; in another, as a system module (due to an import from
4630 // another module marked with the [system] flag). It usually indicates a
4631 // bug in the module map: this module should also be marked with [system].
4632 //
4633 // If -Wno-system-headers (the default), and the first import is as a
4634 // system module, then validation will fail during the as-user import,
4635 // since -Werror flags won't have been validated. However, it's reasonable
4636 // to treat this consistently as a system module.
4637 //
4638 // If -Wsystem-headers, the PCM on disk was built with
4639 // -Wno-system-headers, and the first import is as a user module, then
4640 // validation will fail during the as-system import since the PCM on disk
4641 // doesn't guarantee that -Werror was respected. However, the -Werror
4642 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004643 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004644 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4645 return Success;
4646 }
4647 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004648
4649 return Result;
4650}
4651
4652ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4653 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4654 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4655 bool ValidateDiagnosticOptions) {
4656 // Initialize a stream.
4657 BitstreamCursor Stream(StreamData);
4658
4659 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004660 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4661 // FIXME this drops the error on the floor.
4662 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004663 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004664 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004665
4666 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4667 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4668 return Failure;
4669
4670 // Read all of the records in the options block.
4671 RecordData Record;
4672 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004673 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004674 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4675 if (!MaybeEntry) {
4676 // FIXME this drops the error on the floor.
4677 consumeError(MaybeEntry.takeError());
4678 return Failure;
4679 }
4680 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004681
4682 switch (Entry.Kind) {
4683 case llvm::BitstreamEntry::Error:
4684 case llvm::BitstreamEntry::SubBlock:
4685 return Failure;
4686
4687 case llvm::BitstreamEntry::EndBlock:
4688 return Result;
4689
4690 case llvm::BitstreamEntry::Record:
4691 // The interesting case.
4692 break;
4693 }
4694
4695 // Read and process a record.
4696 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004697 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4698 if (!MaybeRecordType) {
4699 // FIXME this drops the error.
4700 return Failure;
4701 }
4702 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004703 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004704 if (F)
4705 std::copy(Record.begin(), Record.end(), F->Signature.data());
4706 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004707 case DIAGNOSTIC_OPTIONS: {
4708 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4709 if (Listener && ValidateDiagnosticOptions &&
4710 !AllowCompatibleConfigurationMismatch &&
4711 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004712 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004713 break;
4714 }
4715 case DIAG_PRAGMA_MAPPINGS:
4716 if (!F)
4717 break;
4718 if (F->PragmaDiagMappings.empty())
4719 F->PragmaDiagMappings.swap(Record);
4720 else
4721 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4722 Record.begin(), Record.end());
4723 break;
4724 }
4725 }
4726}
4727
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004728/// Parse a record and blob containing module file extension metadata.
4729static bool parseModuleFileExtensionMetadata(
4730 const SmallVectorImpl<uint64_t> &Record,
4731 StringRef Blob,
4732 ModuleFileExtensionMetadata &Metadata) {
4733 if (Record.size() < 4) return true;
4734
4735 Metadata.MajorVersion = Record[0];
4736 Metadata.MinorVersion = Record[1];
4737
4738 unsigned BlockNameLen = Record[2];
4739 unsigned UserInfoLen = Record[3];
4740
4741 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4742
4743 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4744 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4745 Blob.data() + BlockNameLen + UserInfoLen);
4746 return false;
4747}
4748
4749ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4750 BitstreamCursor &Stream = F.Stream;
4751
4752 RecordData Record;
4753 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004754 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4755 if (!MaybeEntry) {
4756 Error(MaybeEntry.takeError());
4757 return Failure;
4758 }
4759 llvm::BitstreamEntry Entry = MaybeEntry.get();
4760
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004761 switch (Entry.Kind) {
4762 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004763 if (llvm::Error Err = Stream.SkipBlock()) {
4764 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004765 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004766 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004767 continue;
4768
4769 case llvm::BitstreamEntry::EndBlock:
4770 return Success;
4771
4772 case llvm::BitstreamEntry::Error:
4773 return HadErrors;
4774
4775 case llvm::BitstreamEntry::Record:
4776 break;
4777 }
4778
4779 Record.clear();
4780 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004781 Expected<unsigned> MaybeRecCode =
4782 Stream.readRecord(Entry.ID, Record, &Blob);
4783 if (!MaybeRecCode) {
4784 Error(MaybeRecCode.takeError());
4785 return Failure;
4786 }
4787 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004788 case EXTENSION_METADATA: {
4789 ModuleFileExtensionMetadata Metadata;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004790 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata)) {
4791 Error("malformed EXTENSION_METADATA in AST file");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004792 return Failure;
Duncan P. N. Exon Smith8e2c1922019-11-10 11:07:20 -08004793 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004794
4795 // Find a module file extension with this block name.
4796 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4797 if (Known == ModuleFileExtensions.end()) break;
4798
4799 // Form a reader.
4800 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4801 F, Stream)) {
4802 F.ExtensionReaders.push_back(std::move(Reader));
4803 }
4804
4805 break;
4806 }
4807 }
4808 }
4809
4810 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004811}
4812
Richard Smitha7e2cc62015-05-01 01:53:09 +00004813void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004814 assert(ContextObj && "no context to initialize");
4815 ASTContext &Context = *ContextObj;
4816
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 // If there's a listener, notify them that we "read" the translation unit.
4818 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004819 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 Context.getTranslationUnitDecl());
4821
Guy Benyei11169dd2012-12-18 14:30:41 +00004822 // FIXME: Find a better way to deal with collisions between these
4823 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004824
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 // Load the special types.
4826 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4827 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4828 if (!Context.CFConstantStringTypeDecl)
4829 Context.setCFConstantStringType(GetType(String));
4830 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004831
Guy Benyei11169dd2012-12-18 14:30:41 +00004832 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4833 QualType FileType = GetType(File);
4834 if (FileType.isNull()) {
4835 Error("FILE type is NULL");
4836 return;
4837 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004838
Guy Benyei11169dd2012-12-18 14:30:41 +00004839 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004840 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 Context.setFILEDecl(Typedef->getDecl());
4842 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004843 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004844 if (!Tag) {
4845 Error("Invalid FILE type in AST file");
4846 return;
4847 }
4848 Context.setFILEDecl(Tag->getDecl());
4849 }
4850 }
4851 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004852
Guy Benyei11169dd2012-12-18 14:30:41 +00004853 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4854 QualType Jmp_bufType = GetType(Jmp_buf);
4855 if (Jmp_bufType.isNull()) {
4856 Error("jmp_buf type is NULL");
4857 return;
4858 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004859
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004861 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 Context.setjmp_bufDecl(Typedef->getDecl());
4863 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004864 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 if (!Tag) {
4866 Error("Invalid jmp_buf type in AST file");
4867 return;
4868 }
4869 Context.setjmp_bufDecl(Tag->getDecl());
4870 }
4871 }
4872 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004873
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4875 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4876 if (Sigjmp_bufType.isNull()) {
4877 Error("sigjmp_buf type is NULL");
4878 return;
4879 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004880
Guy Benyei11169dd2012-12-18 14:30:41 +00004881 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004882 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 Context.setsigjmp_bufDecl(Typedef->getDecl());
4884 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004885 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004886 assert(Tag && "Invalid sigjmp_buf type in AST file");
4887 Context.setsigjmp_bufDecl(Tag->getDecl());
4888 }
4889 }
4890 }
4891
4892 if (unsigned ObjCIdRedef
4893 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4894 if (Context.ObjCIdRedefinitionType.isNull())
4895 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4896 }
4897
4898 if (unsigned ObjCClassRedef
4899 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4900 if (Context.ObjCClassRedefinitionType.isNull())
4901 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4902 }
4903
4904 if (unsigned ObjCSelRedef
4905 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4906 if (Context.ObjCSelRedefinitionType.isNull())
4907 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4908 }
4909
4910 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4911 QualType Ucontext_tType = GetType(Ucontext_t);
4912 if (Ucontext_tType.isNull()) {
4913 Error("ucontext_t type is NULL");
4914 return;
4915 }
4916
4917 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004918 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004919 Context.setucontext_tDecl(Typedef->getDecl());
4920 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004921 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 assert(Tag && "Invalid ucontext_t type in AST file");
4923 Context.setucontext_tDecl(Tag->getDecl());
4924 }
4925 }
4926 }
4927 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004928
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4930
4931 // If there were any CUDA special declarations, deserialize them.
4932 if (!CUDASpecialDeclRefs.empty()) {
4933 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4934 Context.setcudaConfigureCallDecl(
4935 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4936 }
Richard Smith56be7542014-03-21 00:33:59 +00004937
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004939 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004940 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004941 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004942 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004943 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004944 if (Import.ImportLoc.isValid())
4945 PP.makeModuleVisible(Imported, Import.ImportLoc);
4946 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004947 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004948 }
4949 ImportedModules.clear();
4950}
4951
4952void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004953 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004954}
4955
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004956/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004957/// else returns 0.
4958static ASTFileSignature readASTFileSignature(StringRef PCH) {
4959 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004960 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4961 // FIXME this drops the error on the floor.
4962 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004963 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004964 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004965
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004966 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4967 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004968 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004969
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004970 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004971 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004972 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004973 Expected<llvm::BitstreamEntry> MaybeEntry =
4974 Stream.advanceSkippingSubblocks();
4975 if (!MaybeEntry) {
4976 // FIXME this drops the error on the floor.
4977 consumeError(MaybeEntry.takeError());
4978 return ASTFileSignature();
4979 }
4980 llvm::BitstreamEntry Entry = MaybeEntry.get();
4981
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004982 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004983 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004984
4985 Record.clear();
4986 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004987 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4988 if (!MaybeRecord) {
4989 // FIXME this drops the error on the floor.
4990 consumeError(MaybeRecord.takeError());
4991 return ASTFileSignature();
4992 }
4993 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004994 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4995 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004996 }
4997}
4998
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004999/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00005000/// directly from the AST file, without actually loading the AST
5001/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005002std::string ASTReader::getOriginalSourceFile(
5003 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005004 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00005006 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00005008 Diags.Report(diag::err_fe_unable_to_read_pch_file)
5009 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00005010 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 }
5012
5013 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00005014 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00005015
5016 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005017 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5018 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005019 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005021
Chris Lattnere7b154b2013-01-19 21:39:22 +00005022 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005023 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005024 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005025 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00005026 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005027
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005028 // Scan for ORIGINAL_FILE inside the control block.
5029 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005030 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005031 Expected<llvm::BitstreamEntry> MaybeEntry =
5032 Stream.advanceSkippingSubblocks();
5033 if (!MaybeEntry) {
5034 // FIXME this drops errors on the floor.
5035 consumeError(MaybeEntry.takeError());
5036 return std::string();
5037 }
5038 llvm::BitstreamEntry Entry = MaybeEntry.get();
5039
Chris Lattnere7b154b2013-01-19 21:39:22 +00005040 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00005041 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005042
Chris Lattnere7b154b2013-01-19 21:39:22 +00005043 if (Entry.Kind != llvm::BitstreamEntry::Record) {
5044 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005045 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00005046 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005047
Guy Benyei11169dd2012-12-18 14:30:41 +00005048 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005049 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005050 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
5051 if (!MaybeRecord) {
5052 // FIXME this drops the errors on the floor.
5053 consumeError(MaybeRecord.takeError());
5054 return std::string();
5055 }
5056 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00005057 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005059}
5060
5061namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005062
Guy Benyei11169dd2012-12-18 14:30:41 +00005063 class SimplePCHValidator : public ASTReaderListener {
5064 const LangOptions &ExistingLangOpts;
5065 const TargetOptions &ExistingTargetOpts;
5066 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005067 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005069
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 public:
5071 SimplePCHValidator(const LangOptions &ExistingLangOpts,
5072 const TargetOptions &ExistingTargetOpts,
5073 const PreprocessorOptions &ExistingPPOpts,
Benjamin Krameradcd0262020-01-28 20:23:46 +01005074 StringRef ExistingModuleCachePath, FileManager &FileMgr)
5075 : ExistingLangOpts(ExistingLangOpts),
5076 ExistingTargetOpts(ExistingTargetOpts),
5077 ExistingPPOpts(ExistingPPOpts),
5078 ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005079
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005080 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5081 bool AllowCompatibleDifferences) override {
5082 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5083 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005085
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005086 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5087 bool AllowCompatibleDifferences) override {
5088 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5089 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005091
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005092 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5093 StringRef SpecificModuleCachePath,
5094 bool Complain) override {
5095 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5096 ExistingModuleCachePath,
5097 nullptr, ExistingLangOpts);
5098 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005099
Craig Topper3e89dfe2014-03-13 02:13:41 +00005100 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5101 bool Complain,
5102 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005103 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005104 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005105 }
5106 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005107
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005108} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005109
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005110bool ASTReader::readASTFileControlBlock(
5111 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005112 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005113 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005114 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005116 // FIXME: This allows use of the VFS; we do not allow use of the
5117 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005118 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 if (!Buffer) {
5120 return true;
5121 }
5122
5123 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005124 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5125 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005126
5127 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005128 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5129 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005131 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005132
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005133 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005134 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005135 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005136
5137 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005138 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005139 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005140 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005141
Guy Benyei11169dd2012-12-18 14:30:41 +00005142 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005143 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005144 bool DoneWithControlBlock = false;
5145 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005146 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5147 if (!MaybeEntry) {
5148 // FIXME this drops the error on the floor.
5149 consumeError(MaybeEntry.takeError());
5150 return true;
5151 }
5152 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005153
5154 switch (Entry.Kind) {
5155 case llvm::BitstreamEntry::SubBlock: {
5156 switch (Entry.ID) {
5157 case OPTIONS_BLOCK_ID: {
5158 std::string IgnoredSuggestedPredefines;
5159 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5160 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005161 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005162 return true;
5163 break;
5164 }
5165
5166 case INPUT_FILES_BLOCK_ID:
5167 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005168 if (llvm::Error Err = Stream.SkipBlock()) {
5169 // FIXME this drops the error on the floor.
5170 consumeError(std::move(Err));
5171 return true;
5172 }
5173 if (NeedsInputFiles &&
5174 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005175 return true;
5176 break;
5177
5178 default:
JF Bastien0e828952019-06-26 19:50:12 +00005179 if (llvm::Error Err = Stream.SkipBlock()) {
5180 // FIXME this drops the error on the floor.
5181 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005182 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005183 }
Richard Smith0516b182015-09-08 19:40:14 +00005184 break;
5185 }
5186
5187 continue;
5188 }
5189
5190 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005191 DoneWithControlBlock = true;
5192 break;
Richard Smith0516b182015-09-08 19:40:14 +00005193
5194 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005195 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005196
5197 case llvm::BitstreamEntry::Record:
5198 break;
5199 }
5200
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005201 if (DoneWithControlBlock) break;
5202
Guy Benyei11169dd2012-12-18 14:30:41 +00005203 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005204 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005205 Expected<unsigned> MaybeRecCode =
5206 Stream.readRecord(Entry.ID, Record, &Blob);
5207 if (!MaybeRecCode) {
5208 // FIXME this drops the error.
5209 return Failure;
5210 }
5211 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005212 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005213 if (Record[0] != VERSION_MAJOR)
5214 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005215 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005216 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005217 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005218 case MODULE_NAME:
5219 Listener.ReadModuleName(Blob);
5220 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005221 case MODULE_DIRECTORY:
Benjamin Krameradcd0262020-01-28 20:23:46 +01005222 ModuleDir = std::string(Blob);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005223 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005224 case MODULE_MAP_FILE: {
5225 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005226 auto Path = ReadString(Record, Idx);
5227 ResolveImportedPath(Path, ModuleDir);
5228 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005229 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005230 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005231 case INPUT_FILE_OFFSETS: {
5232 if (!NeedsInputFiles)
5233 break;
5234
5235 unsigned NumInputFiles = Record[0];
5236 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005237 const llvm::support::unaligned_uint64_t *InputFileOffs =
5238 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005239 for (unsigned I = 0; I != NumInputFiles; ++I) {
5240 // Go find this input file.
5241 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005242
5243 if (isSystemFile && !NeedsSystemInputFiles)
5244 break; // the rest are system input files
5245
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005246 BitstreamCursor &Cursor = InputFilesCursor;
5247 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005248 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5249 // FIXME this drops errors on the floor.
5250 consumeError(std::move(Err));
5251 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005252
JF Bastien0e828952019-06-26 19:50:12 +00005253 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5254 if (!MaybeCode) {
5255 // FIXME this drops errors on the floor.
5256 consumeError(MaybeCode.takeError());
5257 }
5258 unsigned Code = MaybeCode.get();
5259
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005260 RecordData Record;
5261 StringRef Blob;
5262 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005263 Expected<unsigned> MaybeRecordType =
5264 Cursor.readRecord(Code, Record, &Blob);
5265 if (!MaybeRecordType) {
5266 // FIXME this drops errors on the floor.
5267 consumeError(MaybeRecordType.takeError());
5268 }
5269 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +00005270 case INPUT_FILE_HASH:
5271 break;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005272 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005273 bool Overridden = static_cast<bool>(Record[3]);
Benjamin Krameradcd0262020-01-28 20:23:46 +01005274 std::string Filename = std::string(Blob);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005275 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005276 shouldContinue = Listener.visitInputFile(
5277 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005278 break;
5279 }
5280 if (!shouldContinue)
5281 break;
5282 }
5283 break;
5284 }
5285
Richard Smithd4b230b2014-10-27 23:01:16 +00005286 case IMPORTS: {
5287 if (!NeedsImports)
5288 break;
5289
5290 unsigned Idx = 0, N = Record.size();
5291 while (Idx < N) {
5292 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005293 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5294 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005295 std::string Filename = ReadString(Record, Idx);
5296 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005297 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005298 }
5299 break;
5300 }
5301
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005302 default:
5303 // No other validation to perform.
5304 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 }
5306 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005307
5308 // Look for module file extension blocks, if requested.
5309 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005310 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005311 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5312 bool DoneWithExtensionBlock = false;
5313 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005314 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5315 if (!MaybeEntry) {
5316 // FIXME this drops the error.
5317 return true;
5318 }
5319 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005320
JF Bastien0e828952019-06-26 19:50:12 +00005321 switch (Entry.Kind) {
5322 case llvm::BitstreamEntry::SubBlock:
5323 if (llvm::Error Err = Stream.SkipBlock()) {
5324 // FIXME this drops the error on the floor.
5325 consumeError(std::move(Err));
5326 return true;
5327 }
5328 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005329
JF Bastien0e828952019-06-26 19:50:12 +00005330 case llvm::BitstreamEntry::EndBlock:
5331 DoneWithExtensionBlock = true;
5332 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005333
JF Bastien0e828952019-06-26 19:50:12 +00005334 case llvm::BitstreamEntry::Error:
5335 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005336
JF Bastien0e828952019-06-26 19:50:12 +00005337 case llvm::BitstreamEntry::Record:
5338 break;
5339 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005340
5341 Record.clear();
5342 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005343 Expected<unsigned> MaybeRecCode =
5344 Stream.readRecord(Entry.ID, Record, &Blob);
5345 if (!MaybeRecCode) {
5346 // FIXME this drops the error.
5347 return true;
5348 }
5349 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005350 case EXTENSION_METADATA: {
5351 ModuleFileExtensionMetadata Metadata;
5352 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5353 return true;
5354
5355 Listener.readModuleFileExtension(Metadata);
5356 break;
5357 }
5358 }
5359 }
5360 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005361 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005362 }
5363
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005364 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5365 if (readUnhashedControlBlockImpl(
5366 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5367 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5368 ValidateDiagnosticOptions) != Success)
5369 return true;
5370
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005371 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005372}
5373
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005374bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5375 const PCHContainerReader &PCHContainerRdr,
5376 const LangOptions &LangOpts,
5377 const TargetOptions &TargetOpts,
5378 const PreprocessorOptions &PPOpts,
5379 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005380 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5381 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005382 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005383 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005384 validator,
5385 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005386}
5387
Ben Langmuir2c9af442014-04-10 17:57:43 +00005388ASTReader::ASTReadResult
5389ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005391 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5392 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005393 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005394 }
5395
5396 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5397 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005398 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005399 RecordData Record;
5400 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005401 Expected<llvm::BitstreamEntry> MaybeEntry =
5402 F.Stream.advanceSkippingSubblocks();
5403 if (!MaybeEntry) {
5404 Error(MaybeEntry.takeError());
5405 return Failure;
5406 }
5407 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005408
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005409 switch (Entry.Kind) {
5410 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5411 case llvm::BitstreamEntry::Error:
5412 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005413 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005414 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005415 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005416 case llvm::BitstreamEntry::Record:
5417 // The interesting case.
5418 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005420
Guy Benyei11169dd2012-12-18 14:30:41 +00005421 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005422 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005424 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5425 if (!MaybeKind) {
5426 Error(MaybeKind.takeError());
5427 return Failure;
5428 }
5429 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005430
5431 if ((Kind == SUBMODULE_METADATA) != First) {
5432 Error("submodule metadata record should be at beginning of block");
5433 return Failure;
5434 }
5435 First = false;
5436
5437 // Submodule information is only valid if we have a current module.
5438 // FIXME: Should we error on these cases?
5439 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5440 Kind != SUBMODULE_DEFINITION)
5441 continue;
5442
5443 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005444 default: // Default behavior: ignore.
5445 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005446
Richard Smith03478d92014-10-23 22:12:14 +00005447 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005448 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005450 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005451 }
Richard Smith03478d92014-10-23 22:12:14 +00005452
Chris Lattner0e6c9402013-01-20 02:38:54 +00005453 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005454 unsigned Idx = 0;
5455 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5456 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005457 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005458 bool IsFramework = Record[Idx++];
5459 bool IsExplicit = Record[Idx++];
5460 bool IsSystem = Record[Idx++];
5461 bool IsExternC = Record[Idx++];
5462 bool InferSubmodules = Record[Idx++];
5463 bool InferExplicitSubmodules = Record[Idx++];
5464 bool InferExportWildcard = Record[Idx++];
5465 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005466 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005467
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005468 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005469 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005471
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 // Retrieve this (sub)module from the module map, creating it if
5473 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005474 CurrentModule =
5475 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5476 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005477
5478 // FIXME: set the definition loc for CurrentModule, or call
5479 // ModMap.setInferredModuleAllowedBy()
5480
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5482 if (GlobalIndex >= SubmodulesLoaded.size() ||
5483 SubmodulesLoaded[GlobalIndex]) {
5484 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005485 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005486 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005487
Douglas Gregor7029ce12013-03-19 00:28:20 +00005488 if (!ParentModule) {
5489 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005490 // Don't emit module relocation error if we have -fno-validate-pch
5491 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5492 CurFile != F.File) {
Duncan P. N. Exon Smitheef69022019-11-10 11:17:42 -08005493 Error(diag::err_module_file_conflict,
5494 CurrentModule->getTopLevelModuleName(), CurFile->getName(),
5495 F.File->getName());
Ben Langmuir2c9af442014-04-10 17:57:43 +00005496 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005497 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005498 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005499
Duncan P. N. Exon Smith83dcb342019-11-10 13:14:52 -08005500 F.DidReadTopLevelSubmodule = true;
Douglas Gregor7029ce12013-03-19 00:28:20 +00005501 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005502 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005503 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005504
Richard Smithdd8b5332017-09-04 05:37:53 +00005505 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005506 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005507 CurrentModule->IsFromModuleFile = true;
5508 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005509 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 CurrentModule->InferSubmodules = InferSubmodules;
5511 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5512 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005513 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005514 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005515 if (DeserializationListener)
5516 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005517
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005519
Richard Smith8a3e39a2016-03-28 21:31:09 +00005520 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005521 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005522 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005523 CurrentModule->UnresolvedConflicts.clear();
5524 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005525
5526 // The module is available unless it's missing a requirement; relevant
5527 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5528 // Missing headers that were present when the module was built do not
5529 // make it unavailable -- if we got this far, this must be an explicitly
5530 // imported module file.
5531 CurrentModule->Requirements.clear();
5532 CurrentModule->MissingHeaders.clear();
5533 CurrentModule->IsMissingRequirement =
5534 ParentModule && ParentModule->IsMissingRequirement;
5535 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005536 break;
5537 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005538
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 case SUBMODULE_UMBRELLA_HEADER: {
Benjamin Krameradcd0262020-01-28 20:23:46 +01005540 std::string Filename = std::string(Blob);
Richard Smith2b63d152015-05-16 02:28:53 +00005541 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005542 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005543 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005544 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5545 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005546 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5547 Error("mismatched umbrella headers in submodule");
5548 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 }
5550 }
5551 break;
5552 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005553
Richard Smith202210b2014-10-24 20:23:01 +00005554 case SUBMODULE_HEADER:
5555 case SUBMODULE_EXCLUDED_HEADER:
5556 case SUBMODULE_PRIVATE_HEADER:
5557 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005558 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5559 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005560 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005561
Richard Smith202210b2014-10-24 20:23:01 +00005562 case SUBMODULE_TEXTUAL_HEADER:
5563 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5564 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5565 // them here.
5566 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005567
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005568 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005569 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005570 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005571
5572 case SUBMODULE_UMBRELLA_DIR: {
Benjamin Krameradcd0262020-01-28 20:23:46 +01005573 std::string Dirname = std::string(Blob);
Richard Smith2b63d152015-05-16 02:28:53 +00005574 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005575 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005577 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5578 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005579 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5580 Error("mismatched umbrella directories in submodule");
5581 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005582 }
5583 }
5584 break;
5585 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005586
Guy Benyei11169dd2012-12-18 14:30:41 +00005587 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005588 F.BaseSubmoduleID = getTotalNumSubmodules();
5589 F.LocalNumSubmodules = Record[0];
5590 unsigned LocalBaseSubmoduleID = Record[1];
5591 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005592 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005593 // module.
5594 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005595
5596 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005597 // module.
5598 F.SubmoduleRemap.insertOrReplace(
5599 std::make_pair(LocalBaseSubmoduleID,
5600 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005601
Ben Langmuir52ca6782014-10-20 16:27:32 +00005602 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5603 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005604 break;
5605 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005606
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005607 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005608 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005609 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005610 Unresolved.File = &F;
5611 Unresolved.Mod = CurrentModule;
5612 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005613 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005614 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005615 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 }
5617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005618
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005619 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005621 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005622 Unresolved.File = &F;
5623 Unresolved.Mod = CurrentModule;
5624 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005625 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005627 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005628 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005629
5630 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005631 // the parsed, unresolved exports around.
5632 CurrentModule->UnresolvedExports.clear();
5633 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005634
5635 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005636 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5637 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005638 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005639
5640 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005641 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005642 CurrentModule->LinkLibraries.push_back(
Benjamin Krameradcd0262020-01-28 20:23:46 +01005643 Module::LinkLibrary(std::string(Blob), Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005644 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005645
5646 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005647 CurrentModule->ConfigMacros.push_back(Blob.str());
5648 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005649
5650 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005651 UnresolvedModuleRef Unresolved;
5652 Unresolved.File = &F;
5653 Unresolved.Mod = CurrentModule;
5654 Unresolved.ID = Record[0];
5655 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5656 Unresolved.IsWildcard = false;
5657 Unresolved.String = Blob;
5658 UnresolvedModuleRefs.push_back(Unresolved);
5659 break;
5660 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005661
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005662 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005663 if (!ContextObj)
5664 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005665 SmallVector<uint32_t, 16> Inits;
5666 for (auto &ID : Record)
5667 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005668 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005669 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005670 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005671
5672 case SUBMODULE_EXPORT_AS:
5673 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005674 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005675 break;
5676 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 }
5678}
5679
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005680/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005681/// structure.
5682///
5683/// This routine parses the language options from the AST file and then gives
5684/// them to the AST listener if one is set.
5685///
5686/// \returns true if the listener deems the file unacceptable, false otherwise.
5687bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5688 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005689 ASTReaderListener &Listener,
5690 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 LangOptions LangOpts;
5692 unsigned Idx = 0;
5693#define LANGOPT(Name, Bits, Default, Description) \
5694 LangOpts.Name = Record[Idx++];
5695#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5696 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5697#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005698#define SANITIZER(NAME, ID) \
5699 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005700#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005701
Ben Langmuircd98cb72015-06-23 18:20:18 +00005702 for (unsigned N = Record[Idx++]; N; --N)
5703 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5704
Vedant Kumar48b4f762018-04-14 01:40:48 +00005705 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5707 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005708
Ben Langmuird4a667a2015-06-23 18:20:23 +00005709 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005710
5711 // Comment options.
5712 for (unsigned N = Record[Idx++]; N; --N) {
5713 LangOpts.CommentOpts.BlockCommandNames.push_back(
5714 ReadString(Record, Idx));
5715 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005716 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005717
Samuel Antaoee8fb302016-01-06 13:42:12 +00005718 // OpenMP offloading options.
5719 for (unsigned N = Record[Idx++]; N; --N) {
5720 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5721 }
5722
5723 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5724
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005725 return Listener.ReadLanguageOptions(LangOpts, Complain,
5726 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005727}
5728
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005729bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5730 ASTReaderListener &Listener,
5731 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 unsigned Idx = 0;
5733 TargetOptions TargetOpts;
5734 TargetOpts.Triple = ReadString(Record, Idx);
5735 TargetOpts.CPU = ReadString(Record, Idx);
5736 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005737 for (unsigned N = Record[Idx++]; N; --N) {
5738 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5739 }
5740 for (unsigned N = Record[Idx++]; N; --N) {
5741 TargetOpts.Features.push_back(ReadString(Record, Idx));
5742 }
5743
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005744 return Listener.ReadTargetOptions(TargetOpts, Complain,
5745 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005746}
5747
5748bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5749 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005750 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005751 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005752#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005753#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005754 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005755#include "clang/Basic/DiagnosticOptions.def"
5756
Richard Smith3be1cb22014-08-07 00:24:21 +00005757 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005758 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005759 for (unsigned N = Record[Idx++]; N; --N)
5760 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005761
5762 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5763}
5764
5765bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5766 ASTReaderListener &Listener) {
5767 FileSystemOptions FSOpts;
5768 unsigned Idx = 0;
5769 FSOpts.WorkingDir = ReadString(Record, Idx);
5770 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5771}
5772
5773bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5774 bool Complain,
5775 ASTReaderListener &Listener) {
5776 HeaderSearchOptions HSOpts;
5777 unsigned Idx = 0;
5778 HSOpts.Sysroot = ReadString(Record, Idx);
5779
5780 // Include entries.
5781 for (unsigned N = Record[Idx++]; N; --N) {
5782 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005783 frontend::IncludeDirGroup Group
5784 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005785 bool IsFramework = Record[Idx++];
5786 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005787 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5788 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 }
5790
5791 // System header prefixes.
5792 for (unsigned N = Record[Idx++]; N; --N) {
5793 std::string Prefix = ReadString(Record, Idx);
5794 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005795 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005796 }
5797
5798 HSOpts.ResourceDir = ReadString(Record, Idx);
5799 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005800 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005801 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005802 HSOpts.ImplicitModuleMaps = Record[Idx++];
5803 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005804 HSOpts.UseBuiltinIncludes = Record[Idx++];
5805 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5806 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5807 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005808 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005809
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005810 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5811 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005812}
5813
5814bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5815 bool Complain,
5816 ASTReaderListener &Listener,
5817 std::string &SuggestedPredefines) {
5818 PreprocessorOptions PPOpts;
5819 unsigned Idx = 0;
5820
5821 // Macro definitions/undefs
5822 for (unsigned N = Record[Idx++]; N; --N) {
5823 std::string Macro = ReadString(Record, Idx);
5824 bool IsUndef = Record[Idx++];
5825 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5826 }
5827
5828 // Includes
5829 for (unsigned N = Record[Idx++]; N; --N) {
5830 PPOpts.Includes.push_back(ReadString(Record, Idx));
5831 }
5832
5833 // Macro Includes
5834 for (unsigned N = Record[Idx++]; N; --N) {
5835 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5836 }
5837
5838 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005839 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005840 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 PPOpts.ObjCXXARCStandardLibrary =
5842 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5843 SuggestedPredefines.clear();
5844 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5845 SuggestedPredefines);
5846}
5847
5848std::pair<ModuleFile *, unsigned>
5849ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5850 GlobalPreprocessedEntityMapType::iterator
5851 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005852 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005853 "Corrupted global preprocessed entity map");
5854 ModuleFile *M = I->second;
5855 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5856 return std::make_pair(M, LocalIndex);
5857}
5858
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005859llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005860ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5861 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5862 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5863 Mod.NumPreprocessedEntities);
5864
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005865 return llvm::make_range(PreprocessingRecord::iterator(),
5866 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005867}
5868
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005869llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005870ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005871 return llvm::make_range(
5872 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5873 ModuleDeclIterator(this, &Mod,
5874 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005875}
5876
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005877SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5878 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5879 assert(I != GlobalSkippedRangeMap.end() &&
5880 "Corrupted global skipped range map");
5881 ModuleFile *M = I->second;
5882 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5883 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5884 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5885 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5886 TranslateSourceLocation(*M, RawRange.getEnd()));
5887 assert(Range.isValid());
5888 return Range;
5889}
5890
Guy Benyei11169dd2012-12-18 14:30:41 +00005891PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5892 PreprocessedEntityID PPID = Index+1;
5893 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5894 ModuleFile &M = *PPInfo.first;
5895 unsigned LocalIndex = PPInfo.second;
5896 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5897
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 if (!PP.getPreprocessingRecord()) {
5899 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005900 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005902
5903 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005904 if (llvm::Error Err =
5905 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5906 Error(std::move(Err));
5907 return nullptr;
5908 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005909
JF Bastien0e828952019-06-26 19:50:12 +00005910 Expected<llvm::BitstreamEntry> MaybeEntry =
5911 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5912 if (!MaybeEntry) {
5913 Error(MaybeEntry.takeError());
5914 return nullptr;
5915 }
5916 llvm::BitstreamEntry Entry = MaybeEntry.get();
5917
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005918 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005919 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005920
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005922 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5923 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005924 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005925 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005926 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005927 Expected<unsigned> MaybeRecType =
5928 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5929 if (!MaybeRecType) {
5930 Error(MaybeRecType.takeError());
5931 return nullptr;
5932 }
5933 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005934 case PPD_MACRO_EXPANSION: {
5935 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005936 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005937 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 if (isBuiltin)
5939 Name = getLocalIdentifier(M, Record[1]);
5940 else {
Richard Smith66a81862015-05-04 02:25:31 +00005941 PreprocessedEntityID GlobalID =
5942 getGlobalPreprocessedEntityID(M, Record[1]);
5943 Def = cast<MacroDefinitionRecord>(
5944 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005945 }
5946
5947 MacroExpansion *ME;
5948 if (isBuiltin)
5949 ME = new (PPRec) MacroExpansion(Name, Range);
5950 else
5951 ME = new (PPRec) MacroExpansion(Def, Range);
5952
5953 return ME;
5954 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005955
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 case PPD_MACRO_DEFINITION: {
5957 // Decode the identifier info and then check again; if the macro is
5958 // still defined and associated with the identifier,
5959 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005960 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005961
5962 if (DeserializationListener)
5963 DeserializationListener->MacroDefinitionRead(PPID, MD);
5964
5965 return MD;
5966 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005967
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005969 const char *FullFileNameStart = Blob.data() + Record[0];
5970 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005971 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005973 if (auto FE = PP.getFileManager().getFile(FullFileName))
5974 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005975
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005977 InclusionDirective::InclusionKind Kind
5978 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5979 InclusionDirective *ID
5980 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005981 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005982 Record[1], Record[3],
5983 File,
5984 Range);
5985 return ID;
5986 }
5987 }
5988
5989 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5990}
5991
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005992/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005993/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005994///
5995/// \param SLocMapI points at a chunk of a module that contains no
5996/// preprocessed entities or the entities it contains are not the ones we are
5997/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005998PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5999 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
6000 ++SLocMapI;
6001 for (GlobalSLocOffsetMapType::const_iterator
6002 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
6003 ModuleFile &M = *SLocMapI->second;
6004 if (M.NumPreprocessedEntities)
6005 return M.BasePreprocessedEntityID;
6006 }
6007
6008 return getTotalNumPreprocessedEntities();
6009}
6010
6011namespace {
6012
Guy Benyei11169dd2012-12-18 14:30:41 +00006013struct PPEntityComp {
6014 const ASTReader &Reader;
6015 ModuleFile &M;
6016
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006017 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006018
6019 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
6020 SourceLocation LHS = getLoc(L);
6021 SourceLocation RHS = getLoc(R);
6022 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6023 }
6024
6025 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
6026 SourceLocation LHS = getLoc(L);
6027 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6028 }
6029
6030 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
6031 SourceLocation RHS = getLoc(R);
6032 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6033 }
6034
6035 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00006036 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 }
6038};
6039
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006040} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006041
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006042PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
6043 bool EndsAfter) const {
6044 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00006045 return getTotalNumPreprocessedEntities();
6046
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006047 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
6048 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00006049 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
6050 "Corrupted global sloc offset map");
6051
6052 if (SLocMapI->second->NumPreprocessedEntities == 0)
6053 return findNextPreprocessedEntity(SLocMapI);
6054
6055 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006056
6057 using pp_iterator = const PPEntityOffset *;
6058
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
6060 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
6061
6062 size_t Count = M.NumPreprocessedEntities;
6063 size_t Half;
6064 pp_iterator First = pp_begin;
6065 pp_iterator PPI;
6066
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006067 if (EndsAfter) {
6068 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00006069 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006070 } else {
6071 // Do a binary search manually instead of using std::lower_bound because
6072 // The end locations of entities may be unordered (when a macro expansion
6073 // is inside another macro argument), but for this case it is not important
6074 // whether we get the first macro expansion or its containing macro.
6075 while (Count > 0) {
6076 Half = Count / 2;
6077 PPI = First;
6078 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006079 if (SourceMgr.isBeforeInTranslationUnit(
6080 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006081 First = PPI;
6082 ++First;
6083 Count = Count - Half - 1;
6084 } else
6085 Count = Half;
6086 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 }
6088
6089 if (PPI == pp_end)
6090 return findNextPreprocessedEntity(SLocMapI);
6091
6092 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6093}
6094
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006095/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006096/// preprocessed entities that \arg Range encompasses.
6097std::pair<unsigned, unsigned>
6098 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6099 if (Range.isInvalid())
6100 return std::make_pair(0,0);
6101 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6102
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006103 PreprocessedEntityID BeginID =
6104 findPreprocessedEntity(Range.getBegin(), false);
6105 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006106 return std::make_pair(BeginID, EndID);
6107}
6108
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006109/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006110/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006111Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006112 FileID FID) {
6113 if (FID.isInvalid())
6114 return false;
6115
6116 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6117 ModuleFile &M = *PPInfo.first;
6118 unsigned LocalIndex = PPInfo.second;
6119 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006120
Richard Smithcb34bd32016-03-27 07:28:06 +00006121 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 if (Loc.isInvalid())
6123 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006124
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6126 return true;
6127 else
6128 return false;
6129}
6130
6131namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006132
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006133 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006134 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006135 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006136 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006137
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006139 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006140
6141 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006142 HeaderFileInfoLookupTable *Table
6143 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 if (!Table)
6145 return false;
6146
6147 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006148 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006149 if (Pos == Table->end())
6150 return false;
6151
Richard Smithbdf2d932015-07-30 03:37:16 +00006152 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006153 return true;
6154 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006155
David Blaikie05785d12013-02-20 22:23:23 +00006156 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006157 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006158
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006159} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006160
6161HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006162 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006163 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006164 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006166
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 return HeaderFileInfo();
6168}
6169
6170void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006171 using DiagState = DiagnosticsEngine::DiagState;
6172 SmallVector<DiagState *, 32> DiagStates;
6173
Vedant Kumar48b4f762018-04-14 01:40:48 +00006174 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006175 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006176 auto &Record = F.PragmaDiagMappings;
6177 if (Record.empty())
6178 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006179
Richard Smithd230de22017-01-26 01:01:01 +00006180 DiagStates.clear();
6181
6182 auto ReadDiagState =
6183 [&](const DiagState &BasedOn, SourceLocation Loc,
6184 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6185 unsigned BackrefID = Record[Idx++];
6186 if (BackrefID != 0)
6187 return DiagStates[BackrefID - 1];
6188
Guy Benyei11169dd2012-12-18 14:30:41 +00006189 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006190 Diag.DiagStates.push_back(BasedOn);
6191 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006193 unsigned Size = Record[Idx++];
6194 assert(Idx + Size * 2 <= Record.size() &&
6195 "Invalid data, not enough diag/map pairs");
6196 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006197 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006198 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006199 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006200 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6201 continue;
6202
6203 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6204
6205 // If this mapping was specified as a warning but the severity was
6206 // upgraded due to diagnostic settings, simulate the current diagnostic
6207 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006208 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6209 NewMapping.setSeverity(diag::Severity::Warning);
6210 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006211 }
6212
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006213 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006214 }
Richard Smithd230de22017-01-26 01:01:01 +00006215 return NewState;
6216 };
6217
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006218 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006219 DiagState *FirstState;
6220 if (F.Kind == MK_ImplicitModule) {
6221 // Implicitly-built modules are reused with different diagnostic
6222 // settings. Use the initial diagnostic state from Diag to simulate this
6223 // compilation's diagnostic settings.
6224 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6225 DiagStates.push_back(FirstState);
6226
6227 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006228 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006229 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006230 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006231 assert(Idx < Record.size() &&
6232 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006233 } else if (F.isModule()) {
6234 // For an explicit module, preserve the flags from the module build
6235 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6236 // -Wblah flags.
6237 unsigned Flags = Record[Idx++];
6238 DiagState Initial;
6239 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6240 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6241 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6242 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6243 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6244 Initial.ExtBehavior = (diag::Severity)Flags;
6245 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006246
Richard Smith6c2b5a82018-02-09 01:15:13 +00006247 assert(F.OriginalSourceFileID.isValid());
6248
Richard Smithe37391c2017-05-03 00:28:49 +00006249 // Set up the root buffer of the module to start with the initial
6250 // diagnostic state of the module itself, to cover files that contain no
6251 // explicit transitions (for which we did not serialize anything).
6252 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6253 .StateTransitions.push_back({FirstState, 0});
6254 } else {
6255 // For prefix ASTs, start with whatever the user configured on the
6256 // command line.
6257 Idx++; // Skip flags.
6258 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6259 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006260 }
Richard Smithd230de22017-01-26 01:01:01 +00006261
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006262 // Read the state transitions.
6263 unsigned NumLocations = Record[Idx++];
6264 while (NumLocations--) {
6265 assert(Idx < Record.size() &&
6266 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006267 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6268 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006269 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006270 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6271 unsigned Transitions = Record[Idx++];
6272
6273 // Note that we don't need to set up Parent/ParentOffset here, because
6274 // we won't be changing the diagnostic state within imported FileIDs
6275 // (other than perhaps appending to the main source file, which has no
6276 // parent).
6277 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6278 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6279 for (unsigned I = 0; I != Transitions; ++I) {
6280 unsigned Offset = Record[Idx++];
6281 auto *State =
6282 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6283 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 }
6285 }
Richard Smithd230de22017-01-26 01:01:01 +00006286
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006287 // Read the final state.
6288 assert(Idx < Record.size() &&
6289 "Invalid data, missing final pragma diagnostic state");
6290 SourceLocation CurStateLoc =
6291 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6292 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6293
6294 if (!F.isModule()) {
6295 Diag.DiagStatesByLoc.CurDiagState = CurState;
6296 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6297
6298 // Preserve the property that the imaginary root file describes the
6299 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006300 FileID NullFile;
6301 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006302 if (T.empty())
6303 T.push_back({CurState, 0});
6304 else
6305 T[0].State = CurState;
6306 }
6307
Richard Smithd230de22017-01-26 01:01:01 +00006308 // Don't try to read these mappings again.
6309 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006310 }
6311}
6312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006313/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006314ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6315 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6316 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6317 ModuleFile *M = I->second;
6318 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6319}
6320
John McCalld505e572019-12-13 21:54:44 -05006321static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
6322 switch (code) {
6323#define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
6324 case TYPE_##CODE_ID: return Type::CLASS_ID;
6325#include "clang/Serialization/TypeBitCodes.def"
6326 default: return llvm::None;
6327 }
John McCall3ce3d232019-12-13 03:37:23 -05006328}
6329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006330/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006331///
6332/// The index is the type ID, shifted and minus the number of predefs. This
6333/// routine actually reads the record corresponding to the type at the given
6334/// location. It is a helper routine for GetType, which deals with reading type
6335/// IDs.
6336QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006337 assert(ContextObj && "reading type with no AST context");
6338 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006339 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006340 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006341
6342 // Keep track of where we are in the stream, then jump back there
6343 // after reading this type.
6344 SavedStreamPosition SavedPosition(DeclsCursor);
6345
6346 ReadingKindTracker ReadingKind(Read_Type, *this);
6347
6348 // Note that we are loading a type record.
6349 Deserializing AType(this);
6350
JF Bastien0e828952019-06-26 19:50:12 +00006351 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6352 Error(std::move(Err));
6353 return QualType();
6354 }
John McCall3ce3d232019-12-13 03:37:23 -05006355 Expected<unsigned> RawCode = DeclsCursor.ReadCode();
6356 if (!RawCode) {
6357 Error(RawCode.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006358 return QualType();
6359 }
JF Bastien0e828952019-06-26 19:50:12 +00006360
John McCall3ce3d232019-12-13 03:37:23 -05006361 ASTRecordReader Record(*this, *Loc.F);
6362 Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
6363 if (!Code) {
6364 Error(Code.takeError());
JF Bastien0e828952019-06-26 19:50:12 +00006365 return QualType();
6366 }
John McCalld505e572019-12-13 21:54:44 -05006367 if (Code.get() == TYPE_EXT_QUAL) {
6368 QualType baseType = Record.readQualType();
6369 Qualifiers quals = Record.readQualifiers();
6370 return Context.getQualifiedType(baseType, quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00006371 }
6372
John McCalld505e572019-12-13 21:54:44 -05006373 auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
6374 if (!maybeClass) {
6375 Error("Unexpected code for type");
6376 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006377 }
6378
John McCalld505e572019-12-13 21:54:44 -05006379 serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
6380 return TypeReader.read(*maybeClass);
Richard Smith564417a2014-03-20 21:47:22 +00006381}
6382
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006383namespace clang {
6384
6385class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
John McCall3ce3d232019-12-13 03:37:23 -05006386 ASTRecordReader &Reader;
Guy Benyei11169dd2012-12-18 14:30:41 +00006387
John McCall3ce3d232019-12-13 03:37:23 -05006388 SourceLocation readSourceLocation() {
6389 return Reader.readSourceLocation();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006390 }
6391
6392 TypeSourceInfo *GetTypeSourceInfo() {
John McCall3ce3d232019-12-13 03:37:23 -05006393 return Reader.readTypeSourceInfo();
David L. Jonesbe1557a2016-12-21 00:17:49 +00006394 }
6395
6396 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
John McCall3ce3d232019-12-13 03:37:23 -05006397 return Reader.readNestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00006398 }
6399
Richard Smithe43e2b32018-08-20 21:47:29 +00006400 Attr *ReadAttr() {
John McCall3ce3d232019-12-13 03:37:23 -05006401 return Reader.readAttr();
Richard Smithe43e2b32018-08-20 21:47:29 +00006402 }
6403
Guy Benyei11169dd2012-12-18 14:30:41 +00006404public:
John McCall3ce3d232019-12-13 03:37:23 -05006405 TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006406
6407 // We want compile-time assurance that we've enumerated all of
6408 // these, so unfortunately we have to declare them first, then
6409 // define them out-of-line.
6410#define ABSTRACT_TYPELOC(CLASS, PARENT)
6411#define TYPELOC(CLASS, PARENT) \
6412 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6413#include "clang/AST/TypeLocNodes.def"
6414
6415 void VisitFunctionTypeLoc(FunctionTypeLoc);
6416 void VisitArrayTypeLoc(ArrayTypeLoc);
6417};
6418
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006419} // namespace clang
6420
Guy Benyei11169dd2012-12-18 14:30:41 +00006421void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6422 // nothing to do
6423}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006424
Guy Benyei11169dd2012-12-18 14:30:41 +00006425void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006426 TL.setBuiltinLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006427 if (TL.needsExtraLocalData()) {
John McCall3ce3d232019-12-13 03:37:23 -05006428 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
6429 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Reader.readInt()));
6430 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Reader.readInt()));
6431 TL.setModeAttr(Reader.readInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00006432 }
6433}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006434
Guy Benyei11169dd2012-12-18 14:30:41 +00006435void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006436 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006437}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006438
Guy Benyei11169dd2012-12-18 14:30:41 +00006439void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006440 TL.setStarLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006441}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006442
Reid Kleckner8a365022013-06-24 17:51:48 +00006443void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6444 // nothing to do
6445}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006446
Reid Kleckner0503a872013-12-05 01:23:43 +00006447void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6448 // nothing to do
6449}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006450
Leonard Chanc72aaf62019-05-07 03:20:17 +00006451void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006452 TL.setExpansionLoc(readSourceLocation());
Leonard Chanc72aaf62019-05-07 03:20:17 +00006453}
6454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006456 TL.setCaretLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006457}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006458
Guy Benyei11169dd2012-12-18 14:30:41 +00006459void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006460 TL.setAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006461}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006462
Guy Benyei11169dd2012-12-18 14:30:41 +00006463void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006464 TL.setAmpAmpLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006465}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006466
Guy Benyei11169dd2012-12-18 14:30:41 +00006467void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006468 TL.setStarLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006469 TL.setClassTInfo(GetTypeSourceInfo());
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::VisitArrayTypeLoc(ArrayTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006473 TL.setLBracketLoc(readSourceLocation());
6474 TL.setRBracketLoc(readSourceLocation());
6475 if (Reader.readBool())
6476 TL.setSizeExpr(Reader.readExpr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006477 else
Craig Toppera13603a2014-05-22 05:54:18 +00006478 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006479}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006480
Guy Benyei11169dd2012-12-18 14:30:41 +00006481void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6482 VisitArrayTypeLoc(TL);
6483}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006484
Guy Benyei11169dd2012-12-18 14:30:41 +00006485void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6486 VisitArrayTypeLoc(TL);
6487}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006488
Guy Benyei11169dd2012-12-18 14:30:41 +00006489void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6490 VisitArrayTypeLoc(TL);
6491}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006492
Guy Benyei11169dd2012-12-18 14:30:41 +00006493void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6494 DependentSizedArrayTypeLoc TL) {
6495 VisitArrayTypeLoc(TL);
6496}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006497
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006498void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6499 DependentAddressSpaceTypeLoc TL) {
6500
John McCall3ce3d232019-12-13 03:37:23 -05006501 TL.setAttrNameLoc(readSourceLocation());
6502 TL.setAttrOperandParensRange(Reader.readSourceRange());
6503 TL.setAttrExprOperand(Reader.readExpr());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006504}
6505
Guy Benyei11169dd2012-12-18 14:30:41 +00006506void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6507 DependentSizedExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006508 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006509}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006510
Guy Benyei11169dd2012-12-18 14:30:41 +00006511void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006512 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006513}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006514
Erich Keanef702b022018-07-13 19:46:04 +00006515void TypeLocReader::VisitDependentVectorTypeLoc(
6516 DependentVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006517 TL.setNameLoc(readSourceLocation());
Erich Keanef702b022018-07-13 19:46:04 +00006518}
6519
Guy Benyei11169dd2012-12-18 14:30:41 +00006520void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006521 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006522}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006523
Guy Benyei11169dd2012-12-18 14:30:41 +00006524void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006525 TL.setLocalRangeBegin(readSourceLocation());
6526 TL.setLParenLoc(readSourceLocation());
6527 TL.setRParenLoc(readSourceLocation());
6528 TL.setExceptionSpecRange(Reader.readSourceRange());
6529 TL.setLocalRangeEnd(readSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006530 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
John McCall3ce3d232019-12-13 03:37:23 -05006531 TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00006532 }
6533}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006534
Guy Benyei11169dd2012-12-18 14:30:41 +00006535void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6536 VisitFunctionTypeLoc(TL);
6537}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006538
Guy Benyei11169dd2012-12-18 14:30:41 +00006539void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6540 VisitFunctionTypeLoc(TL);
6541}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006542
Guy Benyei11169dd2012-12-18 14:30:41 +00006543void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006544 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006545}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006546
Guy Benyei11169dd2012-12-18 14:30:41 +00006547void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006548 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006549}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006550
Guy Benyei11169dd2012-12-18 14:30:41 +00006551void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006552 TL.setTypeofLoc(readSourceLocation());
6553 TL.setLParenLoc(readSourceLocation());
6554 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006555}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006556
Guy Benyei11169dd2012-12-18 14:30:41 +00006557void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006558 TL.setTypeofLoc(readSourceLocation());
6559 TL.setLParenLoc(readSourceLocation());
6560 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006561 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006562}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006563
Guy Benyei11169dd2012-12-18 14:30:41 +00006564void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006565 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006566}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006567
Guy Benyei11169dd2012-12-18 14:30:41 +00006568void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006569 TL.setKWLoc(readSourceLocation());
6570 TL.setLParenLoc(readSourceLocation());
6571 TL.setRParenLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006572 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006573}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006574
Guy Benyei11169dd2012-12-18 14:30:41 +00006575void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006576 TL.setNameLoc(readSourceLocation());
Saar Razb481f022020-01-22 02:03:05 +02006577 if (Reader.readBool()) {
6578 TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
6579 TL.setTemplateKWLoc(readSourceLocation());
6580 TL.setConceptNameLoc(readSourceLocation());
6581 TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
6582 TL.setLAngleLoc(readSourceLocation());
6583 TL.setRAngleLoc(readSourceLocation());
6584 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
6585 TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
6586 TL.getTypePtr()->getArg(i).getKind()));
6587 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006588}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006589
Richard Smith600b5262017-01-26 20:40:47 +00006590void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6591 DeducedTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006592 TL.setTemplateNameLoc(readSourceLocation());
Richard Smith600b5262017-01-26 20:40:47 +00006593}
6594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006596 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006597}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006598
Guy Benyei11169dd2012-12-18 14:30:41 +00006599void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006600 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006601}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006602
Guy Benyei11169dd2012-12-18 14:30:41 +00006603void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006604 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006605}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006606
Guy Benyei11169dd2012-12-18 14:30:41 +00006607void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006608 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006609}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006610
Guy Benyei11169dd2012-12-18 14:30:41 +00006611void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6612 SubstTemplateTypeParmTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006613 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006614}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006615
Guy Benyei11169dd2012-12-18 14:30:41 +00006616void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6617 SubstTemplateTypeParmPackTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006618 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006619}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006620
Guy Benyei11169dd2012-12-18 14:30:41 +00006621void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6622 TemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006623 TL.setTemplateKeywordLoc(readSourceLocation());
6624 TL.setTemplateNameLoc(readSourceLocation());
6625 TL.setLAngleLoc(readSourceLocation());
6626 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006627 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006628 TL.setArgLocInfo(
6629 i,
John McCall3ce3d232019-12-13 03:37:23 -05006630 Reader.readTemplateArgumentLocInfo(
6631 TL.getTypePtr()->getArg(i).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006632}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006633
Guy Benyei11169dd2012-12-18 14:30:41 +00006634void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006635 TL.setLParenLoc(readSourceLocation());
6636 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006637}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006638
Guy Benyei11169dd2012-12-18 14:30:41 +00006639void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006640 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006641 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006642}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006643
Guy Benyei11169dd2012-12-18 14:30:41 +00006644void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006645 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006646}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006647
Guy Benyei11169dd2012-12-18 14:30:41 +00006648void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006649 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006650 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006651 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006652}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006653
Guy Benyei11169dd2012-12-18 14:30:41 +00006654void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6655 DependentTemplateSpecializationTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006656 TL.setElaboratedKeywordLoc(readSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006657 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -05006658 TL.setTemplateKeywordLoc(readSourceLocation());
6659 TL.setTemplateNameLoc(readSourceLocation());
6660 TL.setLAngleLoc(readSourceLocation());
6661 TL.setRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006662 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006663 TL.setArgLocInfo(
6664 I,
John McCall3ce3d232019-12-13 03:37:23 -05006665 Reader.readTemplateArgumentLocInfo(
6666 TL.getTypePtr()->getArg(I).getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00006667}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006668
Guy Benyei11169dd2012-12-18 14:30:41 +00006669void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006670 TL.setEllipsisLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006671}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006672
Guy Benyei11169dd2012-12-18 14:30:41 +00006673void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006674 TL.setNameLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006675}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006676
Manman Rene6be26c2016-09-13 17:25:08 +00006677void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6678 if (TL.getNumProtocols()) {
John McCall3ce3d232019-12-13 03:37:23 -05006679 TL.setProtocolLAngleLoc(readSourceLocation());
6680 TL.setProtocolRAngleLoc(readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006681 }
6682 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006683 TL.setProtocolLoc(i, readSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006684}
6685
Guy Benyei11169dd2012-12-18 14:30:41 +00006686void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006687 TL.setHasBaseTypeAsWritten(Reader.readBool());
6688 TL.setTypeArgsLAngleLoc(readSourceLocation());
6689 TL.setTypeArgsRAngleLoc(readSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006690 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006691 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
John McCall3ce3d232019-12-13 03:37:23 -05006692 TL.setProtocolLAngleLoc(readSourceLocation());
6693 TL.setProtocolRAngleLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006694 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05006695 TL.setProtocolLoc(i, readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006696}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006697
Guy Benyei11169dd2012-12-18 14:30:41 +00006698void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006699 TL.setStarLoc(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::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006703 TL.setKWLoc(readSourceLocation());
6704 TL.setLParenLoc(readSourceLocation());
6705 TL.setRParenLoc(readSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006706}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006707
Xiuli Pan9c14e282016-01-09 12:53:17 +00006708void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
John McCall3ce3d232019-12-13 03:37:23 -05006709 TL.setKWLoc(readSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006710}
Guy Benyei11169dd2012-12-18 14:30:41 +00006711
John McCall3ce3d232019-12-13 03:37:23 -05006712void ASTRecordReader::readTypeLoc(TypeLoc TL) {
6713 TypeLocReader TLR(*this);
Richard Smithc23d7342018-06-29 20:46:25 +00006714 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6715 TLR.Visit(TL);
6716}
6717
John McCall3ce3d232019-12-13 03:37:23 -05006718TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
6719 QualType InfoTy = readType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006720 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006721 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006722
6723 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
John McCall3ce3d232019-12-13 03:37:23 -05006724 readTypeLoc(TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 return TInfo;
6726}
6727
6728QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006729 assert(ContextObj && "reading type with no AST context");
6730 ASTContext &Context = *ContextObj;
6731
Guy Benyei11169dd2012-12-18 14:30:41 +00006732 unsigned FastQuals = ID & Qualifiers::FastMask;
6733 unsigned Index = ID >> Qualifiers::FastWidth;
6734
6735 if (Index < NUM_PREDEF_TYPE_IDS) {
6736 QualType T;
6737 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006738 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006739 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006740 case PREDEF_TYPE_VOID_ID:
6741 T = Context.VoidTy;
6742 break;
6743 case PREDEF_TYPE_BOOL_ID:
6744 T = Context.BoolTy;
6745 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 case PREDEF_TYPE_CHAR_U_ID:
6747 case PREDEF_TYPE_CHAR_S_ID:
6748 // FIXME: Check that the signedness of CharTy is correct!
6749 T = Context.CharTy;
6750 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006751 case PREDEF_TYPE_UCHAR_ID:
6752 T = Context.UnsignedCharTy;
6753 break;
6754 case PREDEF_TYPE_USHORT_ID:
6755 T = Context.UnsignedShortTy;
6756 break;
6757 case PREDEF_TYPE_UINT_ID:
6758 T = Context.UnsignedIntTy;
6759 break;
6760 case PREDEF_TYPE_ULONG_ID:
6761 T = Context.UnsignedLongTy;
6762 break;
6763 case PREDEF_TYPE_ULONGLONG_ID:
6764 T = Context.UnsignedLongLongTy;
6765 break;
6766 case PREDEF_TYPE_UINT128_ID:
6767 T = Context.UnsignedInt128Ty;
6768 break;
6769 case PREDEF_TYPE_SCHAR_ID:
6770 T = Context.SignedCharTy;
6771 break;
6772 case PREDEF_TYPE_WCHAR_ID:
6773 T = Context.WCharTy;
6774 break;
6775 case PREDEF_TYPE_SHORT_ID:
6776 T = Context.ShortTy;
6777 break;
6778 case PREDEF_TYPE_INT_ID:
6779 T = Context.IntTy;
6780 break;
6781 case PREDEF_TYPE_LONG_ID:
6782 T = Context.LongTy;
6783 break;
6784 case PREDEF_TYPE_LONGLONG_ID:
6785 T = Context.LongLongTy;
6786 break;
6787 case PREDEF_TYPE_INT128_ID:
6788 T = Context.Int128Ty;
6789 break;
6790 case PREDEF_TYPE_HALF_ID:
6791 T = Context.HalfTy;
6792 break;
6793 case PREDEF_TYPE_FLOAT_ID:
6794 T = Context.FloatTy;
6795 break;
6796 case PREDEF_TYPE_DOUBLE_ID:
6797 T = Context.DoubleTy;
6798 break;
6799 case PREDEF_TYPE_LONGDOUBLE_ID:
6800 T = Context.LongDoubleTy;
6801 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006802 case PREDEF_TYPE_SHORT_ACCUM_ID:
6803 T = Context.ShortAccumTy;
6804 break;
6805 case PREDEF_TYPE_ACCUM_ID:
6806 T = Context.AccumTy;
6807 break;
6808 case PREDEF_TYPE_LONG_ACCUM_ID:
6809 T = Context.LongAccumTy;
6810 break;
6811 case PREDEF_TYPE_USHORT_ACCUM_ID:
6812 T = Context.UnsignedShortAccumTy;
6813 break;
6814 case PREDEF_TYPE_UACCUM_ID:
6815 T = Context.UnsignedAccumTy;
6816 break;
6817 case PREDEF_TYPE_ULONG_ACCUM_ID:
6818 T = Context.UnsignedLongAccumTy;
6819 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006820 case PREDEF_TYPE_SHORT_FRACT_ID:
6821 T = Context.ShortFractTy;
6822 break;
6823 case PREDEF_TYPE_FRACT_ID:
6824 T = Context.FractTy;
6825 break;
6826 case PREDEF_TYPE_LONG_FRACT_ID:
6827 T = Context.LongFractTy;
6828 break;
6829 case PREDEF_TYPE_USHORT_FRACT_ID:
6830 T = Context.UnsignedShortFractTy;
6831 break;
6832 case PREDEF_TYPE_UFRACT_ID:
6833 T = Context.UnsignedFractTy;
6834 break;
6835 case PREDEF_TYPE_ULONG_FRACT_ID:
6836 T = Context.UnsignedLongFractTy;
6837 break;
6838 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6839 T = Context.SatShortAccumTy;
6840 break;
6841 case PREDEF_TYPE_SAT_ACCUM_ID:
6842 T = Context.SatAccumTy;
6843 break;
6844 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6845 T = Context.SatLongAccumTy;
6846 break;
6847 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6848 T = Context.SatUnsignedShortAccumTy;
6849 break;
6850 case PREDEF_TYPE_SAT_UACCUM_ID:
6851 T = Context.SatUnsignedAccumTy;
6852 break;
6853 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6854 T = Context.SatUnsignedLongAccumTy;
6855 break;
6856 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6857 T = Context.SatShortFractTy;
6858 break;
6859 case PREDEF_TYPE_SAT_FRACT_ID:
6860 T = Context.SatFractTy;
6861 break;
6862 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6863 T = Context.SatLongFractTy;
6864 break;
6865 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6866 T = Context.SatUnsignedShortFractTy;
6867 break;
6868 case PREDEF_TYPE_SAT_UFRACT_ID:
6869 T = Context.SatUnsignedFractTy;
6870 break;
6871 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6872 T = Context.SatUnsignedLongFractTy;
6873 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006874 case PREDEF_TYPE_FLOAT16_ID:
6875 T = Context.Float16Ty;
6876 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006877 case PREDEF_TYPE_FLOAT128_ID:
6878 T = Context.Float128Ty;
6879 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006880 case PREDEF_TYPE_OVERLOAD_ID:
6881 T = Context.OverloadTy;
6882 break;
6883 case PREDEF_TYPE_BOUND_MEMBER:
6884 T = Context.BoundMemberTy;
6885 break;
6886 case PREDEF_TYPE_PSEUDO_OBJECT:
6887 T = Context.PseudoObjectTy;
6888 break;
6889 case PREDEF_TYPE_DEPENDENT_ID:
6890 T = Context.DependentTy;
6891 break;
6892 case PREDEF_TYPE_UNKNOWN_ANY:
6893 T = Context.UnknownAnyTy;
6894 break;
6895 case PREDEF_TYPE_NULLPTR_ID:
6896 T = Context.NullPtrTy;
6897 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006898 case PREDEF_TYPE_CHAR8_ID:
6899 T = Context.Char8Ty;
6900 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006901 case PREDEF_TYPE_CHAR16_ID:
6902 T = Context.Char16Ty;
6903 break;
6904 case PREDEF_TYPE_CHAR32_ID:
6905 T = Context.Char32Ty;
6906 break;
6907 case PREDEF_TYPE_OBJC_ID:
6908 T = Context.ObjCBuiltinIdTy;
6909 break;
6910 case PREDEF_TYPE_OBJC_CLASS:
6911 T = Context.ObjCBuiltinClassTy;
6912 break;
6913 case PREDEF_TYPE_OBJC_SEL:
6914 T = Context.ObjCBuiltinSelTy;
6915 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006916#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6917 case PREDEF_TYPE_##Id##_ID: \
6918 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006919 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006920#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00006921#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6922 case PREDEF_TYPE_##Id##_ID: \
6923 T = Context.Id##Ty; \
6924 break;
6925#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006926 case PREDEF_TYPE_SAMPLER_ID:
6927 T = Context.OCLSamplerTy;
6928 break;
6929 case PREDEF_TYPE_EVENT_ID:
6930 T = Context.OCLEventTy;
6931 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006932 case PREDEF_TYPE_CLK_EVENT_ID:
6933 T = Context.OCLClkEventTy;
6934 break;
6935 case PREDEF_TYPE_QUEUE_ID:
6936 T = Context.OCLQueueTy;
6937 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006938 case PREDEF_TYPE_RESERVE_ID_ID:
6939 T = Context.OCLReserveIDTy;
6940 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006941 case PREDEF_TYPE_AUTO_DEDUCT:
6942 T = Context.getAutoDeductType();
6943 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006944 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6945 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006947 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6948 T = Context.ARCUnbridgedCastTy;
6949 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006950 case PREDEF_TYPE_BUILTIN_FN:
6951 T = Context.BuiltinFnTy;
6952 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006953 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6954 T = Context.OMPArraySectionTy;
6955 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00006956#define SVE_TYPE(Name, Id, SingletonId) \
6957 case PREDEF_TYPE_##Id##_ID: \
6958 T = Context.SingletonId; \
6959 break;
6960#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 }
6962
6963 assert(!T.isNull() && "Unknown predefined type");
6964 return T.withFastQualifiers(FastQuals);
6965 }
6966
6967 Index -= NUM_PREDEF_TYPE_IDS;
6968 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6969 if (TypesLoaded[Index].isNull()) {
6970 TypesLoaded[Index] = readTypeRecord(Index);
6971 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006972 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006973
6974 TypesLoaded[Index]->setFromAST();
6975 if (DeserializationListener)
6976 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6977 TypesLoaded[Index]);
6978 }
6979
6980 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6981}
6982
6983QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6984 return GetType(getGlobalTypeID(F, LocalID));
6985}
6986
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006987serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006988ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6989 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6990 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006991
Guy Benyei11169dd2012-12-18 14:30:41 +00006992 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6993 return LocalID;
6994
Richard Smith37a93df2017-02-18 00:32:02 +00006995 if (!F.ModuleOffsetMap.empty())
6996 ReadModuleOffsetMap(F);
6997
Guy Benyei11169dd2012-12-18 14:30:41 +00006998 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6999 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7000 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007001
Guy Benyei11169dd2012-12-18 14:30:41 +00007002 unsigned GlobalIndex = LocalIndex + I->second;
7003 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7004}
7005
7006TemplateArgumentLocInfo
John McCall3ce3d232019-12-13 03:37:23 -05007007ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007008 switch (Kind) {
7009 case TemplateArgument::Expression:
John McCall3ce3d232019-12-13 03:37:23 -05007010 return readExpr();
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 case TemplateArgument::Type:
John McCall3ce3d232019-12-13 03:37:23 -05007012 return readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007013 case TemplateArgument::Template: {
John McCall3ce3d232019-12-13 03:37:23 -05007014 NestedNameSpecifierLoc QualifierLoc =
7015 readNestedNameSpecifierLoc();
7016 SourceLocation TemplateNameLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007017 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7018 SourceLocation());
7019 }
7020 case TemplateArgument::TemplateExpansion: {
John McCall3ce3d232019-12-13 03:37:23 -05007021 NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
7022 SourceLocation TemplateNameLoc = readSourceLocation();
7023 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007024 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007025 EllipsisLoc);
7026 }
7027 case TemplateArgument::Null:
7028 case TemplateArgument::Integral:
7029 case TemplateArgument::Declaration:
7030 case TemplateArgument::NullPtr:
7031 case TemplateArgument::Pack:
7032 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007033 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007034 }
7035 llvm_unreachable("unexpected template argument loc");
7036}
7037
John McCall3ce3d232019-12-13 03:37:23 -05007038TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
7039 TemplateArgument Arg = readTemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00007040
7041 if (Arg.getKind() == TemplateArgument::Expression) {
John McCall3ce3d232019-12-13 03:37:23 -05007042 if (readBool()) // bool InfoHasSameExpr.
Guy Benyei11169dd2012-12-18 14:30:41 +00007043 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7044 }
John McCall3ce3d232019-12-13 03:37:23 -05007045 return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
Guy Benyei11169dd2012-12-18 14:30:41 +00007046}
7047
John McCall3ce3d232019-12-13 03:37:23 -05007048const ASTTemplateArgumentListInfo *
7049ASTRecordReader::readASTTemplateArgumentListInfo() {
7050 SourceLocation LAngleLoc = readSourceLocation();
7051 SourceLocation RAngleLoc = readSourceLocation();
7052 unsigned NumArgsAsWritten = readInt();
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007053 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7054 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05007055 TemplArgsInfo.addArgument(readTemplateArgumentLoc());
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007056 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7057}
7058
Guy Benyei11169dd2012-12-18 14:30:41 +00007059Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7060 return GetDecl(ID);
7061}
7062
Richard Smith053f6c62014-05-16 23:01:30 +00007063void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007064 if (NumCurrentElementsDeserializing) {
7065 // We arrange to not care about the complete redeclaration chain while we're
7066 // deserializing. Just remember that the AST has marked this one as complete
7067 // but that it's not actually complete yet, so we know we still need to
7068 // complete it later.
7069 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7070 return;
7071 }
7072
Richard Smith053f6c62014-05-16 23:01:30 +00007073 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7074
Richard Smith053f6c62014-05-16 23:01:30 +00007075 // If this is a named declaration, complete it by looking it up
7076 // within its context.
7077 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007078 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007079 // all mergeable entities within it.
7080 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7081 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7082 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007083 if (!getContext().getLangOpts().CPlusPlus &&
7084 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007085 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007086 // the identifier instead. (For C++ modules, we don't store decls
7087 // in the serialized identifier table, so we do the lookup in the TU.)
7088 auto *II = Name.getAsIdentifierInfo();
7089 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007090 if (II->isOutOfDate())
7091 updateOutOfDateIdentifier(*II);
7092 } else
7093 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007094 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007095 // Find all declarations of this kind from the relevant context.
7096 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7097 auto *DC = cast<DeclContext>(DCDecl);
7098 SmallVector<Decl*, 8> Decls;
7099 FindExternalLexicalDecls(
7100 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7101 }
Richard Smith053f6c62014-05-16 23:01:30 +00007102 }
7103 }
Richard Smith50895422015-01-31 03:04:55 +00007104
7105 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7106 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7107 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7108 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7109 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7110 if (auto *Template = FD->getPrimaryTemplate())
7111 Template->LoadLazySpecializations();
7112 }
Richard Smith053f6c62014-05-16 23:01:30 +00007113}
7114
Richard Smithc2bb8182015-03-24 06:36:48 +00007115CXXCtorInitializer **
7116ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7117 RecordLocation Loc = getLocalBitOffset(Offset);
7118 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7119 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007120 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7121 Error(std::move(Err));
7122 return nullptr;
7123 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007124 ReadingKindTracker ReadingKind(Read_Decl, *this);
7125
JF Bastien0e828952019-06-26 19:50:12 +00007126 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7127 if (!MaybeCode) {
7128 Error(MaybeCode.takeError());
7129 return nullptr;
7130 }
7131 unsigned Code = MaybeCode.get();
7132
John McCall3ce3d232019-12-13 03:37:23 -05007133 ASTRecordReader Record(*this, *Loc.F);
7134 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007135 if (!MaybeRecCode) {
7136 Error(MaybeRecCode.takeError());
7137 return nullptr;
7138 }
7139 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007140 Error("malformed AST file: missing C++ ctor initializers");
7141 return nullptr;
7142 }
7143
John McCall3ce3d232019-12-13 03:37:23 -05007144 return Record.readCXXCtorInitializers();
Richard Smithc2bb8182015-03-24 06:36:48 +00007145}
7146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007148 assert(ContextObj && "reading base specifiers with no AST context");
7149 ASTContext &Context = *ContextObj;
7150
Guy Benyei11169dd2012-12-18 14:30:41 +00007151 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007152 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007154 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7155 Error(std::move(Err));
7156 return nullptr;
7157 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 ReadingKindTracker ReadingKind(Read_Decl, *this);
JF Bastien0e828952019-06-26 19:50:12 +00007159
7160 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7161 if (!MaybeCode) {
7162 Error(MaybeCode.takeError());
7163 return nullptr;
7164 }
7165 unsigned Code = MaybeCode.get();
7166
John McCall3ce3d232019-12-13 03:37:23 -05007167 ASTRecordReader Record(*this, *Loc.F);
7168 Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
JF Bastien0e828952019-06-26 19:50:12 +00007169 if (!MaybeRecCode) {
7170 Error(MaybeCode.takeError());
7171 return nullptr;
7172 }
7173 unsigned RecCode = MaybeRecCode.get();
7174
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007176 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007177 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007178 }
7179
John McCall3ce3d232019-12-13 03:37:23 -05007180 unsigned NumBases = Record.readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007182 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 for (unsigned I = 0; I != NumBases; ++I)
John McCall3ce3d232019-12-13 03:37:23 -05007184 Bases[I] = Record.readCXXBaseSpecifier();
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 return Bases;
7186}
7187
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007188serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007189ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7190 if (LocalID < NUM_PREDEF_DECL_IDS)
7191 return LocalID;
7192
Richard Smith37a93df2017-02-18 00:32:02 +00007193 if (!F.ModuleOffsetMap.empty())
7194 ReadModuleOffsetMap(F);
7195
Guy Benyei11169dd2012-12-18 14:30:41 +00007196 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7197 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7198 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007199
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 return LocalID + I->second;
7201}
7202
7203bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7204 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007205 // Predefined decls aren't from any module.
7206 if (ID < NUM_PREDEF_DECL_IDS)
7207 return false;
7208
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007209 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007210 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007211}
7212
Douglas Gregor9f782892013-01-21 15:25:38 +00007213ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007214 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007215 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007216 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7217 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7218 return I->second;
7219}
7220
7221SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7222 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007223 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007224
Guy Benyei11169dd2012-12-18 14:30:41 +00007225 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7226
7227 if (Index > DeclsLoaded.size()) {
7228 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007229 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007230 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007231
Guy Benyei11169dd2012-12-18 14:30:41 +00007232 if (Decl *D = DeclsLoaded[Index])
7233 return D->getLocation();
7234
Richard Smithcb34bd32016-03-27 07:28:06 +00007235 SourceLocation Loc;
7236 DeclCursorForID(ID, Loc);
7237 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007238}
7239
Richard Smithfe620d22015-03-05 23:24:12 +00007240static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7241 switch (ID) {
7242 case PREDEF_DECL_NULL_ID:
7243 return nullptr;
7244
7245 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7246 return Context.getTranslationUnitDecl();
7247
7248 case PREDEF_DECL_OBJC_ID_ID:
7249 return Context.getObjCIdDecl();
7250
7251 case PREDEF_DECL_OBJC_SEL_ID:
7252 return Context.getObjCSelDecl();
7253
7254 case PREDEF_DECL_OBJC_CLASS_ID:
7255 return Context.getObjCClassDecl();
7256
7257 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7258 return Context.getObjCProtocolDecl();
7259
7260 case PREDEF_DECL_INT_128_ID:
7261 return Context.getInt128Decl();
7262
7263 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7264 return Context.getUInt128Decl();
7265
7266 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7267 return Context.getObjCInstanceTypeDecl();
7268
7269 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7270 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007271
Richard Smith9b88a4c2015-07-27 05:40:23 +00007272 case PREDEF_DECL_VA_LIST_TAG:
7273 return Context.getVaListTagDecl();
7274
Charles Davisc7d5c942015-09-17 20:55:33 +00007275 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7276 return Context.getBuiltinMSVaListDecl();
7277
Richard Smithf19e1272015-03-07 00:04:49 +00007278 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7279 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007280
7281 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7282 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007283
7284 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7285 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007286
7287 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7288 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007289
7290 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7291 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007292 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007293 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007294}
7295
Richard Smithcd45dbc2014-04-19 03:48:30 +00007296Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007297 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007298 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007299 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007300 if (D) {
7301 // Track that we have merged the declaration with ID \p ID into the
7302 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007303 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007304 if (Merged.empty())
7305 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 }
Richard Smithfe620d22015-03-05 23:24:12 +00007307 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007308 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007309
Guy Benyei11169dd2012-12-18 14:30:41 +00007310 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7311
7312 if (Index >= DeclsLoaded.size()) {
7313 assert(0 && "declaration ID out-of-range for AST file");
7314 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007315 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007316 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007317
7318 return DeclsLoaded[Index];
7319}
7320
7321Decl *ASTReader::GetDecl(DeclID ID) {
7322 if (ID < NUM_PREDEF_DECL_IDS)
7323 return GetExistingDecl(ID);
7324
7325 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7326
7327 if (Index >= DeclsLoaded.size()) {
7328 assert(0 && "declaration ID out-of-range for AST file");
7329 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007330 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007331 }
7332
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 if (!DeclsLoaded[Index]) {
7334 ReadDeclRecord(ID);
7335 if (DeserializationListener)
7336 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7337 }
7338
7339 return DeclsLoaded[Index];
7340}
7341
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007342DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007343 DeclID GlobalID) {
7344 if (GlobalID < NUM_PREDEF_DECL_IDS)
7345 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007346
Guy Benyei11169dd2012-12-18 14:30:41 +00007347 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7348 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7349 ModuleFile *Owner = I->second;
7350
7351 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7352 = M.GlobalToLocalDeclIDs.find(Owner);
7353 if (Pos == M.GlobalToLocalDeclIDs.end())
7354 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007355
Guy Benyei11169dd2012-12-18 14:30:41 +00007356 return GlobalID - Owner->BaseDeclID + Pos->second;
7357}
7358
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007359serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007360 const RecordData &Record,
7361 unsigned &Idx) {
7362 if (Idx >= Record.size()) {
7363 Error("Corrupted AST file");
7364 return 0;
7365 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007366
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 return getGlobalDeclID(F, Record[Idx++]);
7368}
7369
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007370/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007371///
7372/// This operation will read a new statement from the external
7373/// source each time it is called, and is meant to be used via a
7374/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7375Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7376 // Switch case IDs are per Decl.
7377 ClearSwitchCaseIDs();
7378
7379 // Offset here is a global offset across the entire chain.
7380 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007381 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7382 Error(std::move(Err));
7383 return nullptr;
7384 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007385 assert(NumCurrentElementsDeserializing == 0 &&
7386 "should not be called while already deserializing");
7387 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007388 return ReadStmtFromStream(*Loc.F);
7389}
7390
Richard Smith3cb15722015-08-05 22:41:45 +00007391void ASTReader::FindExternalLexicalDecls(
7392 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7393 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007394 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7395
Richard Smith9ccdd932015-08-06 22:14:12 +00007396 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007397 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7398 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7399 auto K = (Decl::Kind)+LexicalDecls[I];
7400 if (!IsKindWeWant(K))
7401 continue;
7402
7403 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7404
7405 // Don't add predefined declarations to the lexical context more
7406 // than once.
7407 if (ID < NUM_PREDEF_DECL_IDS) {
7408 if (PredefsVisited[ID])
7409 continue;
7410
7411 PredefsVisited[ID] = true;
7412 }
7413
7414 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007415 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007416 if (!DC->isDeclInLexicalTraversal(D))
7417 Decls.push_back(D);
7418 }
7419 }
7420 };
7421
7422 if (isa<TranslationUnitDecl>(DC)) {
7423 for (auto Lexical : TULexicalDecls)
7424 Visit(Lexical.first, Lexical.second);
7425 } else {
7426 auto I = LexicalDecls.find(DC);
7427 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007428 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007429 }
7430
Guy Benyei11169dd2012-12-18 14:30:41 +00007431 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007432}
7433
7434namespace {
7435
7436class DeclIDComp {
7437 ASTReader &Reader;
7438 ModuleFile &Mod;
7439
7440public:
7441 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7442
7443 bool operator()(LocalDeclID L, LocalDeclID R) const {
7444 SourceLocation LHS = getLocation(L);
7445 SourceLocation RHS = getLocation(R);
7446 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7447 }
7448
7449 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7450 SourceLocation RHS = getLocation(R);
7451 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7452 }
7453
7454 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7455 SourceLocation LHS = getLocation(L);
7456 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7457 }
7458
7459 SourceLocation getLocation(LocalDeclID ID) const {
7460 return Reader.getSourceManager().getFileLoc(
7461 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7462 }
7463};
7464
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007465} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007466
7467void ASTReader::FindFileRegionDecls(FileID File,
7468 unsigned Offset, unsigned Length,
7469 SmallVectorImpl<Decl *> &Decls) {
7470 SourceManager &SM = getSourceManager();
7471
7472 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7473 if (I == FileDeclIDs.end())
7474 return;
7475
7476 FileDeclsInfo &DInfo = I->second;
7477 if (DInfo.Decls.empty())
7478 return;
7479
7480 SourceLocation
7481 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7482 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7483
7484 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007485 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7486 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 if (BeginIt != DInfo.Decls.begin())
7488 --BeginIt;
7489
7490 // If we are pointing at a top-level decl inside an objc container, we need
7491 // to backtrack until we find it otherwise we will fail to report that the
7492 // region overlaps with an objc container.
7493 while (BeginIt != DInfo.Decls.begin() &&
7494 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7495 ->isTopLevelDeclInObjCContainer())
7496 --BeginIt;
7497
Fangrui Song7264a472019-07-03 08:13:17 +00007498 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7499 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007500 if (EndIt != DInfo.Decls.end())
7501 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007502
Guy Benyei11169dd2012-12-18 14:30:41 +00007503 for (ArrayRef<serialization::LocalDeclID>::iterator
7504 DIt = BeginIt; DIt != EndIt; ++DIt)
7505 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7506}
7507
Richard Smith9ce12e32013-02-07 03:30:24 +00007508bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007509ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7510 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007511 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007512 "DeclContext has no visible decls in storage");
7513 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007514 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007515
Richard Smithd88a7f12015-09-01 20:35:42 +00007516 auto It = Lookups.find(DC);
7517 if (It == Lookups.end())
7518 return false;
7519
Richard Smith8c913ec2014-08-14 02:21:01 +00007520 Deserializing LookupResults(this);
7521
Richard Smithd88a7f12015-09-01 20:35:42 +00007522 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007524 for (DeclID ID : It->second.Table.find(Name)) {
7525 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007526 if (ND->getDeclName() == Name)
7527 Decls.push_back(ND);
7528 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007529
Guy Benyei11169dd2012-12-18 14:30:41 +00007530 ++NumVisibleDeclContextsRead;
7531 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007532 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007533}
7534
Guy Benyei11169dd2012-12-18 14:30:41 +00007535void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7536 if (!DC->hasExternalVisibleStorage())
7537 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007538
7539 auto It = Lookups.find(DC);
7540 assert(It != Lookups.end() &&
7541 "have external visible storage but no lookup tables");
7542
Craig Topper79be4cd2013-07-05 04:33:53 +00007543 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007544
Vedant Kumar48b4f762018-04-14 01:40:48 +00007545 for (DeclID ID : It->second.Table.findAll()) {
7546 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007547 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007548 }
7549
Guy Benyei11169dd2012-12-18 14:30:41 +00007550 ++NumVisibleDeclContextsRead;
7551
Vedant Kumar48b4f762018-04-14 01:40:48 +00007552 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7553 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7554 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007555 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7556}
7557
Richard Smithd88a7f12015-09-01 20:35:42 +00007558const serialization::reader::DeclContextLookupTable *
7559ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7560 auto I = Lookups.find(Primary);
7561 return I == Lookups.end() ? nullptr : &I->second;
7562}
7563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007564/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007565/// before receiving the implementation, and codegen depends on this.
7566/// We simulate this by deserializing and passing to consumer the methods of the
7567/// implementation before passing the deserialized implementation decl.
7568static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7569 ASTConsumer *Consumer) {
7570 assert(ImplD && Consumer);
7571
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007572 for (auto *I : ImplD->methods())
7573 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007574
7575 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7576}
7577
Guy Benyei11169dd2012-12-18 14:30:41 +00007578void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007579 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007580 PassObjCImplDeclToConsumer(ImplD, Consumer);
7581 else
7582 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7583}
7584
7585void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7586 this->Consumer = Consumer;
7587
Richard Smith9e2341d2015-03-23 03:25:59 +00007588 if (Consumer)
7589 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007590
7591 if (DeserializationListener)
7592 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007593}
7594
7595void ASTReader::PrintStats() {
7596 std::fprintf(stderr, "*** AST File Statistics:\n");
7597
7598 unsigned NumTypesLoaded
7599 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7600 QualType());
7601 unsigned NumDeclsLoaded
7602 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007603 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007604 unsigned NumIdentifiersLoaded
7605 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7606 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007607 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007608 unsigned NumMacrosLoaded
7609 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7610 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007611 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 unsigned NumSelectorsLoaded
7613 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7614 SelectorsLoaded.end(),
7615 Selector());
7616
7617 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7618 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7619 NumSLocEntriesRead, TotalNumSLocEntries,
7620 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7621 if (!TypesLoaded.empty())
7622 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7623 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7624 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7625 if (!DeclsLoaded.empty())
7626 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7627 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7628 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7629 if (!IdentifiersLoaded.empty())
7630 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7631 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7632 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7633 if (!MacrosLoaded.empty())
7634 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7635 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7636 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7637 if (!SelectorsLoaded.empty())
7638 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7639 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7640 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7641 if (TotalNumStatements)
7642 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7643 NumStatementsRead, TotalNumStatements,
7644 ((float)NumStatementsRead/TotalNumStatements * 100));
7645 if (TotalNumMacros)
7646 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7647 NumMacrosRead, TotalNumMacros,
7648 ((float)NumMacrosRead/TotalNumMacros * 100));
7649 if (TotalLexicalDeclContexts)
7650 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7651 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7652 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7653 * 100));
7654 if (TotalVisibleDeclContexts)
7655 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7656 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7657 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7658 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007659 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007660 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7661 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7662 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7663 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007664 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007665 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7666 NumMethodPoolHits, NumMethodPoolLookups,
7667 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007668 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007669 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7670 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7671 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7672 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007673 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007674 std::fprintf(stderr,
7675 " %u / %u identifier table lookups succeeded (%f%%)\n",
7676 NumIdentifierLookupHits, NumIdentifierLookups,
7677 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007678
Douglas Gregore060e572013-01-25 01:03:03 +00007679 if (GlobalIndex) {
7680 std::fprintf(stderr, "\n");
7681 GlobalIndex->printStats();
7682 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007683
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 std::fprintf(stderr, "\n");
7685 dump();
7686 std::fprintf(stderr, "\n");
7687}
7688
7689template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007690LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007691dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007692 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007693 InitialCapacity> &Map) {
7694 if (Map.begin() == Map.end())
7695 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007696
Vedant Kumar48b4f762018-04-14 01:40:48 +00007697 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7698
Guy Benyei11169dd2012-12-18 14:30:41 +00007699 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007700 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7701 I != IEnd; ++I) {
7702 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7703 << "\n";
7704 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007705}
7706
Yaron Kerencdae9412016-01-29 19:38:18 +00007707LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7709 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7710 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7711 dumpModuleIDMap("Global type map", GlobalTypeMap);
7712 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7713 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7714 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7715 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7716 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007717 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007719
Guy Benyei11169dd2012-12-18 14:30:41 +00007720 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007721 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007722 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007723}
7724
7725/// Return the amount of memory used by memory buffers, breaking down
7726/// by heap-backed versus mmap'ed memory.
7727void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007728 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007729 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007730 size_t bytes = buf->getBufferSize();
7731 switch (buf->getBufferKind()) {
7732 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7733 sizes.malloc_bytes += bytes;
7734 break;
7735 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7736 sizes.mmap_bytes += bytes;
7737 break;
7738 }
7739 }
7740 }
7741}
7742
7743void ASTReader::InitializeSema(Sema &S) {
7744 SemaObj = &S;
7745 S.addExternalSource(this);
7746
7747 // Makes sure any declarations that were deserialized "too early"
7748 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007749 for (uint64_t ID : PreloadedDeclIDs) {
7750 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007751 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007753 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007754
Richard Smith3d8e97e2013-10-18 06:54:39 +00007755 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007756 if (!FPPragmaOptions.empty()) {
7757 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007758 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007759 }
7760
Yaxun Liu5b746652016-12-18 05:18:55 +00007761 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7762 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7763 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007764
7765 UpdateSema();
7766}
7767
7768void ASTReader::UpdateSema() {
7769 assert(SemaObj && "no Sema to update");
7770
7771 // Load the offsets of the declarations that Sema references.
7772 // They will be lazily deserialized when needed.
7773 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007774 assert(SemaDeclRefs.size() % 3 == 0);
7775 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007776 if (!SemaObj->StdNamespace)
7777 SemaObj->StdNamespace = SemaDeclRefs[I];
7778 if (!SemaObj->StdBadAlloc)
7779 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007780 if (!SemaObj->StdAlignValT)
7781 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007782 }
7783 SemaDeclRefs.clear();
7784 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007785
Nico Weber779355f2016-03-02 23:22:00 +00007786 // Update the state of pragmas. Use the same API as if we had encountered the
7787 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007788 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007789 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007790 if (PragmaMSStructState != -1)
7791 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007792 if (PointersToMembersPragmaLocation.isValid()) {
7793 SemaObj->ActOnPragmaMSPointersToMembers(
7794 (LangOptions::PragmaMSPointersToMembersKind)
7795 PragmaMSPointersToMembersState,
7796 PointersToMembersPragmaLocation);
7797 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007798 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007799
7800 if (PragmaPackCurrentValue) {
7801 // The bottom of the stack might have a default value. It must be adjusted
7802 // to the current value to ensure that the packing state is preserved after
7803 // popping entries that were included/imported from a PCH/module.
7804 bool DropFirst = false;
7805 if (!PragmaPackStack.empty() &&
7806 PragmaPackStack.front().Location.isInvalid()) {
7807 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7808 "Expected a default alignment value");
7809 SemaObj->PackStack.Stack.emplace_back(
7810 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007811 SemaObj->PackStack.CurrentPragmaLocation,
7812 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007813 DropFirst = true;
7814 }
7815 for (const auto &Entry :
7816 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7817 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007818 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007819 if (PragmaPackCurrentLocation.isInvalid()) {
7820 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7821 "Expected a default alignment value");
7822 // Keep the current values.
7823 } else {
7824 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7825 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7826 }
7827 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007828}
7829
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007830IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007831 // Note that we are loading an identifier.
7832 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007833
Douglas Gregor7211ac12013-01-25 23:32:03 +00007834 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007835 NumIdentifierLookups,
7836 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007837
7838 // We don't need to do identifier table lookups in C++ modules (we preload
7839 // all interesting declarations, and don't need to use the scope for name
7840 // lookups). Perform the lookup in PCH files, though, since we don't build
7841 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007842 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007843 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007844 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007845 break;
7846 } else {
7847 // If there is a global index, look there first to determine which modules
7848 // provably do not have any results for this identifier.
7849 GlobalModuleIndex::HitSet Hits;
7850 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7851 if (!loadGlobalIndex()) {
7852 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7853 HitsPtr = &Hits;
7854 }
7855 }
7856
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007857 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007858 }
7859
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 IdentifierInfo *II = Visitor.getIdentifierInfo();
7861 markIdentifierUpToDate(II);
7862 return II;
7863}
7864
7865namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007866
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007867 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007868 /// identifiers stored within a set of AST files.
7869 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007870 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007871 const ASTReader &Reader;
7872
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007873 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007874 /// the AST reader.
7875 unsigned Index;
7876
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007877 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 /// of the current AST file.
7879 ASTIdentifierLookupTable::key_iterator Current;
7880
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007881 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007882 /// the current AST file.
7883 ASTIdentifierLookupTable::key_iterator End;
7884
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007885 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007886 bool SkipModules;
7887
Guy Benyei11169dd2012-12-18 14:30:41 +00007888 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007889 explicit ASTIdentifierIterator(const ASTReader &Reader,
7890 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007891
Craig Topper3e89dfe2014-03-13 02:13:41 +00007892 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007893 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007894
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007895} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007896
Ben Langmuir537c5b52016-05-04 00:53:13 +00007897ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7898 bool SkipModules)
7899 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007900}
7901
7902StringRef ASTIdentifierIterator::Next() {
7903 while (Current == End) {
7904 // If we have exhausted all of our AST files, we're done.
7905 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007906 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007907
7908 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007909 ModuleFile &F = Reader.ModuleMgr[Index];
7910 if (SkipModules && F.isModule())
7911 continue;
7912
Vedant Kumar48b4f762018-04-14 01:40:48 +00007913 ASTIdentifierLookupTable *IdTable =
7914 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 Current = IdTable->key_begin();
7916 End = IdTable->key_end();
7917 }
7918
7919 // We have any identifiers remaining in the current AST file; return
7920 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007921 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007922 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007923 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007924}
7925
Ben Langmuir537c5b52016-05-04 00:53:13 +00007926namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007927
Ben Langmuir537c5b52016-05-04 00:53:13 +00007928/// A utility for appending two IdentifierIterators.
7929class ChainedIdentifierIterator : public IdentifierIterator {
7930 std::unique_ptr<IdentifierIterator> Current;
7931 std::unique_ptr<IdentifierIterator> Queued;
7932
7933public:
7934 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7935 std::unique_ptr<IdentifierIterator> Second)
7936 : Current(std::move(First)), Queued(std::move(Second)) {}
7937
7938 StringRef Next() override {
7939 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007940 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007941
7942 StringRef result = Current->Next();
7943 if (!result.empty())
7944 return result;
7945
7946 // Try the queued iterator, which may itself be empty.
7947 Current.reset();
7948 std::swap(Current, Queued);
7949 return Next();
7950 }
7951};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007952
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007953} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007954
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007955IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007956 if (!loadGlobalIndex()) {
7957 std::unique_ptr<IdentifierIterator> ReaderIter(
7958 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7959 std::unique_ptr<IdentifierIterator> ModulesIter(
7960 GlobalIndex->createIdentifierIterator());
7961 return new ChainedIdentifierIterator(std::move(ReaderIter),
7962 std::move(ModulesIter));
7963 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007964
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 return new ASTIdentifierIterator(*this);
7966}
7967
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007968namespace clang {
7969namespace serialization {
7970
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 class ReadMethodPoolVisitor {
7972 ASTReader &Reader;
7973 Selector Sel;
7974 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007975 unsigned InstanceBits = 0;
7976 unsigned FactoryBits = 0;
7977 bool InstanceHasMoreThanOneDecl = false;
7978 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007979 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7980 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007981
7982 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007983 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007984 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007985 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007986
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007987 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007988 if (!M.SelectorLookupTable)
7989 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007990
Guy Benyei11169dd2012-12-18 14:30:41 +00007991 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007992 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007993 return true;
7994
Richard Smithbdf2d932015-07-30 03:37:16 +00007995 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007996 ASTSelectorLookupTable *PoolTable
7997 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007998 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007999 if (Pos == PoolTable->end())
8000 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008001
Richard Smithbdf2d932015-07-30 03:37:16 +00008002 ++Reader.NumMethodPoolTableHits;
8003 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 // FIXME: Not quite happy with the statistics here. We probably should
8005 // disable this tracking when called via LoadSelector.
8006 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008007 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008008 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008009 if (Reader.DeserializationListener)
8010 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008011
Richard Smithbdf2d932015-07-30 03:37:16 +00008012 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8013 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8014 InstanceBits = Data.InstanceBits;
8015 FactoryBits = Data.FactoryBits;
8016 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8017 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008018 return true;
8019 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008020
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008021 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008022 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8023 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 }
8025
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008026 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008027 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 return FactoryMethods;
8029 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008030
8031 unsigned getInstanceBits() const { return InstanceBits; }
8032 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008033
Nico Weberff4b35e2014-12-27 22:14:15 +00008034 bool instanceHasMoreThanOneDecl() const {
8035 return InstanceHasMoreThanOneDecl;
8036 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008037
Nico Weberff4b35e2014-12-27 22:14:15 +00008038 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008039 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008040
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008041} // namespace serialization
8042} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008044/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008045static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8046 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008047 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8048 S.addMethodToGlobalList(&List, Methods[I]);
8049 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008050}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008051
Guy Benyei11169dd2012-12-18 14:30:41 +00008052void ASTReader::ReadMethodPool(Selector Sel) {
8053 // Get the selector generation and update it to the current generation.
8054 unsigned &Generation = SelectorGeneration[Sel];
8055 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008056 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008057 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008058
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008060 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008062 ModuleMgr.visit(Visitor);
8063
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008065 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008066 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008067
8068 ++NumMethodPoolHits;
8069
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 if (!getSema())
8071 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008072
Guy Benyei11169dd2012-12-18 14:30:41 +00008073 Sema &S = *getSema();
8074 Sema::GlobalMethodPool::iterator Pos
8075 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008076
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008077 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008078 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008079 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008080 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008081
8082 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8083 // when building a module we keep every method individually and may need to
8084 // update hasMoreThanOneDecl as we add the methods.
8085 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8086 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008087}
8088
Manman Rena0f31a02016-04-29 19:04:05 +00008089void ASTReader::updateOutOfDateSelector(Selector Sel) {
8090 if (SelectorOutOfDate[Sel])
8091 ReadMethodPool(Sel);
8092}
8093
Guy Benyei11169dd2012-12-18 14:30:41 +00008094void ASTReader::ReadKnownNamespaces(
8095 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8096 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008097
Vedant Kumar48b4f762018-04-14 01:40:48 +00008098 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8099 if (NamespaceDecl *Namespace
8100 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008101 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008102 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008103}
8104
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008105void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008106 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008107 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008108 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008109 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008110 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008111 Undefined.insert(std::make_pair(D, Loc));
8112 }
8113}
Nick Lewycky8334af82013-01-26 00:35:08 +00008114
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008115void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8116 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8117 Exprs) {
8118 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008119 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008120 uint64_t Count = DelayedDeleteExprs[Idx++];
8121 for (uint64_t C = 0; C < Count; ++C) {
8122 SourceLocation DeleteLoc =
8123 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8124 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8125 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8126 }
8127 }
8128}
8129
Guy Benyei11169dd2012-12-18 14:30:41 +00008130void ASTReader::ReadTentativeDefinitions(
8131 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008132 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8133 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008134 if (Var)
8135 TentativeDefs.push_back(Var);
8136 }
8137 TentativeDefinitions.clear();
8138}
8139
8140void ASTReader::ReadUnusedFileScopedDecls(
8141 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008142 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8143 DeclaratorDecl *D
8144 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008145 if (D)
8146 Decls.push_back(D);
8147 }
8148 UnusedFileScopedDecls.clear();
8149}
8150
8151void ASTReader::ReadDelegatingConstructors(
8152 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008153 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8154 CXXConstructorDecl *D
8155 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008156 if (D)
8157 Decls.push_back(D);
8158 }
8159 DelegatingCtorDecls.clear();
8160}
8161
8162void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008163 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8164 TypedefNameDecl *D
8165 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 if (D)
8167 Decls.push_back(D);
8168 }
8169 ExtVectorDecls.clear();
8170}
8171
Nico Weber72889432014-09-06 01:25:55 +00008172void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8173 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008174 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8175 ++I) {
8176 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8177 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008178 if (D)
8179 Decls.insert(D);
8180 }
8181 UnusedLocalTypedefNameCandidates.clear();
8182}
8183
Guy Benyei11169dd2012-12-18 14:30:41 +00008184void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008185 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 if (ReferencedSelectorsData.empty())
8187 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008188
Guy Benyei11169dd2012-12-18 14:30:41 +00008189 // If there are @selector references added them to its pool. This is for
8190 // implementation of -Wselector.
8191 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8192 unsigned I = 0;
8193 while (I < DataSize) {
8194 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8195 SourceLocation SelLoc
8196 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8197 Sels.push_back(std::make_pair(Sel, SelLoc));
8198 }
8199 ReferencedSelectorsData.clear();
8200}
8201
8202void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008203 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 if (WeakUndeclaredIdentifiers.empty())
8205 return;
8206
8207 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008208 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008209 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008210 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8212 SourceLocation Loc
8213 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8214 bool Used = WeakUndeclaredIdentifiers[I++];
8215 WeakInfo WI(AliasId, Loc);
8216 WI.setUsed(Used);
8217 WeakIDs.push_back(std::make_pair(WeakId, WI));
8218 }
8219 WeakUndeclaredIdentifiers.clear();
8220}
8221
8222void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8223 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8224 ExternalVTableUse VT;
8225 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8226 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8227 VT.DefinitionRequired = VTableUses[Idx++];
8228 VTables.push_back(VT);
8229 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008230
Guy Benyei11169dd2012-12-18 14:30:41 +00008231 VTableUses.clear();
8232}
8233
8234void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008235 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008237 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008238 SourceLocation Loc
8239 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8240
8241 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008243 PendingInstantiations.clear();
8244}
8245
Richard Smithe40f2ba2013-08-07 21:41:30 +00008246void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008247 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8248 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008249 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8250 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008251 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008252
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008253 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008254 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8255
8256 ModuleFile *F = getOwningModuleFile(LT->D);
8257 assert(F && "No module");
8258
8259 unsigned TokN = LateParsedTemplates[Idx++];
8260 LT->Toks.reserve(TokN);
8261 for (unsigned T = 0; T < TokN; ++T)
8262 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8263
Justin Lebar28f09c52016-10-10 16:26:08 +00008264 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008265 }
8266
8267 LateParsedTemplates.clear();
8268}
8269
Guy Benyei11169dd2012-12-18 14:30:41 +00008270void ASTReader::LoadSelector(Selector Sel) {
8271 // It would be complicated to avoid reading the methods anyway. So don't.
8272 ReadMethodPool(Sel);
8273}
8274
8275void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8276 assert(ID && "Non-zero identifier ID required");
8277 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8278 IdentifiersLoaded[ID - 1] = II;
8279 if (DeserializationListener)
8280 DeserializationListener->IdentifierRead(ID, II);
8281}
8282
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008283/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008284/// identifier.
8285///
8286/// If the AST reader is currently in a state where the given declaration IDs
8287/// cannot safely be resolved, they are queued until it is safe to resolve
8288/// them.
8289///
8290/// \param II an IdentifierInfo that refers to one or more globally-visible
8291/// declarations.
8292///
8293/// \param DeclIDs the set of declaration IDs with the name @p II that are
8294/// visible at global scope.
8295///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008296/// \param Decls if non-null, this vector will be populated with the set of
8297/// deserialized declarations. These declarations will not be pushed into
8298/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008299void
8300ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8301 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008302 SmallVectorImpl<Decl *> *Decls) {
8303 if (NumCurrentElementsDeserializing && !Decls) {
8304 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008305 return;
8306 }
8307
Vedant Kumar48b4f762018-04-14 01:40:48 +00008308 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008309 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008310 // Queue this declaration so that it will be added to the
8311 // translation unit scope and identifier's declaration chain
8312 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008313 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008314 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008316
Vedant Kumar48b4f762018-04-14 01:40:48 +00008317 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008318
8319 // If we're simply supposed to record the declarations, do so now.
8320 if (Decls) {
8321 Decls->push_back(D);
8322 continue;
8323 }
8324
8325 // Introduce this declaration into the translation-unit scope
8326 // and add it to the declaration chain for this identifier, so
8327 // that (unqualified) name lookup will find it.
8328 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008329 }
8330}
8331
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008332IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008333 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008334 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008335
8336 if (IdentifiersLoaded.empty()) {
8337 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008338 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008339 }
8340
8341 ID -= 1;
8342 if (!IdentifiersLoaded[ID]) {
8343 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8344 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8345 ModuleFile *M = I->second;
8346 unsigned Index = ID - M->BaseIdentifierID;
8347 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8348
8349 // All of the strings in the AST file are preceded by a 16-bit length.
8350 // Extract that 16-bit length to avoid having to execute strlen().
8351 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8352 // unsigned integers. This is important to avoid integer overflow when
8353 // we cast them to 'unsigned'.
8354 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8355 unsigned StrLen = (((unsigned) StrLenPtr[0])
8356 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008357 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8358 IdentifiersLoaded[ID] = &II;
8359 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008361 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008362 }
8363
8364 return IdentifiersLoaded[ID];
8365}
8366
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008367IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8368 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008369}
8370
8371IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8372 if (LocalID < NUM_PREDEF_IDENT_IDS)
8373 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008374
Richard Smith37a93df2017-02-18 00:32:02 +00008375 if (!M.ModuleOffsetMap.empty())
8376 ReadModuleOffsetMap(M);
8377
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8379 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008380 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008381 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008382
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 return LocalID + I->second;
8384}
8385
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008386MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008387 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008388 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008389
8390 if (MacrosLoaded.empty()) {
8391 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008392 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008393 }
8394
8395 ID -= NUM_PREDEF_MACRO_IDS;
8396 if (!MacrosLoaded[ID]) {
8397 GlobalMacroMapType::iterator I
8398 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8399 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8400 ModuleFile *M = I->second;
8401 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008402 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008403
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008404 if (DeserializationListener)
8405 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8406 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008407 }
8408
8409 return MacrosLoaded[ID];
8410}
8411
8412MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8413 if (LocalID < NUM_PREDEF_MACRO_IDS)
8414 return LocalID;
8415
Richard Smith37a93df2017-02-18 00:32:02 +00008416 if (!M.ModuleOffsetMap.empty())
8417 ReadModuleOffsetMap(M);
8418
Guy Benyei11169dd2012-12-18 14:30:41 +00008419 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8420 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8421 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8422
8423 return LocalID + I->second;
8424}
8425
8426serialization::SubmoduleID
8427ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8428 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8429 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008430
Richard Smith37a93df2017-02-18 00:32:02 +00008431 if (!M.ModuleOffsetMap.empty())
8432 ReadModuleOffsetMap(M);
8433
Guy Benyei11169dd2012-12-18 14:30:41 +00008434 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8435 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008436 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008437 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008438
Guy Benyei11169dd2012-12-18 14:30:41 +00008439 return LocalID + I->second;
8440}
8441
8442Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8443 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8444 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008445 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008446 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008447
Guy Benyei11169dd2012-12-18 14:30:41 +00008448 if (GlobalID > SubmodulesLoaded.size()) {
8449 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008450 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008451 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008452
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8454}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008455
8456Module *ASTReader::getModule(unsigned ID) {
8457 return getSubmodule(ID);
8458}
8459
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008460bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8461 ModuleFile *MF = getOwningModuleFile(D);
8462 return MF && MF->PCHHasObjectFile;
8463}
8464
Richard Smithd88a7f12015-09-01 20:35:42 +00008465ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8466 if (ID & 1) {
8467 // It's a module, look it up by submodule ID.
8468 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8469 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8470 } else {
8471 // It's a prefix (preamble, PCH, ...). Look it up by index.
8472 unsigned IndexFromEnd = ID >> 1;
8473 assert(IndexFromEnd && "got reference to unknown module file");
8474 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8475 }
8476}
8477
8478unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8479 if (!F)
8480 return 1;
8481
8482 // For a file representing a module, use the submodule ID of the top-level
8483 // module as the file ID. For any other kind of file, the number of such
8484 // files loaded beforehand will be the same on reload.
8485 // FIXME: Is this true even if we have an explicit module file and a PCH?
8486 if (F->isModule())
8487 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8488
8489 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008490 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008491 assert(I != PCHModules.end() && "emitting reference to unknown file");
8492 return (I - PCHModules.end()) << 1;
8493}
8494
Adrian Prantl15bcf702015-06-30 17:39:43 +00008495llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8496ASTReader::getSourceDescriptor(unsigned ID) {
8497 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008498 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008499
8500 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008501 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008502 const auto &PCHChain = ModuleMgr.pch_modules();
8503 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008504 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008505 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008506 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8507 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8508 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008509 }
8510 return None;
8511}
8512
David Blaikie1ac9c982017-04-11 21:13:37 +00008513ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008514 auto I = DefinitionSource.find(FD);
8515 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008516 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008517 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008518}
8519
Guy Benyei11169dd2012-12-18 14:30:41 +00008520Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8521 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8522}
8523
8524Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8525 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008526 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008527
8528 if (ID > SelectorsLoaded.size()) {
8529 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008530 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008531 }
8532
Craig Toppera13603a2014-05-22 05:54:18 +00008533 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008534 // Load this selector from the selector table.
8535 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8536 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8537 ModuleFile &M = *I->second;
8538 ASTSelectorLookupTrait Trait(*this, M);
8539 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8540 SelectorsLoaded[ID - 1] =
8541 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8542 if (DeserializationListener)
8543 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8544 }
8545
8546 return SelectorsLoaded[ID - 1];
8547}
8548
8549Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8550 return DecodeSelector(ID);
8551}
8552
8553uint32_t ASTReader::GetNumExternalSelectors() {
8554 // ID 0 (the null selector) is considered an external selector.
8555 return getTotalNumSelectors() + 1;
8556}
8557
8558serialization::SelectorID
8559ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8560 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8561 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008562
Richard Smith37a93df2017-02-18 00:32:02 +00008563 if (!M.ModuleOffsetMap.empty())
8564 ReadModuleOffsetMap(M);
8565
Guy Benyei11169dd2012-12-18 14:30:41 +00008566 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8567 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008568 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008569 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008570
Guy Benyei11169dd2012-12-18 14:30:41 +00008571 return LocalID + I->second;
8572}
8573
John McCall3ce3d232019-12-13 03:37:23 -05008574DeclarationNameLoc
8575ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
8576 DeclarationNameLoc DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008577 switch (Name.getNameKind()) {
8578 case DeclarationName::CXXConstructorName:
8579 case DeclarationName::CXXDestructorName:
8580 case DeclarationName::CXXConversionFunctionName:
John McCall3ce3d232019-12-13 03:37:23 -05008581 DNLoc.NamedType.TInfo = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008582 break;
8583
8584 case DeclarationName::CXXOperatorName:
8585 DNLoc.CXXOperatorName.BeginOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008586 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008587 DNLoc.CXXOperatorName.EndOpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008588 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008589 break;
8590
8591 case DeclarationName::CXXLiteralOperatorName:
8592 DNLoc.CXXLiteralOperatorName.OpNameLoc
John McCall3ce3d232019-12-13 03:37:23 -05008593 = readSourceLocation().getRawEncoding();
Guy Benyei11169dd2012-12-18 14:30:41 +00008594 break;
8595
8596 case DeclarationName::Identifier:
8597 case DeclarationName::ObjCZeroArgSelector:
8598 case DeclarationName::ObjCOneArgSelector:
8599 case DeclarationName::ObjCMultiArgSelector:
8600 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008601 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008602 break;
8603 }
John McCall3ce3d232019-12-13 03:37:23 -05008604 return DNLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00008605}
8606
John McCall3ce3d232019-12-13 03:37:23 -05008607DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
8608 DeclarationNameInfo NameInfo;
8609 NameInfo.setName(readDeclarationName());
8610 NameInfo.setLoc(readSourceLocation());
8611 NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
8612 return NameInfo;
Guy Benyei11169dd2012-12-18 14:30:41 +00008613}
8614
John McCall3ce3d232019-12-13 03:37:23 -05008615void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
8616 Info.QualifierLoc = readNestedNameSpecifierLoc();
8617 unsigned NumTPLists = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008618 Info.NumTemplParamLists = NumTPLists;
8619 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008620 Info.TemplParamLists =
8621 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008622 for (unsigned i = 0; i != NumTPLists; ++i)
John McCall3ce3d232019-12-13 03:37:23 -05008623 Info.TemplParamLists[i] = readTemplateParameterList();
Guy Benyei11169dd2012-12-18 14:30:41 +00008624 }
8625}
8626
Guy Benyei11169dd2012-12-18 14:30:41 +00008627TemplateParameterList *
John McCall3ce3d232019-12-13 03:37:23 -05008628ASTRecordReader::readTemplateParameterList() {
8629 SourceLocation TemplateLoc = readSourceLocation();
8630 SourceLocation LAngleLoc = readSourceLocation();
8631 SourceLocation RAngleLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008632
John McCall3ce3d232019-12-13 03:37:23 -05008633 unsigned NumParams = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008634 SmallVector<NamedDecl *, 16> Params;
8635 Params.reserve(NumParams);
8636 while (NumParams--)
John McCall3ce3d232019-12-13 03:37:23 -05008637 Params.push_back(readDeclAs<NamedDecl>());
Guy Benyei11169dd2012-12-18 14:30:41 +00008638
John McCall3ce3d232019-12-13 03:37:23 -05008639 bool HasRequiresClause = readBool();
8640 Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
Saar Raz0330fba2019-10-15 18:44:06 +00008641
Richard Smithdbafb6c2017-06-29 23:23:46 +00008642 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
Saar Raz0330fba2019-10-15 18:44:06 +00008643 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
Guy Benyei11169dd2012-12-18 14:30:41 +00008644 return TemplateParams;
8645}
8646
John McCall3ce3d232019-12-13 03:37:23 -05008647void ASTRecordReader::readTemplateArgumentList(
8648 SmallVectorImpl<TemplateArgument> &TemplArgs,
8649 bool Canonicalize) {
8650 unsigned NumTemplateArgs = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008651 TemplArgs.reserve(NumTemplateArgs);
8652 while (NumTemplateArgs--)
John McCall3ce3d232019-12-13 03:37:23 -05008653 TemplArgs.push_back(readTemplateArgument(Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008654}
8655
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008656/// Read a UnresolvedSet structure.
John McCall3ce3d232019-12-13 03:37:23 -05008657void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
8658 unsigned NumDecls = readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008659 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008660 while (NumDecls--) {
John McCall3ce3d232019-12-13 03:37:23 -05008661 DeclID ID = readDeclID();
8662 AccessSpecifier AS = (AccessSpecifier) readInt();
Richard Smithdbafb6c2017-06-29 23:23:46 +00008663 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 }
8665}
8666
8667CXXBaseSpecifier
John McCall3ce3d232019-12-13 03:37:23 -05008668ASTRecordReader::readCXXBaseSpecifier() {
8669 bool isVirtual = readBool();
8670 bool isBaseOfClass = readBool();
8671 AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
8672 bool inheritConstructors = readBool();
8673 TypeSourceInfo *TInfo = readTypeSourceInfo();
8674 SourceRange Range = readSourceRange();
8675 SourceLocation EllipsisLoc = readSourceLocation();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008676 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008677 EllipsisLoc);
8678 Result.setInheritConstructors(inheritConstructors);
8679 return Result;
8680}
8681
Richard Smithc2bb8182015-03-24 06:36:48 +00008682CXXCtorInitializer **
John McCall3ce3d232019-12-13 03:37:23 -05008683ASTRecordReader::readCXXCtorInitializers() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008684 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008685 unsigned NumInitializers = readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008686 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008687 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008688 for (unsigned i = 0; i != NumInitializers; ++i) {
8689 TypeSourceInfo *TInfo = nullptr;
8690 bool IsBaseVirtual = false;
8691 FieldDecl *Member = nullptr;
8692 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008693
John McCall3ce3d232019-12-13 03:37:23 -05008694 CtorInitializerType Type = (CtorInitializerType) readInt();
Richard Smithc2bb8182015-03-24 06:36:48 +00008695 switch (Type) {
8696 case CTOR_INITIALIZER_BASE:
John McCall3ce3d232019-12-13 03:37:23 -05008697 TInfo = readTypeSourceInfo();
8698 IsBaseVirtual = readBool();
Richard Smithc2bb8182015-03-24 06:36:48 +00008699 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008700
Richard Smithc2bb8182015-03-24 06:36:48 +00008701 case CTOR_INITIALIZER_DELEGATING:
John McCall3ce3d232019-12-13 03:37:23 -05008702 TInfo = readTypeSourceInfo();
Richard Smithc2bb8182015-03-24 06:36:48 +00008703 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008704
Richard Smithc2bb8182015-03-24 06:36:48 +00008705 case CTOR_INITIALIZER_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008706 Member = readDeclAs<FieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008707 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008708
Richard Smithc2bb8182015-03-24 06:36:48 +00008709 case CTOR_INITIALIZER_INDIRECT_MEMBER:
John McCall3ce3d232019-12-13 03:37:23 -05008710 IndirectMember = readDeclAs<IndirectFieldDecl>();
Richard Smithc2bb8182015-03-24 06:36:48 +00008711 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008712 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008713
John McCall3ce3d232019-12-13 03:37:23 -05008714 SourceLocation MemberOrEllipsisLoc = readSourceLocation();
8715 Expr *Init = readExpr();
8716 SourceLocation LParenLoc = readSourceLocation();
8717 SourceLocation RParenLoc = readSourceLocation();
Richard Smithc2bb8182015-03-24 06:36:48 +00008718
8719 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008720 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008721 BOMInit = new (Context)
8722 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8723 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008724 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008725 BOMInit = new (Context)
8726 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008727 else if (Member)
8728 BOMInit = new (Context)
8729 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8730 Init, RParenLoc);
8731 else
8732 BOMInit = new (Context)
8733 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8734 LParenLoc, Init, RParenLoc);
8735
John McCall3ce3d232019-12-13 03:37:23 -05008736 if (/*IsWritten*/readBool()) {
8737 unsigned SourceOrder = readInt();
Richard Smith30e304e2016-12-14 00:03:17 +00008738 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008739 }
8740
Richard Smithc2bb8182015-03-24 06:36:48 +00008741 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008742 }
8743
Richard Smithc2bb8182015-03-24 06:36:48 +00008744 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008745}
8746
Guy Benyei11169dd2012-12-18 14:30:41 +00008747NestedNameSpecifierLoc
John McCall3ce3d232019-12-13 03:37:23 -05008748ASTRecordReader::readNestedNameSpecifierLoc() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008749 ASTContext &Context = getContext();
John McCall3ce3d232019-12-13 03:37:23 -05008750 unsigned N = readInt();
Guy Benyei11169dd2012-12-18 14:30:41 +00008751 NestedNameSpecifierLocBuilder Builder;
8752 for (unsigned I = 0; I != N; ++I) {
John McCalld505e572019-12-13 21:54:44 -05008753 auto Kind = readNestedNameSpecifierKind();
Guy Benyei11169dd2012-12-18 14:30:41 +00008754 switch (Kind) {
8755 case NestedNameSpecifier::Identifier: {
John McCall3ce3d232019-12-13 03:37:23 -05008756 IdentifierInfo *II = readIdentifier();
8757 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008758 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8759 break;
8760 }
8761
8762 case NestedNameSpecifier::Namespace: {
John McCall3ce3d232019-12-13 03:37:23 -05008763 NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
8764 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008765 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8766 break;
8767 }
8768
8769 case NestedNameSpecifier::NamespaceAlias: {
John McCall3ce3d232019-12-13 03:37:23 -05008770 NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
8771 SourceRange Range = readSourceRange();
Guy Benyei11169dd2012-12-18 14:30:41 +00008772 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8773 break;
8774 }
8775
8776 case NestedNameSpecifier::TypeSpec:
8777 case NestedNameSpecifier::TypeSpecWithTemplate: {
John McCall3ce3d232019-12-13 03:37:23 -05008778 bool Template = readBool();
8779 TypeSourceInfo *T = readTypeSourceInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00008780 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008781 return NestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -05008782 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008783
8784 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008785 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008786 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8787 T->getTypeLoc(), ColonColonLoc);
8788 break;
8789 }
8790
8791 case NestedNameSpecifier::Global: {
John McCall3ce3d232019-12-13 03:37:23 -05008792 SourceLocation ColonColonLoc = readSourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 Builder.MakeGlobal(Context, ColonColonLoc);
8794 break;
8795 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008796
8797 case NestedNameSpecifier::Super: {
John McCall3ce3d232019-12-13 03:37:23 -05008798 CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
8799 SourceRange Range = readSourceRange();
Nikola Smiljanic67860242014-09-26 00:28:20 +00008800 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8801 break;
8802 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008803 }
8804 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008805
Guy Benyei11169dd2012-12-18 14:30:41 +00008806 return Builder.getWithLocInContext(Context);
8807}
8808
8809SourceRange
8810ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8811 unsigned &Idx) {
8812 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8813 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8814 return SourceRange(beg, end);
8815}
8816
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008817static FixedPointSemantics
8818ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
8819 unsigned &Idx) {
8820 unsigned Width = Record[Idx++];
8821 unsigned Scale = Record[Idx++];
8822 uint64_t Tmp = Record[Idx++];
8823 bool IsSigned = Tmp & 0x1;
8824 bool IsSaturated = Tmp & 0x2;
8825 bool HasUnsignedPadding = Tmp & 0x4;
8826 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
8827 HasUnsignedPadding);
8828}
8829
John McCall3ce3d232019-12-13 03:37:23 -05008830static const llvm::fltSemantics &
8831readAPFloatSemantics(ASTRecordReader &reader) {
8832 return llvm::APFloatBase::EnumToSemantics(
8833 static_cast<llvm::APFloatBase::Semantics>(reader.readInt()));
8834}
8835
8836APValue ASTRecordReader::readAPValue() {
8837 unsigned Kind = readInt();
John McCalld505e572019-12-13 21:54:44 -05008838 switch ((APValue::ValueKind) Kind) {
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008839 case APValue::None:
8840 return APValue();
8841 case APValue::Indeterminate:
8842 return APValue::IndeterminateValue();
8843 case APValue::Int:
John McCall3ce3d232019-12-13 03:37:23 -05008844 return APValue(readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008845 case APValue::Float: {
John McCall3ce3d232019-12-13 03:37:23 -05008846 const llvm::fltSemantics &FloatSema = readAPFloatSemantics(*this);
8847 return APValue(readAPFloat(FloatSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008848 }
8849 case APValue::FixedPoint: {
8850 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
John McCall3ce3d232019-12-13 03:37:23 -05008851 return APValue(APFixedPoint(readAPInt(), FPSema));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008852 }
8853 case APValue::ComplexInt: {
John McCall3ce3d232019-12-13 03:37:23 -05008854 llvm::APSInt First = readAPSInt();
8855 return APValue(std::move(First), readAPSInt());
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008856 }
8857 case APValue::ComplexFloat: {
John McCall3ce3d232019-12-13 03:37:23 -05008858 const llvm::fltSemantics &FloatSema1 = readAPFloatSemantics(*this);
8859 llvm::APFloat First = readAPFloat(FloatSema1);
8860 const llvm::fltSemantics &FloatSema2 = readAPFloatSemantics(*this);
8861 return APValue(std::move(First), readAPFloat(FloatSema2));
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00008862 }
8863 case APValue::LValue:
8864 case APValue::Vector:
8865 case APValue::Array:
8866 case APValue::Struct:
8867 case APValue::Union:
8868 case APValue::MemberPointer:
8869 case APValue::AddrLabelDiff:
8870 // TODO : Handle all these APValue::ValueKind.
8871 return APValue();
8872 }
8873 llvm_unreachable("Invalid APValue::ValueKind");
8874}
8875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008876/// Read a floating-point value
John McCall3ce3d232019-12-13 03:37:23 -05008877llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
8878 return llvm::APFloat(Sem, readAPInt());
Guy Benyei11169dd2012-12-18 14:30:41 +00008879}
8880
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008881// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00008882std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8883 unsigned Len = Record[Idx++];
8884 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8885 Idx += Len;
8886 return Result;
8887}
8888
Richard Smith7ed1bc92014-12-05 22:42:13 +00008889std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8890 unsigned &Idx) {
8891 std::string Filename = ReadString(Record, Idx);
8892 ResolveImportedPath(F, Filename);
8893 return Filename;
8894}
8895
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00008896std::string ASTReader::ReadPath(StringRef BaseDirectory,
8897 const RecordData &Record, unsigned &Idx) {
8898 std::string Filename = ReadString(Record, Idx);
8899 if (!BaseDirectory.empty())
8900 ResolveImportedPath(Filename, BaseDirectory);
8901 return Filename;
8902}
8903
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008904VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008905 unsigned &Idx) {
8906 unsigned Major = Record[Idx++];
8907 unsigned Minor = Record[Idx++];
8908 unsigned Subminor = Record[Idx++];
8909 if (Minor == 0)
8910 return VersionTuple(Major);
8911 if (Subminor == 0)
8912 return VersionTuple(Major, Minor - 1);
8913 return VersionTuple(Major, Minor - 1, Subminor - 1);
8914}
8915
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008916CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008917 const RecordData &Record,
8918 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008919 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008920 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008921}
8922
Richard Smith37a93df2017-02-18 00:32:02 +00008923DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008924 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008925}
8926
Richard Smith37a93df2017-02-18 00:32:02 +00008927DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008928 return Diags.Report(Loc, DiagID);
8929}
8930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008931/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00008932/// preprocessor.
8933IdentifierTable &ASTReader::getIdentifierTable() {
8934 return PP.getIdentifierTable();
8935}
8936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008937/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00008938/// statement.
8939void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008940 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008941 "Already have a SwitchCase with this ID");
8942 (*CurrSwitchCaseStmts)[ID] = SC;
8943}
8944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008945/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00008946SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008947 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008948 return (*CurrSwitchCaseStmts)[ID];
8949}
8950
8951void ASTReader::ClearSwitchCaseIDs() {
8952 CurrSwitchCaseStmts->clear();
8953}
8954
8955void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008956 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008957 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008958 for (SmallVectorImpl<std::pair<BitstreamCursor,
8959 serialization::ModuleFile *>>::iterator
8960 I = CommentsCursors.begin(),
8961 E = CommentsCursors.end();
8962 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008963 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008964 BitstreamCursor &Cursor = I->first;
8965 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00008966 SavedStreamPosition SavedPosition(Cursor);
8967
8968 RecordData Record;
8969 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00008970 Expected<llvm::BitstreamEntry> MaybeEntry =
8971 Cursor.advanceSkippingSubblocks(
8972 BitstreamCursor::AF_DontPopBlockAtEnd);
8973 if (!MaybeEntry) {
8974 Error(MaybeEntry.takeError());
8975 return;
8976 }
8977 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008978
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008979 switch (Entry.Kind) {
8980 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8981 case llvm::BitstreamEntry::Error:
8982 Error("malformed block record in AST file");
8983 return;
8984 case llvm::BitstreamEntry::EndBlock:
8985 goto NextCursor;
8986 case llvm::BitstreamEntry::Record:
8987 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008989 }
8990
8991 // Read a record.
8992 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00008993 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
8994 if (!MaybeComment) {
8995 Error(MaybeComment.takeError());
8996 return;
8997 }
8998 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008999 case COMMENTS_RAW_COMMENT: {
9000 unsigned Idx = 0;
9001 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009002 RawComment::CommentKind Kind =
9003 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009004 bool IsTrailingComment = Record[Idx++];
9005 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009006 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009007 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009008 break;
9009 }
9010 }
9011 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009012 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009013 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9014 FileToOffsetToComment;
9015 for (RawComment *C : Comments) {
9016 SourceLocation CommentLoc = C->getBeginLoc();
9017 if (CommentLoc.isValid()) {
9018 std::pair<FileID, unsigned> Loc =
9019 SourceMgr.getDecomposedLoc(CommentLoc);
9020 if (Loc.first.isValid())
9021 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9022 }
9023 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009024 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009025}
9026
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009027void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9028 bool IncludeSystem, bool Complain,
9029 llvm::function_ref<void(const serialization::InputFile &IF,
9030 bool isSystem)> Visitor) {
9031 unsigned NumUserInputs = MF.NumUserInputFiles;
9032 unsigned NumInputs = MF.InputFilesLoaded.size();
9033 assert(NumUserInputs <= NumInputs);
9034 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9035 for (unsigned I = 0; I < N; ++I) {
9036 bool IsSystem = I >= NumUserInputs;
9037 InputFile IF = getInputFile(MF, I+1, Complain);
9038 Visitor(IF, IsSystem);
9039 }
9040}
9041
Richard Smithf3f84612017-06-29 02:19:42 +00009042void ASTReader::visitTopLevelModuleMaps(
9043 serialization::ModuleFile &MF,
9044 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9045 unsigned NumInputs = MF.InputFilesLoaded.size();
9046 for (unsigned I = 0; I < NumInputs; ++I) {
9047 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9048 if (IFI.TopLevelModuleMap)
9049 // FIXME: This unnecessarily re-reads the InputFileInfo.
9050 if (auto *FE = getInputFile(MF, I + 1).getFile())
9051 Visitor(FE);
9052 }
9053}
9054
Richard Smithcd45dbc2014-04-19 03:48:30 +00009055std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9056 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009057 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009058 return M->getFullModuleName();
9059
9060 // Otherwise, use the name of the top-level module the decl is within.
9061 if (ModuleFile *M = getOwningModuleFile(D))
9062 return M->ModuleName;
9063
9064 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009065 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009066}
9067
Guy Benyei11169dd2012-12-18 14:30:41 +00009068void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009069 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009070 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009071 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009072 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009073 // If any identifiers with corresponding top-level declarations have
9074 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009075 using TopLevelDeclsMap =
9076 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009077 TopLevelDeclsMap TopLevelDecls;
9078
Guy Benyei11169dd2012-12-18 14:30:41 +00009079 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009080 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009081 SmallVector<uint32_t, 4> DeclIDs =
9082 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009083 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009084
9085 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009086 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009087
Richard Smitha62d1982018-08-03 01:00:01 +00009088 // Load each function type that we deferred loading because it was a
9089 // deduced type that might refer to a local type declared within itself.
9090 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9091 auto *FD = PendingFunctionTypes[I].first;
9092 FD->setType(GetType(PendingFunctionTypes[I].second));
9093
9094 // If we gave a function a deduced return type, remember that we need to
9095 // propagate that along the redeclaration chain.
9096 auto *DT = FD->getReturnType()->getContainedDeducedType();
9097 if (DT && DT->isDeduced())
9098 PendingDeducedTypeUpdates.insert(
9099 {FD->getCanonicalDecl(), FD->getReturnType()});
9100 }
9101 PendingFunctionTypes.clear();
9102
Richard Smith851072e2014-05-19 20:59:20 +00009103 // For each decl chain that we wanted to complete while deserializing, mark
9104 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009105 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9106 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9107 }
Richard Smith851072e2014-05-19 20:59:20 +00009108 PendingIncompleteDeclChains.clear();
9109
Guy Benyei11169dd2012-12-18 14:30:41 +00009110 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009111 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009112 loadPendingDeclChain(PendingDeclChains[I].first,
9113 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009114 PendingDeclChains.clear();
9115
Douglas Gregor6168bd22013-02-18 15:53:43 +00009116 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009117 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9118 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9119 IdentifierInfo *II = TLD->first;
9120 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9121 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009122 }
9123 }
9124
Guy Benyei11169dd2012-12-18 14:30:41 +00009125 // Load any pending macro definitions.
9126 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009127 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9128 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9129 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9130 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009131 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009132 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009133 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009134 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009135 resolvePendingMacro(II, Info);
9136 }
9137 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009138 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009139 ++IDIdx) {
9140 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009141 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009142 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009143 }
9144 }
9145 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009146
9147 // Wire up the DeclContexts for Decls that we delayed setting until
9148 // recursive loading is completed.
9149 while (!PendingDeclContextInfos.empty()) {
9150 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9151 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009152 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9153 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009154 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9155 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009156
Richard Smithd1c46742014-04-30 02:24:17 +00009157 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009158 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009159 auto Update = PendingUpdateRecords.pop_back_val();
9160 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009161 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009163 }
Richard Smith8a639892015-01-24 01:07:20 +00009164
9165 // At this point, all update records for loaded decls are in place, so any
9166 // fake class definitions should have become real.
9167 assert(PendingFakeDefinitionData.empty() &&
9168 "faked up a class definition but never saw the real one");
9169
Guy Benyei11169dd2012-12-18 14:30:41 +00009170 // If we deserialized any C++ or Objective-C class definitions, any
9171 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009172 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009173 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009174 for (Decl *D : PendingDefinitions) {
9175 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9176 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009177 // Make sure that the TagType points at the definition.
9178 const_cast<TagType*>(TagT)->decl = TD;
9179 }
Richard Smith8ce51082015-03-11 01:44:51 +00009180
Vedant Kumar48b4f762018-04-14 01:40:48 +00009181 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009182 for (auto *R = getMostRecentExistingDecl(RD); R;
9183 R = R->getPreviousDecl()) {
9184 assert((R == D) ==
9185 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009186 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009187 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009188 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009189 }
9190
9191 continue;
9192 }
Richard Smith8ce51082015-03-11 01:44:51 +00009193
Vedant Kumar48b4f762018-04-14 01:40:48 +00009194 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009195 // Make sure that the ObjCInterfaceType points at the definition.
9196 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9197 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009198
9199 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9200 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9201
Guy Benyei11169dd2012-12-18 14:30:41 +00009202 continue;
9203 }
Richard Smith8ce51082015-03-11 01:44:51 +00009204
Vedant Kumar48b4f762018-04-14 01:40:48 +00009205 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009206 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9207 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9208
Guy Benyei11169dd2012-12-18 14:30:41 +00009209 continue;
9210 }
Richard Smith8ce51082015-03-11 01:44:51 +00009211
Vedant Kumar48b4f762018-04-14 01:40:48 +00009212 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009213 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9214 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009215 }
9216 PendingDefinitions.clear();
9217
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009218 // Load the bodies of any functions or methods we've encountered. We do
9219 // this now (delayed) so that we can be sure that the declaration chains
9220 // have been fully wired up (hasBody relies on this).
9221 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009222 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9223 PBEnd = PendingBodies.end();
9224 PB != PBEnd; ++PB) {
9225 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009226 // For a function defined inline within a class template, force the
9227 // canonical definition to be the one inside the canonical definition of
9228 // the template. This ensures that we instantiate from a correct view
9229 // of the template.
9230 //
9231 // Sadly we can't do this more generally: we can't be sure that all
9232 // copies of an arbitrary class definition will have the same members
9233 // defined (eg, some member functions may not be instantiated, and some
9234 // special members may or may not have been implicitly defined).
9235 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9236 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9237 continue;
9238
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009239 // FIXME: Check for =delete/=default?
9240 // FIXME: Complain about ODR violations here?
9241 const FunctionDecl *Defn = nullptr;
9242 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009243 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009244 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009245 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009246 mergeDefinitionVisibility(NonConstDefn, FD);
9247
9248 if (!FD->isLateTemplateParsed() &&
9249 !NonConstDefn->isLateTemplateParsed() &&
9250 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009251 if (!isa<CXXMethodDecl>(FD)) {
9252 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9253 } else if (FD->getLexicalParent()->isFileContext() &&
9254 NonConstDefn->getLexicalParent()->isFileContext()) {
9255 // Only diagnose out-of-line method definitions. If they are
9256 // in class definitions, then an error will be generated when
9257 // processing the class bodies.
9258 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9259 }
Richard Trieue6caa262017-12-23 00:41:01 +00009260 }
9261 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009262 continue;
9263 }
9264
Vedant Kumar48b4f762018-04-14 01:40:48 +00009265 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009266 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009267 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009268 }
9269 PendingBodies.clear();
9270
Richard Smith42413142015-05-15 20:05:43 +00009271 // Do some cleanup.
9272 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9273 getContext().deduplicateMergedDefinitonsFor(ND);
9274 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009275}
9276
9277void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009278 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009279 PendingFunctionOdrMergeFailures.empty() &&
9280 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009281 return;
9282
Richard Smitha0ce9c42014-07-29 23:23:27 +00009283 // Trigger the import of the full definition of each class that had any
9284 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009285 // These updates may in turn find and diagnose some ODR failures, so take
9286 // ownership of the set first.
9287 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9288 PendingOdrMergeFailures.clear();
9289 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009290 Merge.first->buildLookup();
9291 Merge.first->decls_begin();
9292 Merge.first->bases_begin();
9293 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009294 for (auto &RecordPair : Merge.second) {
9295 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009296 RD->decls_begin();
9297 RD->bases_begin();
9298 RD->vbases_begin();
9299 }
9300 }
9301
Richard Trieue6caa262017-12-23 00:41:01 +00009302 // Trigger the import of functions.
9303 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9304 PendingFunctionOdrMergeFailures.clear();
9305 for (auto &Merge : FunctionOdrMergeFailures) {
9306 Merge.first->buildLookup();
9307 Merge.first->decls_begin();
9308 Merge.first->getBody();
9309 for (auto &FD : Merge.second) {
9310 FD->buildLookup();
9311 FD->decls_begin();
9312 FD->getBody();
9313 }
9314 }
9315
Richard Trieuab4d7302018-07-25 22:52:05 +00009316 // Trigger the import of enums.
9317 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9318 PendingEnumOdrMergeFailures.clear();
9319 for (auto &Merge : EnumOdrMergeFailures) {
9320 Merge.first->decls_begin();
9321 for (auto &Enum : Merge.second) {
9322 Enum->decls_begin();
9323 }
9324 }
9325
Richard Smitha0ce9c42014-07-29 23:23:27 +00009326 // For each declaration from a merged context, check that the canonical
9327 // definition of that context also contains a declaration of the same
9328 // entity.
9329 //
9330 // Caution: this loop does things that might invalidate iterators into
9331 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9332 while (!PendingOdrMergeChecks.empty()) {
9333 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9334
9335 // FIXME: Skip over implicit declarations for now. This matters for things
9336 // like implicitly-declared special member functions. This isn't entirely
9337 // correct; we can end up with multiple unmerged declarations of the same
9338 // implicit entity.
9339 if (D->isImplicit())
9340 continue;
9341
9342 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009343
9344 bool Found = false;
9345 const Decl *DCanon = D->getCanonicalDecl();
9346
Richard Smith01bdb7a2014-08-28 05:44:07 +00009347 for (auto RI : D->redecls()) {
9348 if (RI->getLexicalDeclContext() == CanonDef) {
9349 Found = true;
9350 break;
9351 }
9352 }
9353 if (Found)
9354 continue;
9355
Richard Smith0f4e2c42015-08-06 04:23:48 +00009356 // Quick check failed, time to do the slow thing. Note, we can't just
9357 // look up the name of D in CanonDef here, because the member that is
9358 // in CanonDef might not be found by name lookup (it might have been
9359 // replaced by a more recent declaration in the lookup table), and we
9360 // can't necessarily find it in the redeclaration chain because it might
9361 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009362 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009363 for (auto *CanonMember : CanonDef->decls()) {
9364 if (CanonMember->getCanonicalDecl() == DCanon) {
9365 // This can happen if the declaration is merely mergeable and not
9366 // actually redeclarable (we looked for redeclarations earlier).
9367 //
9368 // FIXME: We should be able to detect this more efficiently, without
9369 // pulling in all of the members of CanonDef.
9370 Found = true;
9371 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009372 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009373 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9374 if (ND->getDeclName() == D->getDeclName())
9375 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009376 }
9377
9378 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009379 // The AST doesn't like TagDecls becoming invalid after they've been
9380 // completed. We only really need to mark FieldDecls as invalid here.
9381 if (!isa<TagDecl>(D))
9382 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009383
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009384 // Ensure we don't accidentally recursively enter deserialization while
9385 // we're producing our diagnostic.
9386 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009387
9388 std::string CanonDefModule =
9389 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9390 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9391 << D << getOwningModuleNameForDiagnostic(D)
9392 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9393
9394 if (Candidates.empty())
9395 Diag(cast<Decl>(CanonDef)->getLocation(),
9396 diag::note_module_odr_violation_no_possible_decls) << D;
9397 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009398 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9399 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009400 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009401 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009402 }
9403
9404 DiagnosedOdrMergeFailures.insert(CanonDef);
9405 }
9406 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009407
Richard Trieuab4d7302018-07-25 22:52:05 +00009408 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9409 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009410 return;
9411
9412 // Ensure we don't accidentally recursively enter deserialization while
9413 // we're producing our diagnostics.
9414 Deserializing RecursionGuard(this);
9415
Richard Trieue6caa262017-12-23 00:41:01 +00009416 // Common code for hashing helpers.
9417 ODRHash Hash;
9418 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9419 Hash.clear();
9420 Hash.AddQualType(Ty);
9421 return Hash.CalculateHash();
9422 };
9423
9424 auto ComputeODRHash = [&Hash](const Stmt *S) {
9425 assert(S);
9426 Hash.clear();
9427 Hash.AddStmt(S);
9428 return Hash.CalculateHash();
9429 };
9430
9431 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9432 assert(D);
9433 Hash.clear();
9434 Hash.AddSubDecl(D);
9435 return Hash.CalculateHash();
9436 };
9437
Richard Trieu7282d322018-04-25 00:31:15 +00009438 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9439 Hash.clear();
9440 Hash.AddTemplateArgument(TA);
9441 return Hash.CalculateHash();
9442 };
9443
Richard Trieu9359e8f2018-05-30 01:12:26 +00009444 auto ComputeTemplateParameterListODRHash =
9445 [&Hash](const TemplateParameterList *TPL) {
9446 assert(TPL);
9447 Hash.clear();
9448 Hash.AddTemplateParameterList(TPL);
9449 return Hash.CalculateHash();
9450 };
9451
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009452 // Used with err_module_odr_violation_mismatch_decl and
9453 // note_module_odr_violation_mismatch_decl
9454 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
9455 enum ODRMismatchDecl {
9456 EndOfClass,
9457 PublicSpecifer,
9458 PrivateSpecifer,
9459 ProtectedSpecifer,
9460 StaticAssert,
9461 Field,
9462 CXXMethod,
9463 TypeAlias,
9464 TypeDef,
9465 Var,
9466 Friend,
9467 FunctionTemplate,
9468 Other
9469 };
9470
9471 // Used with err_module_odr_violation_mismatch_decl_diff and
9472 // note_module_odr_violation_mismatch_decl_diff
9473 enum ODRMismatchDeclDifference {
9474 StaticAssertCondition,
9475 StaticAssertMessage,
9476 StaticAssertOnlyMessage,
9477 FieldName,
9478 FieldTypeName,
9479 FieldSingleBitField,
9480 FieldDifferentWidthBitField,
9481 FieldSingleMutable,
9482 FieldSingleInitializer,
9483 FieldDifferentInitializers,
9484 MethodName,
9485 MethodDeleted,
9486 MethodDefaulted,
9487 MethodVirtual,
9488 MethodStatic,
9489 MethodVolatile,
9490 MethodConst,
9491 MethodInline,
9492 MethodNumberParameters,
9493 MethodParameterType,
9494 MethodParameterName,
9495 MethodParameterSingleDefaultArgument,
9496 MethodParameterDifferentDefaultArgument,
9497 MethodNoTemplateArguments,
9498 MethodDifferentNumberTemplateArguments,
9499 MethodDifferentTemplateArgument,
9500 MethodSingleBody,
9501 MethodDifferentBody,
9502 TypedefName,
9503 TypedefType,
9504 VarName,
9505 VarType,
9506 VarSingleInitializer,
9507 VarDifferentInitializer,
9508 VarConstexpr,
9509 FriendTypeFunction,
9510 FriendType,
9511 FriendFunction,
9512 FunctionTemplateDifferentNumberParameters,
9513 FunctionTemplateParameterDifferentKind,
9514 FunctionTemplateParameterName,
9515 FunctionTemplateParameterSingleDefaultArgument,
9516 FunctionTemplateParameterDifferentDefaultArgument,
9517 FunctionTemplateParameterDifferentType,
9518 FunctionTemplatePackParameter,
9519 };
9520
9521 // These lambdas have the common portions of the ODR diagnostics. This
9522 // has the same return as Diag(), so addition parameters can be passed
9523 // in with operator<<
9524 auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule,
9525 SourceLocation Loc, SourceRange Range,
9526 ODRMismatchDeclDifference DiffType) {
9527 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9528 << FirstRecord << FirstModule.empty() << FirstModule << Range
9529 << DiffType;
9530 };
9531 auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc,
9532 SourceRange Range, ODRMismatchDeclDifference DiffType) {
9533 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9534 << SecondModule << Range << DiffType;
9535 };
9536
9537 auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote,
9538 &ComputeQualTypeODRHash, &ComputeODRHash](
9539 NamedDecl *FirstRecord, StringRef FirstModule,
9540 StringRef SecondModule, FieldDecl *FirstField,
9541 FieldDecl *SecondField) {
9542 IdentifierInfo *FirstII = FirstField->getIdentifier();
9543 IdentifierInfo *SecondII = SecondField->getIdentifier();
9544 if (FirstII->getName() != SecondII->getName()) {
9545 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9546 FirstField->getSourceRange(), FieldName)
9547 << FirstII;
9548 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9549 SecondField->getSourceRange(), FieldName)
9550 << SecondII;
9551
9552 return true;
9553 }
9554
9555 assert(getContext().hasSameType(FirstField->getType(),
9556 SecondField->getType()));
9557
9558 QualType FirstType = FirstField->getType();
9559 QualType SecondType = SecondField->getType();
9560 if (ComputeQualTypeODRHash(FirstType) !=
9561 ComputeQualTypeODRHash(SecondType)) {
9562 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9563 FirstField->getSourceRange(), FieldTypeName)
9564 << FirstII << FirstType;
9565 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9566 SecondField->getSourceRange(), FieldTypeName)
9567 << SecondII << SecondType;
9568
9569 return true;
9570 }
9571
9572 const bool IsFirstBitField = FirstField->isBitField();
9573 const bool IsSecondBitField = SecondField->isBitField();
9574 if (IsFirstBitField != IsSecondBitField) {
9575 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9576 FirstField->getSourceRange(), FieldSingleBitField)
9577 << FirstII << IsFirstBitField;
9578 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9579 SecondField->getSourceRange(), FieldSingleBitField)
9580 << SecondII << IsSecondBitField;
9581 return true;
9582 }
9583
9584 if (IsFirstBitField && IsSecondBitField) {
9585 unsigned FirstBitWidthHash =
9586 ComputeODRHash(FirstField->getBitWidth());
9587 unsigned SecondBitWidthHash =
9588 ComputeODRHash(SecondField->getBitWidth());
9589 if (FirstBitWidthHash != SecondBitWidthHash) {
9590 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9591 FirstField->getSourceRange(),
9592 FieldDifferentWidthBitField)
9593 << FirstII << FirstField->getBitWidth()->getSourceRange();
9594 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9595 SecondField->getSourceRange(),
9596 FieldDifferentWidthBitField)
9597 << SecondII << SecondField->getBitWidth()->getSourceRange();
9598 return true;
9599 }
9600 }
9601
9602 if (!PP.getLangOpts().CPlusPlus)
9603 return false;
9604
9605 const bool IsFirstMutable = FirstField->isMutable();
9606 const bool IsSecondMutable = SecondField->isMutable();
9607 if (IsFirstMutable != IsSecondMutable) {
9608 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9609 FirstField->getSourceRange(), FieldSingleMutable)
9610 << FirstII << IsFirstMutable;
9611 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9612 SecondField->getSourceRange(), FieldSingleMutable)
9613 << SecondII << IsSecondMutable;
9614 return true;
9615 }
9616
9617 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9618 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9619 if ((!FirstInitializer && SecondInitializer) ||
9620 (FirstInitializer && !SecondInitializer)) {
9621 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9622 FirstField->getSourceRange(), FieldSingleInitializer)
9623 << FirstII << (FirstInitializer != nullptr);
9624 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9625 SecondField->getSourceRange(), FieldSingleInitializer)
9626 << SecondII << (SecondInitializer != nullptr);
9627 return true;
9628 }
9629
9630 if (FirstInitializer && SecondInitializer) {
9631 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9632 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9633 if (FirstInitHash != SecondInitHash) {
9634 ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
9635 FirstField->getSourceRange(),
9636 FieldDifferentInitializers)
9637 << FirstII << FirstInitializer->getSourceRange();
9638 ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
9639 SecondField->getSourceRange(),
9640 FieldDifferentInitializers)
9641 << SecondII << SecondInitializer->getSourceRange();
9642 return true;
9643 }
9644 }
9645
9646 return false;
9647 };
9648
9649 auto ODRDiagTypeDefOrAlias =
9650 [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash](
9651 NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule,
9652 TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD,
9653 bool IsTypeAlias) {
9654 auto FirstName = FirstTD->getDeclName();
9655 auto SecondName = SecondTD->getDeclName();
9656 if (FirstName != SecondName) {
9657 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9658 FirstTD->getSourceRange(), TypedefName)
9659 << IsTypeAlias << FirstName;
9660 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9661 SecondTD->getSourceRange(), TypedefName)
9662 << IsTypeAlias << SecondName;
9663 return true;
9664 }
9665
9666 QualType FirstType = FirstTD->getUnderlyingType();
9667 QualType SecondType = SecondTD->getUnderlyingType();
9668 if (ComputeQualTypeODRHash(FirstType) !=
9669 ComputeQualTypeODRHash(SecondType)) {
9670 ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
9671 FirstTD->getSourceRange(), TypedefType)
9672 << IsTypeAlias << FirstName << FirstType;
9673 ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
9674 SecondTD->getSourceRange(), TypedefType)
9675 << IsTypeAlias << SecondName << SecondType;
9676 return true;
9677 }
9678
9679 return false;
9680 };
9681
9682 auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote,
9683 &ComputeQualTypeODRHash, &ComputeODRHash,
9684 this](NamedDecl *FirstRecord, StringRef FirstModule,
9685 StringRef SecondModule, VarDecl *FirstVD,
9686 VarDecl *SecondVD) {
9687 auto FirstName = FirstVD->getDeclName();
9688 auto SecondName = SecondVD->getDeclName();
9689 if (FirstName != SecondName) {
9690 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9691 FirstVD->getSourceRange(), VarName)
9692 << FirstName;
9693 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9694 SecondVD->getSourceRange(), VarName)
9695 << SecondName;
9696 return true;
9697 }
9698
9699 QualType FirstType = FirstVD->getType();
9700 QualType SecondType = SecondVD->getType();
9701 if (ComputeQualTypeODRHash(FirstType) !=
9702 ComputeQualTypeODRHash(SecondType)) {
9703 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9704 FirstVD->getSourceRange(), VarType)
9705 << FirstName << FirstType;
9706 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9707 SecondVD->getSourceRange(), VarType)
9708 << SecondName << SecondType;
9709 return true;
9710 }
9711
9712 if (!PP.getLangOpts().CPlusPlus)
9713 return false;
9714
9715 const Expr *FirstInit = FirstVD->getInit();
9716 const Expr *SecondInit = SecondVD->getInit();
9717 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
9718 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9719 FirstVD->getSourceRange(), VarSingleInitializer)
9720 << FirstName << (FirstInit == nullptr)
9721 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
9722 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9723 SecondVD->getSourceRange(), VarSingleInitializer)
9724 << SecondName << (SecondInit == nullptr)
9725 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
9726 return true;
9727 }
9728
9729 if (FirstInit && SecondInit &&
9730 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
9731 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9732 FirstVD->getSourceRange(), VarDifferentInitializer)
9733 << FirstName << FirstInit->getSourceRange();
9734 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9735 SecondVD->getSourceRange(), VarDifferentInitializer)
9736 << SecondName << SecondInit->getSourceRange();
9737 return true;
9738 }
9739
9740 const bool FirstIsConstexpr = FirstVD->isConstexpr();
9741 const bool SecondIsConstexpr = SecondVD->isConstexpr();
9742 if (FirstIsConstexpr != SecondIsConstexpr) {
9743 ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
9744 FirstVD->getSourceRange(), VarConstexpr)
9745 << FirstName << FirstIsConstexpr;
9746 ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
9747 SecondVD->getSourceRange(), VarConstexpr)
9748 << SecondName << SecondIsConstexpr;
9749 return true;
9750 }
9751 return false;
9752 };
9753
9754 auto DifferenceSelector = [](Decl *D) {
9755 assert(D && "valid Decl required");
9756 switch (D->getKind()) {
9757 default:
9758 return Other;
9759 case Decl::AccessSpec:
9760 switch (D->getAccess()) {
9761 case AS_public:
9762 return PublicSpecifer;
9763 case AS_private:
9764 return PrivateSpecifer;
9765 case AS_protected:
9766 return ProtectedSpecifer;
9767 case AS_none:
9768 break;
9769 }
9770 llvm_unreachable("Invalid access specifier");
9771 case Decl::StaticAssert:
9772 return StaticAssert;
9773 case Decl::Field:
9774 return Field;
9775 case Decl::CXXMethod:
9776 case Decl::CXXConstructor:
9777 case Decl::CXXDestructor:
9778 return CXXMethod;
9779 case Decl::TypeAlias:
9780 return TypeAlias;
9781 case Decl::Typedef:
9782 return TypeDef;
9783 case Decl::Var:
9784 return Var;
9785 case Decl::Friend:
9786 return Friend;
9787 case Decl::FunctionTemplate:
9788 return FunctionTemplate;
9789 }
9790 };
9791
9792 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9793 auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9794 RecordDecl *Record,
9795 const DeclContext *DC) {
9796 for (auto *D : Record->decls()) {
9797 if (!ODRHash::isWhitelistedDecl(D, DC))
9798 continue;
9799 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
9800 }
9801 };
9802
9803 struct DiffResult {
9804 Decl *FirstDecl = nullptr, *SecondDecl = nullptr;
9805 ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other;
9806 };
9807
9808 // If there is a diagnoseable difference, FirstDiffType and
9809 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9810 // filled in if not EndOfClass.
9811 auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes,
9812 DeclHashes &SecondHashes) {
9813 DiffResult DR;
9814 auto FirstIt = FirstHashes.begin();
9815 auto SecondIt = SecondHashes.begin();
9816 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
9817 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9818 FirstIt->second == SecondIt->second) {
9819 ++FirstIt;
9820 ++SecondIt;
9821 continue;
9822 }
9823
9824 DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9825 DR.SecondDecl =
9826 SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9827
9828 DR.FirstDiffType =
9829 DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass;
9830 DR.SecondDiffType =
9831 DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass;
9832 return DR;
9833 }
9834 return DR;
9835 };
9836
9837 // Use this to diagnose that an unexpected Decl was encountered
9838 // or no difference was detected. This causes a generic error
9839 // message to be emitted.
9840 auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord,
9841 StringRef FirstModule,
9842 NamedDecl *SecondRecord,
9843 StringRef SecondModule) {
9844 Diag(FirstRecord->getLocation(),
9845 diag::err_module_odr_violation_different_definitions)
9846 << FirstRecord << FirstModule.empty() << FirstModule;
9847
9848 if (DR.FirstDecl) {
9849 Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference)
9850 << FirstRecord << DR.FirstDecl->getSourceRange();
9851 }
9852
9853 Diag(SecondRecord->getLocation(),
9854 diag::note_module_odr_violation_different_definitions)
9855 << SecondModule;
9856
9857 if (DR.SecondDecl) {
9858 Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference)
9859 << DR.SecondDecl->getSourceRange();
9860 }
9861 };
9862
9863 auto DiagnoseODRMismatch =
9864 [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule,
9865 NamedDecl *SecondRecord, StringRef SecondModule) {
9866 SourceLocation FirstLoc;
9867 SourceRange FirstRange;
9868 auto *FirstTag = dyn_cast<TagDecl>(FirstRecord);
9869 if (DR.FirstDiffType == EndOfClass && FirstTag) {
9870 FirstLoc = FirstTag->getBraceRange().getEnd();
9871 } else {
9872 FirstLoc = DR.FirstDecl->getLocation();
9873 FirstRange = DR.FirstDecl->getSourceRange();
9874 }
9875 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9876 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9877 << DR.FirstDiffType;
9878
9879 SourceLocation SecondLoc;
9880 SourceRange SecondRange;
9881 auto *SecondTag = dyn_cast<TagDecl>(SecondRecord);
9882 if (DR.SecondDiffType == EndOfClass && SecondTag) {
9883 SecondLoc = SecondTag->getBraceRange().getEnd();
9884 } else {
9885 SecondLoc = DR.SecondDecl->getLocation();
9886 SecondRange = DR.SecondDecl->getSourceRange();
9887 }
9888 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9889 << SecondModule << SecondRange << DR.SecondDiffType;
9890 };
9891
Richard Smithcd45dbc2014-04-19 03:48:30 +00009892 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009893 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009894 // If we've already pointed out a specific problem with this class, don't
9895 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009896 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009897 continue;
9898
9899 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009900 CXXRecordDecl *FirstRecord = Merge.first;
9901 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009902 for (auto &RecordPair : Merge.second) {
9903 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009904 // Multiple different declarations got merged together; tell the user
9905 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009906 if (FirstRecord == SecondRecord)
9907 continue;
9908
9909 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009910
9911 auto *FirstDD = FirstRecord->DefinitionData;
9912 auto *SecondDD = RecordPair.second;
9913
9914 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9915
9916 // Diagnostics from DefinitionData are emitted here.
9917 if (FirstDD != SecondDD) {
9918 enum ODRDefinitionDataDifference {
9919 NumBases,
9920 NumVBases,
9921 BaseType,
9922 BaseVirtual,
9923 BaseAccess,
9924 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009925 auto ODRDiagBaseError = [FirstRecord, &FirstModule,
9926 this](SourceLocation Loc, SourceRange Range,
9927 ODRDefinitionDataDifference DiffType) {
Richard Trieue13eabe2017-09-30 02:19:17 +00009928 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9929 << FirstRecord << FirstModule.empty() << FirstModule << Range
9930 << DiffType;
9931 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009932 auto ODRDiagBaseNote = [&SecondModule,
9933 this](SourceLocation Loc, SourceRange Range,
9934 ODRDefinitionDataDifference DiffType) {
Richard Trieue13eabe2017-09-30 02:19:17 +00009935 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9936 << SecondModule << Range << DiffType;
9937 };
9938
Richard Trieue13eabe2017-09-30 02:19:17 +00009939 unsigned FirstNumBases = FirstDD->NumBases;
9940 unsigned FirstNumVBases = FirstDD->NumVBases;
9941 unsigned SecondNumBases = SecondDD->NumBases;
9942 unsigned SecondNumVBases = SecondDD->NumVBases;
9943
9944 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9945 unsigned NumBases = DD->NumBases;
9946 if (NumBases == 0) return SourceRange();
9947 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009948 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009949 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +00009950 };
9951
9952 if (FirstNumBases != SecondNumBases) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009953 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9954 NumBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009955 << FirstNumBases;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009956 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9957 NumBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009958 << SecondNumBases;
9959 Diagnosed = true;
9960 break;
9961 }
9962
9963 if (FirstNumVBases != SecondNumVBases) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009964 ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9965 NumVBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009966 << FirstNumVBases;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009967 ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9968 NumVBases)
Richard Trieue13eabe2017-09-30 02:19:17 +00009969 << SecondNumVBases;
9970 Diagnosed = true;
9971 break;
9972 }
9973
9974 auto FirstBases = FirstDD->bases();
9975 auto SecondBases = SecondDD->bases();
9976 unsigned i = 0;
9977 for (i = 0; i < FirstNumBases; ++i) {
9978 auto FirstBase = FirstBases[i];
9979 auto SecondBase = SecondBases[i];
9980 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9981 ComputeQualTypeODRHash(SecondBase.getType())) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009982 ODRDiagBaseError(FirstRecord->getLocation(),
9983 FirstBase.getSourceRange(), BaseType)
Richard Trieue13eabe2017-09-30 02:19:17 +00009984 << (i + 1) << FirstBase.getType();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009985 ODRDiagBaseNote(SecondRecord->getLocation(),
9986 SecondBase.getSourceRange(), BaseType)
Richard Trieue13eabe2017-09-30 02:19:17 +00009987 << (i + 1) << SecondBase.getType();
9988 break;
9989 }
9990
9991 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009992 ODRDiagBaseError(FirstRecord->getLocation(),
9993 FirstBase.getSourceRange(), BaseVirtual)
Richard Trieue13eabe2017-09-30 02:19:17 +00009994 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -08009995 ODRDiagBaseNote(SecondRecord->getLocation(),
9996 SecondBase.getSourceRange(), BaseVirtual)
Richard Trieue13eabe2017-09-30 02:19:17 +00009997 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9998 break;
9999 }
10000
10001 if (FirstBase.getAccessSpecifierAsWritten() !=
10002 SecondBase.getAccessSpecifierAsWritten()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010003 ODRDiagBaseError(FirstRecord->getLocation(),
10004 FirstBase.getSourceRange(), BaseAccess)
Richard Trieue13eabe2017-09-30 02:19:17 +000010005 << (i + 1) << FirstBase.getType()
10006 << (int)FirstBase.getAccessSpecifierAsWritten();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010007 ODRDiagBaseNote(SecondRecord->getLocation(),
10008 SecondBase.getSourceRange(), BaseAccess)
Richard Trieue13eabe2017-09-30 02:19:17 +000010009 << (i + 1) << SecondBase.getType()
10010 << (int)SecondBase.getAccessSpecifierAsWritten();
10011 break;
10012 }
10013 }
10014
10015 if (i != FirstNumBases) {
10016 Diagnosed = true;
10017 break;
10018 }
10019 }
10020
Richard Trieu498117b2017-08-23 02:43:59 +000010021 const ClassTemplateDecl *FirstTemplate =
10022 FirstRecord->getDescribedClassTemplate();
10023 const ClassTemplateDecl *SecondTemplate =
10024 SecondRecord->getDescribedClassTemplate();
10025
10026 assert(!FirstTemplate == !SecondTemplate &&
10027 "Both pointers should be null or non-null");
10028
10029 enum ODRTemplateDifference {
10030 ParamEmptyName,
10031 ParamName,
10032 ParamSingleDefaultArgument,
10033 ParamDifferentDefaultArgument,
10034 };
10035
10036 if (FirstTemplate && SecondTemplate) {
10037 DeclHashes FirstTemplateHashes;
10038 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010039
10040 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010041 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10042 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010043 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010044 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010045 }
10046 };
10047
10048 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10049 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10050
10051 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10052 "Number of template parameters should be equal.");
10053
10054 auto FirstIt = FirstTemplateHashes.begin();
10055 auto FirstEnd = FirstTemplateHashes.end();
10056 auto SecondIt = SecondTemplateHashes.begin();
10057 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10058 if (FirstIt->second == SecondIt->second)
10059 continue;
10060
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010061 auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this](
10062 SourceLocation Loc, SourceRange Range,
10063 ODRTemplateDifference DiffType) {
Richard Trieu498117b2017-08-23 02:43:59 +000010064 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10065 << FirstRecord << FirstModule.empty() << FirstModule << Range
10066 << DiffType;
10067 };
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010068 auto ODRDiagTemplateNote = [&SecondModule, this](
10069 SourceLocation Loc, SourceRange Range,
10070 ODRTemplateDifference DiffType) {
Richard Trieu498117b2017-08-23 02:43:59 +000010071 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10072 << SecondModule << Range << DiffType;
10073 };
10074
Vedant Kumar48b4f762018-04-14 01:40:48 +000010075 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10076 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010077
10078 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10079 "Parameter Decl's should be the same kind.");
10080
10081 DeclarationName FirstName = FirstDecl->getDeclName();
10082 DeclarationName SecondName = SecondDecl->getDeclName();
10083
10084 if (FirstName != SecondName) {
10085 const bool FirstNameEmpty =
10086 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10087 const bool SecondNameEmpty =
10088 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10089 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10090 "Both template parameters cannot be unnamed.");
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010091 ODRDiagTemplateError(FirstDecl->getLocation(),
10092 FirstDecl->getSourceRange(),
10093 FirstNameEmpty ? ParamEmptyName : ParamName)
Richard Trieu498117b2017-08-23 02:43:59 +000010094 << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010095 ODRDiagTemplateNote(SecondDecl->getLocation(),
10096 SecondDecl->getSourceRange(),
10097 SecondNameEmpty ? ParamEmptyName : ParamName)
Richard Trieu498117b2017-08-23 02:43:59 +000010098 << SecondName;
10099 break;
10100 }
10101
10102 switch (FirstDecl->getKind()) {
10103 default:
10104 llvm_unreachable("Invalid template parameter type.");
10105 case Decl::TemplateTypeParm: {
10106 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10107 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10108 const bool HasFirstDefaultArgument =
10109 FirstParam->hasDefaultArgument() &&
10110 !FirstParam->defaultArgumentWasInherited();
10111 const bool HasSecondDefaultArgument =
10112 SecondParam->hasDefaultArgument() &&
10113 !SecondParam->defaultArgumentWasInherited();
10114
10115 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010116 ODRDiagTemplateError(FirstDecl->getLocation(),
10117 FirstDecl->getSourceRange(),
10118 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010119 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010120 ODRDiagTemplateNote(SecondDecl->getLocation(),
10121 SecondDecl->getSourceRange(),
10122 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010123 << HasSecondDefaultArgument;
10124 break;
10125 }
10126
10127 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10128 "Expecting default arguments.");
10129
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010130 ODRDiagTemplateError(FirstDecl->getLocation(),
10131 FirstDecl->getSourceRange(),
10132 ParamDifferentDefaultArgument);
10133 ODRDiagTemplateNote(SecondDecl->getLocation(),
10134 SecondDecl->getSourceRange(),
10135 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010136
10137 break;
10138 }
10139 case Decl::NonTypeTemplateParm: {
10140 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10141 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10142 const bool HasFirstDefaultArgument =
10143 FirstParam->hasDefaultArgument() &&
10144 !FirstParam->defaultArgumentWasInherited();
10145 const bool HasSecondDefaultArgument =
10146 SecondParam->hasDefaultArgument() &&
10147 !SecondParam->defaultArgumentWasInherited();
10148
10149 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010150 ODRDiagTemplateError(FirstDecl->getLocation(),
10151 FirstDecl->getSourceRange(),
10152 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010153 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010154 ODRDiagTemplateNote(SecondDecl->getLocation(),
10155 SecondDecl->getSourceRange(),
10156 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010157 << HasSecondDefaultArgument;
10158 break;
10159 }
10160
10161 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10162 "Expecting default arguments.");
10163
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010164 ODRDiagTemplateError(FirstDecl->getLocation(),
10165 FirstDecl->getSourceRange(),
10166 ParamDifferentDefaultArgument);
10167 ODRDiagTemplateNote(SecondDecl->getLocation(),
10168 SecondDecl->getSourceRange(),
10169 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010170
10171 break;
10172 }
10173 case Decl::TemplateTemplateParm: {
10174 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10175 const auto *SecondParam =
10176 cast<TemplateTemplateParmDecl>(SecondDecl);
10177 const bool HasFirstDefaultArgument =
10178 FirstParam->hasDefaultArgument() &&
10179 !FirstParam->defaultArgumentWasInherited();
10180 const bool HasSecondDefaultArgument =
10181 SecondParam->hasDefaultArgument() &&
10182 !SecondParam->defaultArgumentWasInherited();
10183
10184 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010185 ODRDiagTemplateError(FirstDecl->getLocation(),
10186 FirstDecl->getSourceRange(),
10187 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010188 << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010189 ODRDiagTemplateNote(SecondDecl->getLocation(),
10190 SecondDecl->getSourceRange(),
10191 ParamSingleDefaultArgument)
Richard Trieu498117b2017-08-23 02:43:59 +000010192 << HasSecondDefaultArgument;
10193 break;
10194 }
10195
10196 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10197 "Expecting default arguments.");
10198
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010199 ODRDiagTemplateError(FirstDecl->getLocation(),
10200 FirstDecl->getSourceRange(),
10201 ParamDifferentDefaultArgument);
10202 ODRDiagTemplateNote(SecondDecl->getLocation(),
10203 SecondDecl->getSourceRange(),
10204 ParamDifferentDefaultArgument);
Richard Trieu498117b2017-08-23 02:43:59 +000010205
10206 break;
10207 }
10208 }
10209
10210 break;
10211 }
10212
10213 if (FirstIt != FirstEnd) {
10214 Diagnosed = true;
10215 break;
10216 }
10217 }
10218
Richard Trieue7f7ed22017-02-22 01:11:25 +000010219 DeclHashes FirstHashes;
10220 DeclHashes SecondHashes;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010221 const DeclContext *DC = FirstRecord;
10222 PopulateHashes(FirstHashes, FirstRecord, DC);
10223 PopulateHashes(SecondHashes, SecondRecord, DC);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010224
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010225 auto DR = FindTypeDiffs(FirstHashes, SecondHashes);
10226 ODRMismatchDecl FirstDiffType = DR.FirstDiffType;
10227 ODRMismatchDecl SecondDiffType = DR.SecondDiffType;
10228 Decl *FirstDecl = DR.FirstDecl;
10229 Decl *SecondDecl = DR.SecondDecl;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010230
10231 if (FirstDiffType == Other || SecondDiffType == Other) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010232 DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord,
10233 SecondModule);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010234 Diagnosed = true;
10235 break;
10236 }
10237
10238 if (FirstDiffType != SecondDiffType) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010239 DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord,
10240 SecondModule);
Richard Trieue7f7ed22017-02-22 01:11:25 +000010241 Diagnosed = true;
10242 break;
10243 }
10244
Richard Trieu639d7b62017-02-22 22:22:42 +000010245 assert(FirstDiffType == SecondDiffType);
10246
Richard Trieu639d7b62017-02-22 22:22:42 +000010247 switch (FirstDiffType) {
10248 case Other:
10249 case EndOfClass:
10250 case PublicSpecifer:
10251 case PrivateSpecifer:
10252 case ProtectedSpecifer:
10253 llvm_unreachable("Invalid diff type");
10254
10255 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010256 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10257 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010258
10259 Expr *FirstExpr = FirstSA->getAssertExpr();
10260 Expr *SecondExpr = SecondSA->getAssertExpr();
10261 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10262 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10263 if (FirstODRHash != SecondODRHash) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010264 ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(),
10265 FirstExpr->getSourceRange(), StaticAssertCondition);
10266 ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(),
10267 SecondExpr->getSourceRange(), StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010268 Diagnosed = true;
10269 break;
10270 }
10271
10272 StringLiteral *FirstStr = FirstSA->getMessage();
10273 StringLiteral *SecondStr = SecondSA->getMessage();
10274 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10275 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10276 SourceLocation FirstLoc, SecondLoc;
10277 SourceRange FirstRange, SecondRange;
10278 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010279 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010280 FirstRange = FirstStr->getSourceRange();
10281 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010282 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010283 FirstRange = FirstSA->getSourceRange();
10284 }
10285 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010286 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010287 SecondRange = SecondStr->getSourceRange();
10288 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010289 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010290 SecondRange = SecondSA->getSourceRange();
10291 }
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010292 ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange,
10293 StaticAssertOnlyMessage)
Richard Trieu639d7b62017-02-22 22:22:42 +000010294 << (FirstStr == nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010295 ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange,
10296 StaticAssertOnlyMessage)
Richard Trieu639d7b62017-02-22 22:22:42 +000010297 << (SecondStr == nullptr);
10298 Diagnosed = true;
10299 break;
10300 }
10301
10302 if (FirstStr && SecondStr &&
10303 FirstStr->getString() != SecondStr->getString()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010304 ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(),
10305 FirstStr->getSourceRange(), StaticAssertMessage);
10306 ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(),
10307 SecondStr->getSourceRange(), StaticAssertMessage);
Richard Trieu639d7b62017-02-22 22:22:42 +000010308 Diagnosed = true;
10309 break;
10310 }
10311 break;
10312 }
Richard Trieud0786092017-02-23 00:23:01 +000010313 case Field: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010314 Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule,
10315 cast<FieldDecl>(FirstDecl),
10316 cast<FieldDecl>(SecondDecl));
Richard Trieud0786092017-02-23 00:23:01 +000010317 break;
10318 }
Richard Trieu48143742017-02-28 21:24:38 +000010319 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010320 enum {
10321 DiagMethod,
10322 DiagConstructor,
10323 DiagDestructor,
10324 } FirstMethodType,
10325 SecondMethodType;
10326 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10327 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10328 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10329 return DiagMethod;
10330 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010331 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10332 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010333 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10334 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010335 auto FirstName = FirstMethod->getDeclName();
10336 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010337 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010338 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10339 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010340 << FirstMethodType << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010341 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10342 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010343 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010344
10345 Diagnosed = true;
10346 break;
10347 }
10348
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010349 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10350 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010351 if (FirstDeleted != SecondDeleted) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010352 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10353 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010354 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010355
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010356 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10357 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010358 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010359 Diagnosed = true;
10360 break;
10361 }
10362
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010363 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10364 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10365 if (FirstDefaulted != SecondDefaulted) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010366 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10367 FirstMethod->getSourceRange(), MethodDefaulted)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010368 << FirstMethodType << FirstName << FirstDefaulted;
10369
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010370 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10371 SecondMethod->getSourceRange(), MethodDefaulted)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010372 << SecondMethodType << SecondName << SecondDefaulted;
10373 Diagnosed = true;
10374 break;
10375 }
10376
Richard Trieu583e2c12017-03-04 00:08:58 +000010377 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10378 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10379 const bool FirstPure = FirstMethod->isPure();
10380 const bool SecondPure = SecondMethod->isPure();
10381 if ((FirstVirtual || SecondVirtual) &&
10382 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010383 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10384 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010385 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010386 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10387 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010388 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010389 Diagnosed = true;
10390 break;
10391 }
10392
10393 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10394 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10395 // class needs to be checked instead.
10396 const auto FirstStorage = FirstMethod->getStorageClass();
10397 const auto SecondStorage = SecondMethod->getStorageClass();
10398 const bool FirstStatic = FirstStorage == SC_Static;
10399 const bool SecondStatic = SecondStorage == SC_Static;
10400 if (FirstStatic != SecondStatic) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010401 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10402 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010403 << FirstMethodType << FirstName << FirstStatic;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010404 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10405 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010406 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010407 Diagnosed = true;
10408 break;
10409 }
10410
10411 const bool FirstVolatile = FirstMethod->isVolatile();
10412 const bool SecondVolatile = SecondMethod->isVolatile();
10413 if (FirstVolatile != SecondVolatile) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010414 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10415 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010416 << FirstMethodType << FirstName << FirstVolatile;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010417 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10418 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010419 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010420 Diagnosed = true;
10421 break;
10422 }
10423
10424 const bool FirstConst = FirstMethod->isConst();
10425 const bool SecondConst = SecondMethod->isConst();
10426 if (FirstConst != SecondConst) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010427 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10428 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010429 << FirstMethodType << FirstName << FirstConst;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010430 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10431 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010432 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010433 Diagnosed = true;
10434 break;
10435 }
10436
10437 const bool FirstInline = FirstMethod->isInlineSpecified();
10438 const bool SecondInline = SecondMethod->isInlineSpecified();
10439 if (FirstInline != SecondInline) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010440 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10441 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010442 << FirstMethodType << FirstName << FirstInline;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010443 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10444 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010445 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010446 Diagnosed = true;
10447 break;
10448 }
10449
Richard Trieu02552272017-05-02 23:58:52 +000010450 const unsigned FirstNumParameters = FirstMethod->param_size();
10451 const unsigned SecondNumParameters = SecondMethod->param_size();
10452 if (FirstNumParameters != SecondNumParameters) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010453 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10454 FirstMethod->getSourceRange(),
10455 MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010456 << FirstMethodType << FirstName << FirstNumParameters;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010457 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10458 SecondMethod->getSourceRange(),
10459 MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010460 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010461 Diagnosed = true;
10462 break;
10463 }
10464
10465 // Need this status boolean to know when break out of the switch.
10466 bool ParameterMismatch = false;
10467 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10468 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10469 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10470
10471 QualType FirstParamType = FirstParam->getType();
10472 QualType SecondParamType = SecondParam->getType();
10473 if (FirstParamType != SecondParamType &&
10474 ComputeQualTypeODRHash(FirstParamType) !=
10475 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010476 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010477 FirstParamType->getAs<DecayedType>()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010478 ODRDiagDeclError(
10479 FirstRecord, FirstModule, FirstMethod->getLocation(),
10480 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010481 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10482 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010483 } else {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010484 ODRDiagDeclError(
10485 FirstRecord, FirstModule, FirstMethod->getLocation(),
10486 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010487 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10488 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010489 }
10490
Vedant Kumar48b4f762018-04-14 01:40:48 +000010491 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010492 SecondParamType->getAs<DecayedType>()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010493 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10494 SecondMethod->getSourceRange(),
10495 MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010496 << SecondMethodType << SecondName << (I + 1)
10497 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010498 << ParamDecayedType->getOriginalType();
10499 } else {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010500 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10501 SecondMethod->getSourceRange(),
10502 MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010503 << SecondMethodType << SecondName << (I + 1)
10504 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010505 }
10506 ParameterMismatch = true;
10507 break;
10508 }
10509
10510 DeclarationName FirstParamName = FirstParam->getDeclName();
10511 DeclarationName SecondParamName = SecondParam->getDeclName();
10512 if (FirstParamName != SecondParamName) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010513 ODRDiagDeclError(FirstRecord, FirstModule,
10514 FirstMethod->getLocation(),
10515 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010516 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010517 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10518 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010519 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010520 ParameterMismatch = true;
10521 break;
10522 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010523
10524 const Expr *FirstInit = FirstParam->getInit();
10525 const Expr *SecondInit = SecondParam->getInit();
10526 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010527 ODRDiagDeclError(FirstRecord, FirstModule,
10528 FirstMethod->getLocation(),
10529 FirstMethod->getSourceRange(),
10530 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010531 << FirstMethodType << FirstName << (I + 1)
10532 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010533 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010534 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10535 SecondMethod->getSourceRange(),
10536 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010537 << SecondMethodType << SecondName << (I + 1)
10538 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010539 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10540 ParameterMismatch = true;
10541 break;
10542 }
10543
10544 if (FirstInit && SecondInit &&
10545 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010546 ODRDiagDeclError(FirstRecord, FirstModule,
10547 FirstMethod->getLocation(),
10548 FirstMethod->getSourceRange(),
10549 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010550 << FirstMethodType << FirstName << (I + 1)
10551 << FirstInit->getSourceRange();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010552 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10553 SecondMethod->getSourceRange(),
10554 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010555 << SecondMethodType << SecondName << (I + 1)
10556 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010557 ParameterMismatch = true;
10558 break;
10559
10560 }
Richard Trieu02552272017-05-02 23:58:52 +000010561 }
10562
10563 if (ParameterMismatch) {
10564 Diagnosed = true;
10565 break;
10566 }
10567
Richard Trieu7282d322018-04-25 00:31:15 +000010568 const auto *FirstTemplateArgs =
10569 FirstMethod->getTemplateSpecializationArgs();
10570 const auto *SecondTemplateArgs =
10571 SecondMethod->getTemplateSpecializationArgs();
10572
10573 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10574 (!FirstTemplateArgs && SecondTemplateArgs)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010575 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10576 FirstMethod->getSourceRange(),
10577 MethodNoTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010578 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010579 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10580 SecondMethod->getSourceRange(),
10581 MethodNoTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010582 << SecondMethodType << SecondName
10583 << (SecondTemplateArgs != nullptr);
10584
10585 Diagnosed = true;
10586 break;
10587 }
10588
10589 if (FirstTemplateArgs && SecondTemplateArgs) {
10590 // Remove pack expansions from argument list.
10591 auto ExpandTemplateArgumentList =
10592 [](const TemplateArgumentList *TAL) {
10593 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10594 for (const TemplateArgument &TA : TAL->asArray()) {
10595 if (TA.getKind() != TemplateArgument::Pack) {
10596 ExpandedList.push_back(&TA);
10597 continue;
10598 }
10599 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10600 ExpandedList.push_back(&PackTA);
10601 }
10602 }
10603 return ExpandedList;
10604 };
10605 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10606 ExpandTemplateArgumentList(FirstTemplateArgs);
10607 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10608 ExpandTemplateArgumentList(SecondTemplateArgs);
10609
10610 if (FirstExpandedList.size() != SecondExpandedList.size()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010611 ODRDiagDeclError(FirstRecord, FirstModule,
10612 FirstMethod->getLocation(),
10613 FirstMethod->getSourceRange(),
10614 MethodDifferentNumberTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010615 << FirstMethodType << FirstName
10616 << (unsigned)FirstExpandedList.size();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010617 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10618 SecondMethod->getSourceRange(),
10619 MethodDifferentNumberTemplateArguments)
Richard Trieu7282d322018-04-25 00:31:15 +000010620 << SecondMethodType << SecondName
10621 << (unsigned)SecondExpandedList.size();
10622
10623 Diagnosed = true;
10624 break;
10625 }
10626
10627 bool TemplateArgumentMismatch = false;
10628 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10629 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10630 &SecondTA = *SecondExpandedList[i];
10631 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10632 ComputeTemplateArgumentODRHash(SecondTA)) {
10633 continue;
10634 }
10635
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010636 ODRDiagDeclError(
10637 FirstRecord, FirstModule, FirstMethod->getLocation(),
10638 FirstMethod->getSourceRange(), MethodDifferentTemplateArgument)
Richard Trieu7282d322018-04-25 00:31:15 +000010639 << FirstMethodType << FirstName << FirstTA << i + 1;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010640 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10641 SecondMethod->getSourceRange(),
10642 MethodDifferentTemplateArgument)
Richard Trieu7282d322018-04-25 00:31:15 +000010643 << SecondMethodType << SecondName << SecondTA << i + 1;
10644
10645 TemplateArgumentMismatch = true;
10646 break;
10647 }
10648
10649 if (TemplateArgumentMismatch) {
10650 Diagnosed = true;
10651 break;
10652 }
10653 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010654
10655 // Compute the hash of the method as if it has no body.
10656 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10657 Hash.clear();
10658 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10659 return Hash.CalculateHash();
10660 };
10661
10662 // Compare the hash generated to the hash stored. A difference means
10663 // that a body was present in the original source. Due to merging,
10664 // the stardard way of detecting a body will not work.
10665 const bool HasFirstBody =
10666 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10667 const bool HasSecondBody =
10668 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10669
10670 if (HasFirstBody != HasSecondBody) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010671 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10672 FirstMethod->getSourceRange(), MethodSingleBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010673 << FirstMethodType << FirstName << HasFirstBody;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010674 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10675 SecondMethod->getSourceRange(), MethodSingleBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010676 << SecondMethodType << SecondName << HasSecondBody;
10677 Diagnosed = true;
10678 break;
10679 }
10680
10681 if (HasFirstBody && HasSecondBody) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010682 ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
10683 FirstMethod->getSourceRange(), MethodDifferentBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010684 << FirstMethodType << FirstName;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010685 ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
10686 SecondMethod->getSourceRange(), MethodDifferentBody)
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010687 << SecondMethodType << SecondName;
10688 Diagnosed = true;
10689 break;
10690 }
10691
Richard Trieu48143742017-02-28 21:24:38 +000010692 break;
10693 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010694 case TypeAlias:
10695 case TypeDef: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010696 Diagnosed = ODRDiagTypeDefOrAlias(
10697 FirstRecord, FirstModule, SecondModule,
10698 cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl),
10699 FirstDiffType == TypeAlias);
Richard Trieu11d566a2017-06-12 21:58:22 +000010700 break;
10701 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010702 case Var: {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010703 Diagnosed =
10704 ODRDiagVar(FirstRecord, FirstModule, SecondModule,
10705 cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl));
Richard Trieu6e13ff32017-06-16 02:44:29 +000010706 break;
10707 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010708 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010709 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10710 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010711
10712 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10713 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10714
10715 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10716 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10717
10718 if (FirstND && SecondND) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010719 ODRDiagDeclError(FirstRecord, FirstModule,
10720 FirstFriend->getFriendLoc(),
10721 FirstFriend->getSourceRange(), FriendFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010722 << FirstND;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010723 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10724 SecondFriend->getSourceRange(), FriendFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010725 << SecondND;
10726
10727 Diagnosed = true;
10728 break;
10729 }
10730
10731 if (FirstTSI && SecondTSI) {
10732 QualType FirstFriendType = FirstTSI->getType();
10733 QualType SecondFriendType = SecondTSI->getType();
10734 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10735 ComputeQualTypeODRHash(SecondFriendType));
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010736 ODRDiagDeclError(FirstRecord, FirstModule,
10737 FirstFriend->getFriendLoc(),
10738 FirstFriend->getSourceRange(), FriendType)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010739 << FirstFriendType;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010740 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10741 SecondFriend->getSourceRange(), FriendType)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010742 << SecondFriendType;
10743 Diagnosed = true;
10744 break;
10745 }
10746
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010747 ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(),
10748 FirstFriend->getSourceRange(), FriendTypeFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010749 << (FirstTSI == nullptr);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010750 ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
10751 SecondFriend->getSourceRange(), FriendTypeFunction)
Richard Trieuac6a1b62017-07-08 02:04:42 +000010752 << (SecondTSI == nullptr);
10753
10754 Diagnosed = true;
10755 break;
10756 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010757 case FunctionTemplate: {
10758 FunctionTemplateDecl *FirstTemplate =
10759 cast<FunctionTemplateDecl>(FirstDecl);
10760 FunctionTemplateDecl *SecondTemplate =
10761 cast<FunctionTemplateDecl>(SecondDecl);
10762
10763 TemplateParameterList *FirstTPL =
10764 FirstTemplate->getTemplateParameters();
10765 TemplateParameterList *SecondTPL =
10766 SecondTemplate->getTemplateParameters();
10767
10768 if (FirstTPL->size() != SecondTPL->size()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010769 ODRDiagDeclError(FirstRecord, FirstModule,
10770 FirstTemplate->getLocation(),
10771 FirstTemplate->getSourceRange(),
10772 FunctionTemplateDifferentNumberParameters)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010773 << FirstTemplate << FirstTPL->size();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010774 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10775 SecondTemplate->getSourceRange(),
10776 FunctionTemplateDifferentNumberParameters)
10777 << SecondTemplate << SecondTPL->size();
Richard Trieu9359e8f2018-05-30 01:12:26 +000010778
10779 Diagnosed = true;
10780 break;
10781 }
10782
10783 bool ParameterMismatch = false;
10784 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10785 NamedDecl *FirstParam = FirstTPL->getParam(i);
10786 NamedDecl *SecondParam = SecondTPL->getParam(i);
10787
10788 if (FirstParam->getKind() != SecondParam->getKind()) {
10789 enum {
10790 TemplateTypeParameter,
10791 NonTypeTemplateParameter,
10792 TemplateTemplateParameter,
10793 };
10794 auto GetParamType = [](NamedDecl *D) {
10795 switch (D->getKind()) {
10796 default:
10797 llvm_unreachable("Unexpected template parameter type");
10798 case Decl::TemplateTypeParm:
10799 return TemplateTypeParameter;
10800 case Decl::NonTypeTemplateParm:
10801 return NonTypeTemplateParameter;
10802 case Decl::TemplateTemplateParm:
10803 return TemplateTemplateParameter;
10804 }
10805 };
10806
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010807 ODRDiagDeclError(FirstRecord, FirstModule,
10808 FirstTemplate->getLocation(),
10809 FirstTemplate->getSourceRange(),
10810 FunctionTemplateParameterDifferentKind)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010811 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010812 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10813 SecondTemplate->getSourceRange(),
10814 FunctionTemplateParameterDifferentKind)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010815 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10816
10817 ParameterMismatch = true;
10818 break;
10819 }
10820
10821 if (FirstParam->getName() != SecondParam->getName()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010822 ODRDiagDeclError(
10823 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10824 FirstTemplate->getSourceRange(), FunctionTemplateParameterName)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010825 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10826 << FirstParam;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010827 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10828 SecondTemplate->getSourceRange(),
10829 FunctionTemplateParameterName)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010830 << SecondTemplate << (i + 1)
10831 << (bool)SecondParam->getIdentifier() << SecondParam;
10832 ParameterMismatch = true;
10833 break;
10834 }
10835
10836 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10837 isa<TemplateTypeParmDecl>(SecondParam)) {
10838 TemplateTypeParmDecl *FirstTTPD =
10839 cast<TemplateTypeParmDecl>(FirstParam);
10840 TemplateTypeParmDecl *SecondTTPD =
10841 cast<TemplateTypeParmDecl>(SecondParam);
10842 bool HasFirstDefaultArgument =
10843 FirstTTPD->hasDefaultArgument() &&
10844 !FirstTTPD->defaultArgumentWasInherited();
10845 bool HasSecondDefaultArgument =
10846 SecondTTPD->hasDefaultArgument() &&
10847 !SecondTTPD->defaultArgumentWasInherited();
10848 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010849 ODRDiagDeclError(FirstRecord, FirstModule,
10850 FirstTemplate->getLocation(),
10851 FirstTemplate->getSourceRange(),
10852 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010853 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010854 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10855 SecondTemplate->getSourceRange(),
10856 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010857 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10858 ParameterMismatch = true;
10859 break;
10860 }
10861
10862 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10863 QualType FirstType = FirstTTPD->getDefaultArgument();
10864 QualType SecondType = SecondTTPD->getDefaultArgument();
10865 if (ComputeQualTypeODRHash(FirstType) !=
10866 ComputeQualTypeODRHash(SecondType)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010867 ODRDiagDeclError(
10868 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10869 FirstTemplate->getSourceRange(),
10870 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010871 << FirstTemplate << (i + 1) << FirstType;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010872 ODRDiagDeclNote(
10873 SecondModule, SecondTemplate->getLocation(),
10874 SecondTemplate->getSourceRange(),
10875 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010876 << SecondTemplate << (i + 1) << SecondType;
10877 ParameterMismatch = true;
10878 break;
10879 }
10880 }
10881
10882 if (FirstTTPD->isParameterPack() !=
10883 SecondTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010884 ODRDiagDeclError(FirstRecord, FirstModule,
10885 FirstTemplate->getLocation(),
10886 FirstTemplate->getSourceRange(),
10887 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010888 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010889 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10890 SecondTemplate->getSourceRange(),
10891 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010892 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10893 ParameterMismatch = true;
10894 break;
10895 }
10896 }
10897
10898 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10899 isa<TemplateTemplateParmDecl>(SecondParam)) {
10900 TemplateTemplateParmDecl *FirstTTPD =
10901 cast<TemplateTemplateParmDecl>(FirstParam);
10902 TemplateTemplateParmDecl *SecondTTPD =
10903 cast<TemplateTemplateParmDecl>(SecondParam);
10904
10905 TemplateParameterList *FirstTPL =
10906 FirstTTPD->getTemplateParameters();
10907 TemplateParameterList *SecondTPL =
10908 SecondTTPD->getTemplateParameters();
10909
10910 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10911 ComputeTemplateParameterListODRHash(SecondTPL)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010912 ODRDiagDeclError(FirstRecord, FirstModule,
10913 FirstTemplate->getLocation(),
10914 FirstTemplate->getSourceRange(),
10915 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010916 << FirstTemplate << (i + 1);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010917 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10918 SecondTemplate->getSourceRange(),
10919 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010920 << SecondTemplate << (i + 1);
10921 ParameterMismatch = true;
10922 break;
10923 }
10924
10925 bool HasFirstDefaultArgument =
10926 FirstTTPD->hasDefaultArgument() &&
10927 !FirstTTPD->defaultArgumentWasInherited();
10928 bool HasSecondDefaultArgument =
10929 SecondTTPD->hasDefaultArgument() &&
10930 !SecondTTPD->defaultArgumentWasInherited();
10931 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010932 ODRDiagDeclError(FirstRecord, FirstModule,
10933 FirstTemplate->getLocation(),
10934 FirstTemplate->getSourceRange(),
10935 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010936 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010937 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10938 SecondTemplate->getSourceRange(),
10939 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010940 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10941 ParameterMismatch = true;
10942 break;
10943 }
10944
10945 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10946 TemplateArgument FirstTA =
10947 FirstTTPD->getDefaultArgument().getArgument();
10948 TemplateArgument SecondTA =
10949 SecondTTPD->getDefaultArgument().getArgument();
10950 if (ComputeTemplateArgumentODRHash(FirstTA) !=
10951 ComputeTemplateArgumentODRHash(SecondTA)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010952 ODRDiagDeclError(
10953 FirstRecord, FirstModule, FirstTemplate->getLocation(),
10954 FirstTemplate->getSourceRange(),
10955 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010956 << FirstTemplate << (i + 1) << FirstTA;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010957 ODRDiagDeclNote(
10958 SecondModule, SecondTemplate->getLocation(),
10959 SecondTemplate->getSourceRange(),
10960 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010961 << SecondTemplate << (i + 1) << SecondTA;
10962 ParameterMismatch = true;
10963 break;
10964 }
10965 }
10966
10967 if (FirstTTPD->isParameterPack() !=
10968 SecondTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010969 ODRDiagDeclError(FirstRecord, FirstModule,
10970 FirstTemplate->getLocation(),
10971 FirstTemplate->getSourceRange(),
10972 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010973 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010974 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
10975 SecondTemplate->getSourceRange(),
10976 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010977 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10978 ParameterMismatch = true;
10979 break;
10980 }
10981 }
10982
10983 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10984 isa<NonTypeTemplateParmDecl>(SecondParam)) {
10985 NonTypeTemplateParmDecl *FirstNTTPD =
10986 cast<NonTypeTemplateParmDecl>(FirstParam);
10987 NonTypeTemplateParmDecl *SecondNTTPD =
10988 cast<NonTypeTemplateParmDecl>(SecondParam);
10989
10990 QualType FirstType = FirstNTTPD->getType();
10991 QualType SecondType = SecondNTTPD->getType();
10992 if (ComputeQualTypeODRHash(FirstType) !=
10993 ComputeQualTypeODRHash(SecondType)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010994 ODRDiagDeclError(FirstRecord, FirstModule,
10995 FirstTemplate->getLocation(),
10996 FirstTemplate->getSourceRange(),
10997 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000010998 << FirstTemplate << (i + 1);
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080010999 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11000 SecondTemplate->getSourceRange(),
11001 FunctionTemplateParameterDifferentType)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011002 << SecondTemplate << (i + 1);
11003 ParameterMismatch = true;
11004 break;
11005 }
11006
11007 bool HasFirstDefaultArgument =
11008 FirstNTTPD->hasDefaultArgument() &&
11009 !FirstNTTPD->defaultArgumentWasInherited();
11010 bool HasSecondDefaultArgument =
11011 SecondNTTPD->hasDefaultArgument() &&
11012 !SecondNTTPD->defaultArgumentWasInherited();
11013 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011014 ODRDiagDeclError(FirstRecord, FirstModule,
11015 FirstTemplate->getLocation(),
11016 FirstTemplate->getSourceRange(),
11017 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011018 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011019 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11020 SecondTemplate->getSourceRange(),
11021 FunctionTemplateParameterSingleDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011022 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11023 ParameterMismatch = true;
11024 break;
11025 }
11026
11027 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11028 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11029 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11030 if (ComputeODRHash(FirstDefaultArgument) !=
11031 ComputeODRHash(SecondDefaultArgument)) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011032 ODRDiagDeclError(
11033 FirstRecord, FirstModule, FirstTemplate->getLocation(),
11034 FirstTemplate->getSourceRange(),
11035 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011036 << FirstTemplate << (i + 1) << FirstDefaultArgument;
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011037 ODRDiagDeclNote(
11038 SecondModule, SecondTemplate->getLocation(),
11039 SecondTemplate->getSourceRange(),
11040 FunctionTemplateParameterDifferentDefaultArgument)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011041 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11042 ParameterMismatch = true;
11043 break;
11044 }
11045 }
11046
11047 if (FirstNTTPD->isParameterPack() !=
11048 SecondNTTPD->isParameterPack()) {
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011049 ODRDiagDeclError(FirstRecord, FirstModule,
11050 FirstTemplate->getLocation(),
11051 FirstTemplate->getSourceRange(),
11052 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011053 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
Bruno Cardoso Lopes90f58ea2020-01-22 12:43:19 -080011054 ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
11055 SecondTemplate->getSourceRange(),
11056 FunctionTemplatePackParameter)
Richard Trieu9359e8f2018-05-30 01:12:26 +000011057 << SecondTemplate << (i + 1)
11058 << SecondNTTPD->isParameterPack();
11059 ParameterMismatch = true;
11060 break;
11061 }
11062 }
11063 }
11064
11065 if (ParameterMismatch) {
11066 Diagnosed = true;
11067 break;
11068 }
11069
11070 break;
11071 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011072 }
11073
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011074 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011075 continue;
11076
Richard Trieu708859a2017-06-08 00:56:21 +000011077 Diag(FirstDecl->getLocation(),
11078 diag::err_module_odr_violation_mismatch_decl_unknown)
11079 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11080 << FirstDecl->getSourceRange();
11081 Diag(SecondDecl->getLocation(),
11082 diag::note_module_odr_violation_mismatch_decl_unknown)
11083 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011084 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011085 }
11086
11087 if (!Diagnosed) {
11088 // All definitions are updates to the same declaration. This happens if a
11089 // module instantiates the declaration of a class template specialization
11090 // and two or more other modules instantiate its definition.
11091 //
11092 // FIXME: Indicate which modules had instantiations of this definition.
11093 // FIXME: How can this even happen?
11094 Diag(Merge.first->getLocation(),
11095 diag::err_module_odr_violation_different_instantiations)
11096 << Merge.first;
11097 }
11098 }
Richard Trieue6caa262017-12-23 00:41:01 +000011099
11100 // Issue ODR failures diagnostics for functions.
11101 for (auto &Merge : FunctionOdrMergeFailures) {
11102 enum ODRFunctionDifference {
11103 ReturnType,
11104 ParameterName,
11105 ParameterType,
11106 ParameterSingleDefaultArgument,
11107 ParameterDifferentDefaultArgument,
11108 FunctionBody,
11109 };
11110
11111 FunctionDecl *FirstFunction = Merge.first;
11112 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11113
11114 bool Diagnosed = false;
11115 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011116
Richard Trieue6caa262017-12-23 00:41:01 +000011117 if (FirstFunction == SecondFunction)
11118 continue;
11119
11120 std::string SecondModule =
11121 getOwningModuleNameForDiagnostic(SecondFunction);
11122
11123 auto ODRDiagError = [FirstFunction, &FirstModule,
11124 this](SourceLocation Loc, SourceRange Range,
11125 ODRFunctionDifference DiffType) {
11126 return Diag(Loc, diag::err_module_odr_violation_function)
11127 << FirstFunction << FirstModule.empty() << FirstModule << Range
11128 << DiffType;
11129 };
11130 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11131 SourceRange Range,
11132 ODRFunctionDifference DiffType) {
11133 return Diag(Loc, diag::note_module_odr_violation_function)
11134 << SecondModule << Range << DiffType;
11135 };
11136
11137 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11138 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11139 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11140 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11141 << FirstFunction->getReturnType();
11142 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11143 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11144 << SecondFunction->getReturnType();
11145 Diagnosed = true;
11146 break;
11147 }
11148
11149 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11150 "Merged functions with different number of parameters");
11151
11152 auto ParamSize = FirstFunction->param_size();
11153 bool ParameterMismatch = false;
11154 for (unsigned I = 0; I < ParamSize; ++I) {
11155 auto *FirstParam = FirstFunction->getParamDecl(I);
11156 auto *SecondParam = SecondFunction->getParamDecl(I);
11157
11158 assert(getContext().hasSameType(FirstParam->getType(),
11159 SecondParam->getType()) &&
11160 "Merged function has different parameter types.");
11161
11162 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11163 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11164 ParameterName)
11165 << I + 1 << FirstParam->getDeclName();
11166 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11167 ParameterName)
11168 << I + 1 << SecondParam->getDeclName();
11169 ParameterMismatch = true;
11170 break;
11171 };
11172
11173 QualType FirstParamType = FirstParam->getType();
11174 QualType SecondParamType = SecondParam->getType();
11175 if (FirstParamType != SecondParamType &&
11176 ComputeQualTypeODRHash(FirstParamType) !=
11177 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011178 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011179 FirstParamType->getAs<DecayedType>()) {
11180 ODRDiagError(FirstParam->getLocation(),
11181 FirstParam->getSourceRange(), ParameterType)
11182 << (I + 1) << FirstParamType << true
11183 << ParamDecayedType->getOriginalType();
11184 } else {
11185 ODRDiagError(FirstParam->getLocation(),
11186 FirstParam->getSourceRange(), ParameterType)
11187 << (I + 1) << FirstParamType << false;
11188 }
11189
Vedant Kumar48b4f762018-04-14 01:40:48 +000011190 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011191 SecondParamType->getAs<DecayedType>()) {
11192 ODRDiagNote(SecondParam->getLocation(),
11193 SecondParam->getSourceRange(), ParameterType)
11194 << (I + 1) << SecondParamType << true
11195 << ParamDecayedType->getOriginalType();
11196 } else {
11197 ODRDiagNote(SecondParam->getLocation(),
11198 SecondParam->getSourceRange(), ParameterType)
11199 << (I + 1) << SecondParamType << false;
11200 }
11201 ParameterMismatch = true;
11202 break;
11203 }
11204
11205 const Expr *FirstInit = FirstParam->getInit();
11206 const Expr *SecondInit = SecondParam->getInit();
11207 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11208 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11209 ParameterSingleDefaultArgument)
11210 << (I + 1) << (FirstInit == nullptr)
11211 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11212 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11213 ParameterSingleDefaultArgument)
11214 << (I + 1) << (SecondInit == nullptr)
11215 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11216 ParameterMismatch = true;
11217 break;
11218 }
11219
11220 if (FirstInit && SecondInit &&
11221 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11222 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11223 ParameterDifferentDefaultArgument)
11224 << (I + 1) << FirstInit->getSourceRange();
11225 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11226 ParameterDifferentDefaultArgument)
11227 << (I + 1) << SecondInit->getSourceRange();
11228 ParameterMismatch = true;
11229 break;
11230 }
11231
11232 assert(ComputeSubDeclODRHash(FirstParam) ==
11233 ComputeSubDeclODRHash(SecondParam) &&
11234 "Undiagnosed parameter difference.");
11235 }
11236
11237 if (ParameterMismatch) {
11238 Diagnosed = true;
11239 break;
11240 }
11241
11242 // If no error has been generated before now, assume the problem is in
11243 // the body and generate a message.
11244 ODRDiagError(FirstFunction->getLocation(),
11245 FirstFunction->getSourceRange(), FunctionBody);
11246 ODRDiagNote(SecondFunction->getLocation(),
11247 SecondFunction->getSourceRange(), FunctionBody);
11248 Diagnosed = true;
11249 break;
11250 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011251 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011252 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11253 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011254
11255 // Issue ODR failures diagnostics for enums.
11256 for (auto &Merge : EnumOdrMergeFailures) {
11257 enum ODREnumDifference {
11258 SingleScopedEnum,
11259 EnumTagKeywordMismatch,
11260 SingleSpecifiedType,
11261 DifferentSpecifiedTypes,
11262 DifferentNumberEnumConstants,
11263 EnumConstantName,
11264 EnumConstantSingleInitilizer,
11265 EnumConstantDifferentInitilizer,
11266 };
11267
11268 // If we've already pointed out a specific problem with this enum, don't
11269 // bother issuing a general "something's different" diagnostic.
11270 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11271 continue;
11272
11273 EnumDecl *FirstEnum = Merge.first;
11274 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11275
11276 using DeclHashes =
11277 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11278 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11279 DeclHashes &Hashes, EnumDecl *Enum) {
11280 for (auto *D : Enum->decls()) {
11281 // Due to decl merging, the first EnumDecl is the parent of
11282 // Decls in both records.
11283 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11284 continue;
11285 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11286 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11287 ComputeSubDeclODRHash(D));
11288 }
11289 };
11290 DeclHashes FirstHashes;
11291 PopulateHashes(FirstHashes, FirstEnum);
11292 bool Diagnosed = false;
11293 for (auto &SecondEnum : Merge.second) {
11294
11295 if (FirstEnum == SecondEnum)
11296 continue;
11297
11298 std::string SecondModule =
11299 getOwningModuleNameForDiagnostic(SecondEnum);
11300
11301 auto ODRDiagError = [FirstEnum, &FirstModule,
11302 this](SourceLocation Loc, SourceRange Range,
11303 ODREnumDifference DiffType) {
11304 return Diag(Loc, diag::err_module_odr_violation_enum)
11305 << FirstEnum << FirstModule.empty() << FirstModule << Range
11306 << DiffType;
11307 };
11308 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11309 SourceRange Range,
11310 ODREnumDifference DiffType) {
11311 return Diag(Loc, diag::note_module_odr_violation_enum)
11312 << SecondModule << Range << DiffType;
11313 };
11314
11315 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11316 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11317 SingleScopedEnum)
11318 << FirstEnum->isScoped();
11319 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11320 SingleScopedEnum)
11321 << SecondEnum->isScoped();
11322 Diagnosed = true;
11323 continue;
11324 }
11325
11326 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11327 if (FirstEnum->isScopedUsingClassTag() !=
11328 SecondEnum->isScopedUsingClassTag()) {
11329 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11330 EnumTagKeywordMismatch)
11331 << FirstEnum->isScopedUsingClassTag();
11332 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11333 EnumTagKeywordMismatch)
11334 << SecondEnum->isScopedUsingClassTag();
11335 Diagnosed = true;
11336 continue;
11337 }
11338 }
11339
11340 QualType FirstUnderlyingType =
11341 FirstEnum->getIntegerTypeSourceInfo()
11342 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11343 : QualType();
11344 QualType SecondUnderlyingType =
11345 SecondEnum->getIntegerTypeSourceInfo()
11346 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11347 : QualType();
11348 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11349 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11350 SingleSpecifiedType)
11351 << !FirstUnderlyingType.isNull();
11352 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11353 SingleSpecifiedType)
11354 << !SecondUnderlyingType.isNull();
11355 Diagnosed = true;
11356 continue;
11357 }
11358
11359 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11360 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11361 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11362 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11363 DifferentSpecifiedTypes)
11364 << FirstUnderlyingType;
11365 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11366 DifferentSpecifiedTypes)
11367 << SecondUnderlyingType;
11368 Diagnosed = true;
11369 continue;
11370 }
11371 }
11372
11373 DeclHashes SecondHashes;
11374 PopulateHashes(SecondHashes, SecondEnum);
11375
11376 if (FirstHashes.size() != SecondHashes.size()) {
11377 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11378 DifferentNumberEnumConstants)
11379 << (int)FirstHashes.size();
11380 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11381 DifferentNumberEnumConstants)
11382 << (int)SecondHashes.size();
11383 Diagnosed = true;
11384 continue;
11385 }
11386
11387 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11388 if (FirstHashes[I].second == SecondHashes[I].second)
11389 continue;
11390 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11391 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11392
11393 if (FirstEnumConstant->getDeclName() !=
11394 SecondEnumConstant->getDeclName()) {
11395
11396 ODRDiagError(FirstEnumConstant->getLocation(),
11397 FirstEnumConstant->getSourceRange(), EnumConstantName)
11398 << I + 1 << FirstEnumConstant;
11399 ODRDiagNote(SecondEnumConstant->getLocation(),
11400 SecondEnumConstant->getSourceRange(), EnumConstantName)
11401 << I + 1 << SecondEnumConstant;
11402 Diagnosed = true;
11403 break;
11404 }
11405
11406 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11407 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11408 if (!FirstInit && !SecondInit)
11409 continue;
11410
11411 if (!FirstInit || !SecondInit) {
11412 ODRDiagError(FirstEnumConstant->getLocation(),
11413 FirstEnumConstant->getSourceRange(),
11414 EnumConstantSingleInitilizer)
11415 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11416 ODRDiagNote(SecondEnumConstant->getLocation(),
11417 SecondEnumConstant->getSourceRange(),
11418 EnumConstantSingleInitilizer)
11419 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11420 Diagnosed = true;
11421 break;
11422 }
11423
11424 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11425 ODRDiagError(FirstEnumConstant->getLocation(),
11426 FirstEnumConstant->getSourceRange(),
11427 EnumConstantDifferentInitilizer)
11428 << I + 1 << FirstEnumConstant;
11429 ODRDiagNote(SecondEnumConstant->getLocation(),
11430 SecondEnumConstant->getSourceRange(),
11431 EnumConstantDifferentInitilizer)
11432 << I + 1 << SecondEnumConstant;
11433 Diagnosed = true;
11434 break;
11435 }
11436 }
11437 }
11438
11439 (void)Diagnosed;
11440 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11441 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011442}
11443
Richard Smithce18a182015-07-14 00:26:00 +000011444void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011445 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011446 ReadTimer->startTimer();
11447}
11448
Guy Benyei11169dd2012-12-18 14:30:41 +000011449void ASTReader::FinishedDeserializing() {
11450 assert(NumCurrentElementsDeserializing &&
11451 "FinishedDeserializing not paired with StartedDeserializing");
11452 if (NumCurrentElementsDeserializing == 1) {
11453 // We decrease NumCurrentElementsDeserializing only after pending actions
11454 // are finished, to avoid recursively re-calling finishPendingActions().
11455 finishPendingActions();
11456 }
11457 --NumCurrentElementsDeserializing;
11458
Richard Smitha0ce9c42014-07-29 23:23:27 +000011459 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011460 // Propagate exception specification and deduced type updates along
11461 // redeclaration chains.
11462 //
11463 // We do this now rather than in finishPendingActions because we want to
11464 // be able to walk the complete redeclaration chains of the updated decls.
11465 while (!PendingExceptionSpecUpdates.empty() ||
11466 !PendingDeducedTypeUpdates.empty()) {
11467 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011468 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011469 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011470 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011471 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011472 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011473 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011474 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011475 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011476 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011477 }
Richard Smitha62d1982018-08-03 01:00:01 +000011478
11479 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11480 PendingDeducedTypeUpdates.clear();
11481 for (auto Update : DTUpdates) {
11482 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11483 // FIXME: If the return type is already deduced, check that it matches.
11484 getContext().adjustDeducedFunctionResultType(Update.first,
11485 Update.second);
11486 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011487 }
11488
Richard Smithce18a182015-07-14 00:26:00 +000011489 if (ReadTimer)
11490 ReadTimer->stopTimer();
11491
Richard Smith0f4e2c42015-08-06 04:23:48 +000011492 diagnoseOdrViolations();
11493
Richard Smith04d05b52014-03-23 00:27:18 +000011494 // We are not in recursive loading, so it's safe to pass the "interesting"
11495 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011496 if (Consumer)
11497 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011498 }
11499}
11500
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011501void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011502 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11503 // Remove any fake results before adding any real ones.
11504 auto It = PendingFakeLookupResults.find(II);
11505 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011506 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011507 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011508 // FIXME: this works around module+PCH performance issue.
11509 // Rather than erase the result from the map, which is O(n), just clear
11510 // the vector of NamedDecls.
11511 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011512 }
11513 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011514
11515 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11516 SemaObj->TUScope->AddDecl(D);
11517 } else if (SemaObj->TUScope) {
11518 // Adding the decl to IdResolver may have failed because it was already in
11519 // (even though it was not added in scope). If it is already in, make sure
11520 // it gets in the scope as well.
11521 if (std::find(SemaObj->IdResolver.begin(Name),
11522 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11523 SemaObj->TUScope->AddDecl(D);
11524 }
11525}
11526
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011527ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11528 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011529 const PCHContainerReader &PCHContainerRdr,
11530 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11531 StringRef isysroot, bool DisableValidation,
11532 bool AllowASTWithCompilerErrors,
11533 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011534 bool ValidateASTInputFilesContent, bool UseGlobalIndex,
David Blaikie61137e12017-01-05 18:23:18 +000011535 std::unique_ptr<llvm::Timer> ReadTimer)
11536 : Listener(DisableValidation
11537 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11538 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011539 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011540 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011541 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11542 PCHContainerRdr, PP.getHeaderSearchInfo()),
11543 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011544 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011545 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11546 AllowConfigurationMismatch(AllowConfigurationMismatch),
11547 ValidateSystemInputs(ValidateSystemInputs),
Bruno Cardoso Lopes1731fc82019-10-15 14:23:55 +000011548 ValidateASTInputFilesContent(ValidateASTInputFilesContent),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011549 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011550 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011551
11552 for (const auto &Ext : Extensions) {
11553 auto BlockName = Ext->getExtensionMetadata().BlockName;
11554 auto Known = ModuleFileExtensions.find(BlockName);
11555 if (Known != ModuleFileExtensions.end()) {
11556 Diags.Report(diag::warn_duplicate_module_file_extension)
11557 << BlockName;
11558 continue;
11559 }
11560
11561 ModuleFileExtensions.insert({BlockName, Ext});
11562 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011563}
11564
11565ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011566 if (OwnsDeserializationListener)
11567 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011568}
Richard Smith10379092016-05-06 23:14:07 +000011569
11570IdentifierResolver &ASTReader::getIdResolver() {
11571 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11572}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011573
JF Bastien0e828952019-06-26 19:50:12 +000011574Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11575 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000011576 Idx = 0;
11577 Record.clear();
11578 return Cursor.readRecord(AbbrevID, Record);
11579}
Kelvin Libe286f52018-09-15 13:54:15 +000011580//===----------------------------------------------------------------------===//
11581//// OMPClauseReader implementation
11582////===----------------------------------------------------------------------===//
11583
John McCallc2f18312019-12-14 03:01:28 -050011584// This has to be in namespace clang because it's friended by all
11585// of the OMP clauses.
11586namespace clang {
11587
11588class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
11589 ASTRecordReader &Record;
11590 ASTContext &Context;
11591
11592public:
11593 OMPClauseReader(ASTRecordReader &Record)
11594 : Record(Record), Context(Record.getContext()) {}
11595
11596#define OPENMP_CLAUSE(Name, Class) void Visit##Class(Class *C);
11597#include "clang/Basic/OpenMPKinds.def"
11598 OMPClause *readClause();
11599 void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
11600 void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
11601};
11602
11603} // end namespace clang
11604
11605OMPClause *ASTRecordReader::readOMPClause() {
11606 return OMPClauseReader(*this).readClause();
11607}
11608
Kelvin Libe286f52018-09-15 13:54:15 +000011609OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011610 OMPClause *C = nullptr;
Kelvin Libe286f52018-09-15 13:54:15 +000011611 switch (Record.readInt()) {
11612 case OMPC_if:
11613 C = new (Context) OMPIfClause();
11614 break;
11615 case OMPC_final:
11616 C = new (Context) OMPFinalClause();
11617 break;
11618 case OMPC_num_threads:
11619 C = new (Context) OMPNumThreadsClause();
11620 break;
11621 case OMPC_safelen:
11622 C = new (Context) OMPSafelenClause();
11623 break;
11624 case OMPC_simdlen:
11625 C = new (Context) OMPSimdlenClause();
11626 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011627 case OMPC_allocator:
11628 C = new (Context) OMPAllocatorClause();
11629 break;
Kelvin Libe286f52018-09-15 13:54:15 +000011630 case OMPC_collapse:
11631 C = new (Context) OMPCollapseClause();
11632 break;
11633 case OMPC_default:
11634 C = new (Context) OMPDefaultClause();
11635 break;
11636 case OMPC_proc_bind:
11637 C = new (Context) OMPProcBindClause();
11638 break;
11639 case OMPC_schedule:
11640 C = new (Context) OMPScheduleClause();
11641 break;
11642 case OMPC_ordered:
11643 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11644 break;
11645 case OMPC_nowait:
11646 C = new (Context) OMPNowaitClause();
11647 break;
11648 case OMPC_untied:
11649 C = new (Context) OMPUntiedClause();
11650 break;
11651 case OMPC_mergeable:
11652 C = new (Context) OMPMergeableClause();
11653 break;
11654 case OMPC_read:
11655 C = new (Context) OMPReadClause();
11656 break;
11657 case OMPC_write:
11658 C = new (Context) OMPWriteClause();
11659 break;
11660 case OMPC_update:
11661 C = new (Context) OMPUpdateClause();
11662 break;
11663 case OMPC_capture:
11664 C = new (Context) OMPCaptureClause();
11665 break;
11666 case OMPC_seq_cst:
11667 C = new (Context) OMPSeqCstClause();
11668 break;
11669 case OMPC_threads:
11670 C = new (Context) OMPThreadsClause();
11671 break;
11672 case OMPC_simd:
11673 C = new (Context) OMPSIMDClause();
11674 break;
11675 case OMPC_nogroup:
11676 C = new (Context) OMPNogroupClause();
11677 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011678 case OMPC_unified_address:
11679 C = new (Context) OMPUnifiedAddressClause();
11680 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011681 case OMPC_unified_shared_memory:
11682 C = new (Context) OMPUnifiedSharedMemoryClause();
11683 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011684 case OMPC_reverse_offload:
11685 C = new (Context) OMPReverseOffloadClause();
11686 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011687 case OMPC_dynamic_allocators:
11688 C = new (Context) OMPDynamicAllocatorsClause();
11689 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011690 case OMPC_atomic_default_mem_order:
11691 C = new (Context) OMPAtomicDefaultMemOrderClause();
11692 break;
11693 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000011694 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11695 break;
11696 case OMPC_firstprivate:
11697 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11698 break;
11699 case OMPC_lastprivate:
11700 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11701 break;
11702 case OMPC_shared:
11703 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11704 break;
11705 case OMPC_reduction:
11706 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11707 break;
11708 case OMPC_task_reduction:
11709 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11710 break;
11711 case OMPC_in_reduction:
11712 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11713 break;
11714 case OMPC_linear:
11715 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11716 break;
11717 case OMPC_aligned:
11718 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11719 break;
11720 case OMPC_copyin:
11721 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11722 break;
11723 case OMPC_copyprivate:
11724 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11725 break;
11726 case OMPC_flush:
11727 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11728 break;
11729 case OMPC_depend: {
11730 unsigned NumVars = Record.readInt();
11731 unsigned NumLoops = Record.readInt();
11732 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11733 break;
11734 }
11735 case OMPC_device:
11736 C = new (Context) OMPDeviceClause();
11737 break;
11738 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011739 OMPMappableExprListSizeTy Sizes;
11740 Sizes.NumVars = Record.readInt();
11741 Sizes.NumUniqueDeclarations = Record.readInt();
11742 Sizes.NumComponentLists = Record.readInt();
11743 Sizes.NumComponents = Record.readInt();
11744 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011745 break;
11746 }
11747 case OMPC_num_teams:
11748 C = new (Context) OMPNumTeamsClause();
11749 break;
11750 case OMPC_thread_limit:
11751 C = new (Context) OMPThreadLimitClause();
11752 break;
11753 case OMPC_priority:
11754 C = new (Context) OMPPriorityClause();
11755 break;
11756 case OMPC_grainsize:
11757 C = new (Context) OMPGrainsizeClause();
11758 break;
11759 case OMPC_num_tasks:
11760 C = new (Context) OMPNumTasksClause();
11761 break;
11762 case OMPC_hint:
11763 C = new (Context) OMPHintClause();
11764 break;
11765 case OMPC_dist_schedule:
11766 C = new (Context) OMPDistScheduleClause();
11767 break;
11768 case OMPC_defaultmap:
11769 C = new (Context) OMPDefaultmapClause();
11770 break;
11771 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011772 OMPMappableExprListSizeTy Sizes;
11773 Sizes.NumVars = Record.readInt();
11774 Sizes.NumUniqueDeclarations = Record.readInt();
11775 Sizes.NumComponentLists = Record.readInt();
11776 Sizes.NumComponents = Record.readInt();
11777 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011778 break;
11779 }
11780 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011781 OMPMappableExprListSizeTy Sizes;
11782 Sizes.NumVars = Record.readInt();
11783 Sizes.NumUniqueDeclarations = Record.readInt();
11784 Sizes.NumComponentLists = Record.readInt();
11785 Sizes.NumComponents = Record.readInt();
11786 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011787 break;
11788 }
11789 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011790 OMPMappableExprListSizeTy Sizes;
11791 Sizes.NumVars = Record.readInt();
11792 Sizes.NumUniqueDeclarations = Record.readInt();
11793 Sizes.NumComponentLists = Record.readInt();
11794 Sizes.NumComponents = Record.readInt();
11795 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011796 break;
11797 }
11798 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011799 OMPMappableExprListSizeTy Sizes;
11800 Sizes.NumVars = Record.readInt();
11801 Sizes.NumUniqueDeclarations = Record.readInt();
11802 Sizes.NumComponentLists = Record.readInt();
11803 Sizes.NumComponents = Record.readInt();
11804 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011805 break;
11806 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000011807 case OMPC_allocate:
11808 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11809 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050011810 case OMPC_nontemporal:
11811 C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
11812 break;
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011813 case OMPC_order:
11814 C = new (Context) OMPOrderClause();
11815 break;
Kelvin Libe286f52018-09-15 13:54:15 +000011816 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000011817 assert(C && "Unknown OMPClause type");
11818
Kelvin Libe286f52018-09-15 13:54:15 +000011819 Visit(C);
11820 C->setLocStart(Record.readSourceLocation());
11821 C->setLocEnd(Record.readSourceLocation());
11822
11823 return C;
11824}
11825
11826void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11827 C->setPreInitStmt(Record.readSubStmt(),
11828 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11829}
11830
11831void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11832 VisitOMPClauseWithPreInit(C);
11833 C->setPostUpdateExpr(Record.readSubExpr());
11834}
11835
11836void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11837 VisitOMPClauseWithPreInit(C);
11838 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11839 C->setNameModifierLoc(Record.readSourceLocation());
11840 C->setColonLoc(Record.readSourceLocation());
11841 C->setCondition(Record.readSubExpr());
11842 C->setLParenLoc(Record.readSourceLocation());
11843}
11844
11845void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011846 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000011847 C->setCondition(Record.readSubExpr());
11848 C->setLParenLoc(Record.readSourceLocation());
11849}
11850
11851void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11852 VisitOMPClauseWithPreInit(C);
11853 C->setNumThreads(Record.readSubExpr());
11854 C->setLParenLoc(Record.readSourceLocation());
11855}
11856
11857void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11858 C->setSafelen(Record.readSubExpr());
11859 C->setLParenLoc(Record.readSourceLocation());
11860}
11861
11862void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11863 C->setSimdlen(Record.readSubExpr());
11864 C->setLParenLoc(Record.readSourceLocation());
11865}
11866
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011867void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
11868 C->setAllocator(Record.readExpr());
11869 C->setLParenLoc(Record.readSourceLocation());
11870}
11871
Kelvin Libe286f52018-09-15 13:54:15 +000011872void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11873 C->setNumForLoops(Record.readSubExpr());
11874 C->setLParenLoc(Record.readSourceLocation());
11875}
11876
11877void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11878 C->setDefaultKind(
11879 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
11880 C->setLParenLoc(Record.readSourceLocation());
11881 C->setDefaultKindKwLoc(Record.readSourceLocation());
11882}
11883
11884void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011885 C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
Kelvin Libe286f52018-09-15 13:54:15 +000011886 C->setLParenLoc(Record.readSourceLocation());
11887 C->setProcBindKindKwLoc(Record.readSourceLocation());
11888}
11889
11890void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11891 VisitOMPClauseWithPreInit(C);
11892 C->setScheduleKind(
11893 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11894 C->setFirstScheduleModifier(
11895 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11896 C->setSecondScheduleModifier(
11897 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11898 C->setChunkSize(Record.readSubExpr());
11899 C->setLParenLoc(Record.readSourceLocation());
11900 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11901 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11902 C->setScheduleKindLoc(Record.readSourceLocation());
11903 C->setCommaLoc(Record.readSourceLocation());
11904}
11905
11906void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11907 C->setNumForLoops(Record.readSubExpr());
11908 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11909 C->setLoopNumIterations(I, Record.readSubExpr());
11910 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11911 C->setLoopCounter(I, Record.readSubExpr());
11912 C->setLParenLoc(Record.readSourceLocation());
11913}
11914
11915void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11916
11917void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11918
11919void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11920
11921void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11922
11923void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11924
11925void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
11926
11927void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11928
11929void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11930
11931void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11932
11933void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11934
11935void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11936
Kelvin Li1408f912018-09-26 04:28:39 +000011937void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
11938
Patrick Lyster4a370b92018-10-01 13:47:43 +000011939void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
11940 OMPUnifiedSharedMemoryClause *) {}
11941
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011942void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
11943
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011944void
11945OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
11946}
11947
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011948void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
11949 OMPAtomicDefaultMemOrderClause *C) {
11950 C->setAtomicDefaultMemOrderKind(
11951 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
11952 C->setLParenLoc(Record.readSourceLocation());
11953 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
11954}
11955
Kelvin Libe286f52018-09-15 13:54:15 +000011956void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11957 C->setLParenLoc(Record.readSourceLocation());
11958 unsigned NumVars = C->varlist_size();
11959 SmallVector<Expr *, 16> Vars;
11960 Vars.reserve(NumVars);
11961 for (unsigned i = 0; i != NumVars; ++i)
11962 Vars.push_back(Record.readSubExpr());
11963 C->setVarRefs(Vars);
11964 Vars.clear();
11965 for (unsigned i = 0; i != NumVars; ++i)
11966 Vars.push_back(Record.readSubExpr());
11967 C->setPrivateCopies(Vars);
11968}
11969
11970void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11971 VisitOMPClauseWithPreInit(C);
11972 C->setLParenLoc(Record.readSourceLocation());
11973 unsigned NumVars = C->varlist_size();
11974 SmallVector<Expr *, 16> Vars;
11975 Vars.reserve(NumVars);
11976 for (unsigned i = 0; i != NumVars; ++i)
11977 Vars.push_back(Record.readSubExpr());
11978 C->setVarRefs(Vars);
11979 Vars.clear();
11980 for (unsigned i = 0; i != NumVars; ++i)
11981 Vars.push_back(Record.readSubExpr());
11982 C->setPrivateCopies(Vars);
11983 Vars.clear();
11984 for (unsigned i = 0; i != NumVars; ++i)
11985 Vars.push_back(Record.readSubExpr());
11986 C->setInits(Vars);
11987}
11988
11989void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11990 VisitOMPClauseWithPostUpdate(C);
11991 C->setLParenLoc(Record.readSourceLocation());
Alexey Bataev93dc40d2019-12-20 11:04:57 -050011992 C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
11993 C->setKindLoc(Record.readSourceLocation());
11994 C->setColonLoc(Record.readSourceLocation());
Kelvin Libe286f52018-09-15 13:54:15 +000011995 unsigned NumVars = C->varlist_size();
11996 SmallVector<Expr *, 16> Vars;
11997 Vars.reserve(NumVars);
11998 for (unsigned i = 0; i != NumVars; ++i)
11999 Vars.push_back(Record.readSubExpr());
12000 C->setVarRefs(Vars);
12001 Vars.clear();
12002 for (unsigned i = 0; i != NumVars; ++i)
12003 Vars.push_back(Record.readSubExpr());
12004 C->setPrivateCopies(Vars);
12005 Vars.clear();
12006 for (unsigned i = 0; i != NumVars; ++i)
12007 Vars.push_back(Record.readSubExpr());
12008 C->setSourceExprs(Vars);
12009 Vars.clear();
12010 for (unsigned i = 0; i != NumVars; ++i)
12011 Vars.push_back(Record.readSubExpr());
12012 C->setDestinationExprs(Vars);
12013 Vars.clear();
12014 for (unsigned i = 0; i != NumVars; ++i)
12015 Vars.push_back(Record.readSubExpr());
12016 C->setAssignmentOps(Vars);
12017}
12018
12019void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12020 C->setLParenLoc(Record.readSourceLocation());
12021 unsigned NumVars = C->varlist_size();
12022 SmallVector<Expr *, 16> Vars;
12023 Vars.reserve(NumVars);
12024 for (unsigned i = 0; i != NumVars; ++i)
12025 Vars.push_back(Record.readSubExpr());
12026 C->setVarRefs(Vars);
12027}
12028
12029void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12030 VisitOMPClauseWithPostUpdate(C);
12031 C->setLParenLoc(Record.readSourceLocation());
12032 C->setColonLoc(Record.readSourceLocation());
12033 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012034 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012035 C->setQualifierLoc(NNSL);
12036 C->setNameInfo(DNI);
12037
12038 unsigned NumVars = C->varlist_size();
12039 SmallVector<Expr *, 16> Vars;
12040 Vars.reserve(NumVars);
12041 for (unsigned i = 0; i != NumVars; ++i)
12042 Vars.push_back(Record.readSubExpr());
12043 C->setVarRefs(Vars);
12044 Vars.clear();
12045 for (unsigned i = 0; i != NumVars; ++i)
12046 Vars.push_back(Record.readSubExpr());
12047 C->setPrivates(Vars);
12048 Vars.clear();
12049 for (unsigned i = 0; i != NumVars; ++i)
12050 Vars.push_back(Record.readSubExpr());
12051 C->setLHSExprs(Vars);
12052 Vars.clear();
12053 for (unsigned i = 0; i != NumVars; ++i)
12054 Vars.push_back(Record.readSubExpr());
12055 C->setRHSExprs(Vars);
12056 Vars.clear();
12057 for (unsigned i = 0; i != NumVars; ++i)
12058 Vars.push_back(Record.readSubExpr());
12059 C->setReductionOps(Vars);
12060}
12061
12062void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12063 VisitOMPClauseWithPostUpdate(C);
12064 C->setLParenLoc(Record.readSourceLocation());
12065 C->setColonLoc(Record.readSourceLocation());
12066 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012067 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012068 C->setQualifierLoc(NNSL);
12069 C->setNameInfo(DNI);
12070
12071 unsigned NumVars = C->varlist_size();
12072 SmallVector<Expr *, 16> Vars;
12073 Vars.reserve(NumVars);
12074 for (unsigned I = 0; I != NumVars; ++I)
12075 Vars.push_back(Record.readSubExpr());
12076 C->setVarRefs(Vars);
12077 Vars.clear();
12078 for (unsigned I = 0; I != NumVars; ++I)
12079 Vars.push_back(Record.readSubExpr());
12080 C->setPrivates(Vars);
12081 Vars.clear();
12082 for (unsigned I = 0; I != NumVars; ++I)
12083 Vars.push_back(Record.readSubExpr());
12084 C->setLHSExprs(Vars);
12085 Vars.clear();
12086 for (unsigned I = 0; I != NumVars; ++I)
12087 Vars.push_back(Record.readSubExpr());
12088 C->setRHSExprs(Vars);
12089 Vars.clear();
12090 for (unsigned I = 0; I != NumVars; ++I)
12091 Vars.push_back(Record.readSubExpr());
12092 C->setReductionOps(Vars);
12093}
12094
12095void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12096 VisitOMPClauseWithPostUpdate(C);
12097 C->setLParenLoc(Record.readSourceLocation());
12098 C->setColonLoc(Record.readSourceLocation());
12099 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
John McCall3ce3d232019-12-13 03:37:23 -050012100 DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
Kelvin Libe286f52018-09-15 13:54:15 +000012101 C->setQualifierLoc(NNSL);
12102 C->setNameInfo(DNI);
12103
12104 unsigned NumVars = C->varlist_size();
12105 SmallVector<Expr *, 16> Vars;
12106 Vars.reserve(NumVars);
12107 for (unsigned I = 0; I != NumVars; ++I)
12108 Vars.push_back(Record.readSubExpr());
12109 C->setVarRefs(Vars);
12110 Vars.clear();
12111 for (unsigned I = 0; I != NumVars; ++I)
12112 Vars.push_back(Record.readSubExpr());
12113 C->setPrivates(Vars);
12114 Vars.clear();
12115 for (unsigned I = 0; I != NumVars; ++I)
12116 Vars.push_back(Record.readSubExpr());
12117 C->setLHSExprs(Vars);
12118 Vars.clear();
12119 for (unsigned I = 0; I != NumVars; ++I)
12120 Vars.push_back(Record.readSubExpr());
12121 C->setRHSExprs(Vars);
12122 Vars.clear();
12123 for (unsigned I = 0; I != NumVars; ++I)
12124 Vars.push_back(Record.readSubExpr());
12125 C->setReductionOps(Vars);
12126 Vars.clear();
12127 for (unsigned I = 0; I != NumVars; ++I)
12128 Vars.push_back(Record.readSubExpr());
12129 C->setTaskgroupDescriptors(Vars);
12130}
12131
12132void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12133 VisitOMPClauseWithPostUpdate(C);
12134 C->setLParenLoc(Record.readSourceLocation());
12135 C->setColonLoc(Record.readSourceLocation());
12136 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12137 C->setModifierLoc(Record.readSourceLocation());
12138 unsigned NumVars = C->varlist_size();
12139 SmallVector<Expr *, 16> Vars;
12140 Vars.reserve(NumVars);
12141 for (unsigned i = 0; i != NumVars; ++i)
12142 Vars.push_back(Record.readSubExpr());
12143 C->setVarRefs(Vars);
12144 Vars.clear();
12145 for (unsigned i = 0; i != NumVars; ++i)
12146 Vars.push_back(Record.readSubExpr());
12147 C->setPrivates(Vars);
12148 Vars.clear();
12149 for (unsigned i = 0; i != NumVars; ++i)
12150 Vars.push_back(Record.readSubExpr());
12151 C->setInits(Vars);
12152 Vars.clear();
12153 for (unsigned i = 0; i != NumVars; ++i)
12154 Vars.push_back(Record.readSubExpr());
12155 C->setUpdates(Vars);
12156 Vars.clear();
12157 for (unsigned i = 0; i != NumVars; ++i)
12158 Vars.push_back(Record.readSubExpr());
12159 C->setFinals(Vars);
12160 C->setStep(Record.readSubExpr());
12161 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012162 Vars.clear();
12163 for (unsigned I = 0; I != NumVars + 1; ++I)
12164 Vars.push_back(Record.readSubExpr());
12165 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012166}
12167
12168void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12169 C->setLParenLoc(Record.readSourceLocation());
12170 C->setColonLoc(Record.readSourceLocation());
12171 unsigned NumVars = C->varlist_size();
12172 SmallVector<Expr *, 16> Vars;
12173 Vars.reserve(NumVars);
12174 for (unsigned i = 0; i != NumVars; ++i)
12175 Vars.push_back(Record.readSubExpr());
12176 C->setVarRefs(Vars);
12177 C->setAlignment(Record.readSubExpr());
12178}
12179
12180void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12181 C->setLParenLoc(Record.readSourceLocation());
12182 unsigned NumVars = C->varlist_size();
12183 SmallVector<Expr *, 16> Exprs;
12184 Exprs.reserve(NumVars);
12185 for (unsigned i = 0; i != NumVars; ++i)
12186 Exprs.push_back(Record.readSubExpr());
12187 C->setVarRefs(Exprs);
12188 Exprs.clear();
12189 for (unsigned i = 0; i != NumVars; ++i)
12190 Exprs.push_back(Record.readSubExpr());
12191 C->setSourceExprs(Exprs);
12192 Exprs.clear();
12193 for (unsigned i = 0; i != NumVars; ++i)
12194 Exprs.push_back(Record.readSubExpr());
12195 C->setDestinationExprs(Exprs);
12196 Exprs.clear();
12197 for (unsigned i = 0; i != NumVars; ++i)
12198 Exprs.push_back(Record.readSubExpr());
12199 C->setAssignmentOps(Exprs);
12200}
12201
12202void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12203 C->setLParenLoc(Record.readSourceLocation());
12204 unsigned NumVars = C->varlist_size();
12205 SmallVector<Expr *, 16> Exprs;
12206 Exprs.reserve(NumVars);
12207 for (unsigned i = 0; i != NumVars; ++i)
12208 Exprs.push_back(Record.readSubExpr());
12209 C->setVarRefs(Exprs);
12210 Exprs.clear();
12211 for (unsigned i = 0; i != NumVars; ++i)
12212 Exprs.push_back(Record.readSubExpr());
12213 C->setSourceExprs(Exprs);
12214 Exprs.clear();
12215 for (unsigned i = 0; i != NumVars; ++i)
12216 Exprs.push_back(Record.readSubExpr());
12217 C->setDestinationExprs(Exprs);
12218 Exprs.clear();
12219 for (unsigned i = 0; i != NumVars; ++i)
12220 Exprs.push_back(Record.readSubExpr());
12221 C->setAssignmentOps(Exprs);
12222}
12223
12224void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12225 C->setLParenLoc(Record.readSourceLocation());
12226 unsigned NumVars = C->varlist_size();
12227 SmallVector<Expr *, 16> Vars;
12228 Vars.reserve(NumVars);
12229 for (unsigned i = 0; i != NumVars; ++i)
12230 Vars.push_back(Record.readSubExpr());
12231 C->setVarRefs(Vars);
12232}
12233
12234void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12235 C->setLParenLoc(Record.readSourceLocation());
12236 C->setDependencyKind(
12237 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12238 C->setDependencyLoc(Record.readSourceLocation());
12239 C->setColonLoc(Record.readSourceLocation());
12240 unsigned NumVars = C->varlist_size();
12241 SmallVector<Expr *, 16> Vars;
12242 Vars.reserve(NumVars);
12243 for (unsigned I = 0; I != NumVars; ++I)
12244 Vars.push_back(Record.readSubExpr());
12245 C->setVarRefs(Vars);
12246 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12247 C->setLoopData(I, Record.readSubExpr());
12248}
12249
12250void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12251 VisitOMPClauseWithPreInit(C);
12252 C->setDevice(Record.readSubExpr());
12253 C->setLParenLoc(Record.readSourceLocation());
12254}
12255
12256void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12257 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012258 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12259 C->setMapTypeModifier(
12260 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12261 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12262 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012263 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012264 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012265 C->setMapType(
12266 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12267 C->setMapLoc(Record.readSourceLocation());
12268 C->setColonLoc(Record.readSourceLocation());
12269 auto NumVars = C->varlist_size();
12270 auto UniqueDecls = C->getUniqueDeclarationsNum();
12271 auto TotalLists = C->getTotalComponentListNum();
12272 auto TotalComponents = C->getTotalComponentsNum();
12273
12274 SmallVector<Expr *, 16> Vars;
12275 Vars.reserve(NumVars);
12276 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012277 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012278 C->setVarRefs(Vars);
12279
Michael Kruse4304e9d2019-02-19 16:38:20 +000012280 SmallVector<Expr *, 16> UDMappers;
12281 UDMappers.reserve(NumVars);
12282 for (unsigned I = 0; I < NumVars; ++I)
12283 UDMappers.push_back(Record.readExpr());
12284 C->setUDMapperRefs(UDMappers);
12285
Kelvin Libe286f52018-09-15 13:54:15 +000012286 SmallVector<ValueDecl *, 16> Decls;
12287 Decls.reserve(UniqueDecls);
12288 for (unsigned i = 0; i < UniqueDecls; ++i)
12289 Decls.push_back(Record.readDeclAs<ValueDecl>());
12290 C->setUniqueDecls(Decls);
12291
12292 SmallVector<unsigned, 16> ListsPerDecl;
12293 ListsPerDecl.reserve(UniqueDecls);
12294 for (unsigned i = 0; i < UniqueDecls; ++i)
12295 ListsPerDecl.push_back(Record.readInt());
12296 C->setDeclNumLists(ListsPerDecl);
12297
12298 SmallVector<unsigned, 32> ListSizes;
12299 ListSizes.reserve(TotalLists);
12300 for (unsigned i = 0; i < TotalLists; ++i)
12301 ListSizes.push_back(Record.readInt());
12302 C->setComponentListSizes(ListSizes);
12303
12304 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12305 Components.reserve(TotalComponents);
12306 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012307 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012308 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12309 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12310 AssociatedExpr, AssociatedDecl));
12311 }
12312 C->setComponents(Components, ListSizes);
12313}
12314
Alexey Bataeve04483e2019-03-27 14:14:31 +000012315void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12316 C->setLParenLoc(Record.readSourceLocation());
12317 C->setColonLoc(Record.readSourceLocation());
12318 C->setAllocator(Record.readSubExpr());
12319 unsigned NumVars = C->varlist_size();
12320 SmallVector<Expr *, 16> Vars;
12321 Vars.reserve(NumVars);
12322 for (unsigned i = 0; i != NumVars; ++i)
12323 Vars.push_back(Record.readSubExpr());
12324 C->setVarRefs(Vars);
12325}
12326
Kelvin Libe286f52018-09-15 13:54:15 +000012327void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12328 VisitOMPClauseWithPreInit(C);
12329 C->setNumTeams(Record.readSubExpr());
12330 C->setLParenLoc(Record.readSourceLocation());
12331}
12332
12333void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12334 VisitOMPClauseWithPreInit(C);
12335 C->setThreadLimit(Record.readSubExpr());
12336 C->setLParenLoc(Record.readSourceLocation());
12337}
12338
12339void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
Alexey Bataev31ba4762019-10-16 18:09:37 +000012340 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012341 C->setPriority(Record.readSubExpr());
12342 C->setLParenLoc(Record.readSourceLocation());
12343}
12344
12345void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
Alexey Bataevb9c55e22019-10-14 19:29:52 +000012346 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012347 C->setGrainsize(Record.readSubExpr());
12348 C->setLParenLoc(Record.readSourceLocation());
12349}
12350
12351void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
Alexey Bataevd88c7de2019-10-14 20:44:34 +000012352 VisitOMPClauseWithPreInit(C);
Kelvin Libe286f52018-09-15 13:54:15 +000012353 C->setNumTasks(Record.readSubExpr());
12354 C->setLParenLoc(Record.readSourceLocation());
12355}
12356
12357void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12358 C->setHint(Record.readSubExpr());
12359 C->setLParenLoc(Record.readSourceLocation());
12360}
12361
12362void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12363 VisitOMPClauseWithPreInit(C);
12364 C->setDistScheduleKind(
12365 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12366 C->setChunkSize(Record.readSubExpr());
12367 C->setLParenLoc(Record.readSourceLocation());
12368 C->setDistScheduleKindLoc(Record.readSourceLocation());
12369 C->setCommaLoc(Record.readSourceLocation());
12370}
12371
12372void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12373 C->setDefaultmapKind(
12374 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12375 C->setDefaultmapModifier(
12376 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12377 C->setLParenLoc(Record.readSourceLocation());
12378 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12379 C->setDefaultmapKindLoc(Record.readSourceLocation());
12380}
12381
12382void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12383 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012384 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012385 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012386 auto NumVars = C->varlist_size();
12387 auto UniqueDecls = C->getUniqueDeclarationsNum();
12388 auto TotalLists = C->getTotalComponentListNum();
12389 auto TotalComponents = C->getTotalComponentsNum();
12390
12391 SmallVector<Expr *, 16> Vars;
12392 Vars.reserve(NumVars);
12393 for (unsigned i = 0; i != NumVars; ++i)
12394 Vars.push_back(Record.readSubExpr());
12395 C->setVarRefs(Vars);
12396
Michael Kruse01f670d2019-02-22 22:29:42 +000012397 SmallVector<Expr *, 16> UDMappers;
12398 UDMappers.reserve(NumVars);
12399 for (unsigned I = 0; I < NumVars; ++I)
12400 UDMappers.push_back(Record.readSubExpr());
12401 C->setUDMapperRefs(UDMappers);
12402
Kelvin Libe286f52018-09-15 13:54:15 +000012403 SmallVector<ValueDecl *, 16> Decls;
12404 Decls.reserve(UniqueDecls);
12405 for (unsigned i = 0; i < UniqueDecls; ++i)
12406 Decls.push_back(Record.readDeclAs<ValueDecl>());
12407 C->setUniqueDecls(Decls);
12408
12409 SmallVector<unsigned, 16> ListsPerDecl;
12410 ListsPerDecl.reserve(UniqueDecls);
12411 for (unsigned i = 0; i < UniqueDecls; ++i)
12412 ListsPerDecl.push_back(Record.readInt());
12413 C->setDeclNumLists(ListsPerDecl);
12414
12415 SmallVector<unsigned, 32> ListSizes;
12416 ListSizes.reserve(TotalLists);
12417 for (unsigned i = 0; i < TotalLists; ++i)
12418 ListSizes.push_back(Record.readInt());
12419 C->setComponentListSizes(ListSizes);
12420
12421 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12422 Components.reserve(TotalComponents);
12423 for (unsigned i = 0; i < TotalComponents; ++i) {
12424 Expr *AssociatedExpr = Record.readSubExpr();
12425 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12426 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12427 AssociatedExpr, AssociatedDecl));
12428 }
12429 C->setComponents(Components, ListSizes);
12430}
12431
12432void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12433 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000012434 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
John McCall3ce3d232019-12-13 03:37:23 -050012435 C->setMapperIdInfo(Record.readDeclarationNameInfo());
Kelvin Libe286f52018-09-15 13:54:15 +000012436 auto NumVars = C->varlist_size();
12437 auto UniqueDecls = C->getUniqueDeclarationsNum();
12438 auto TotalLists = C->getTotalComponentListNum();
12439 auto TotalComponents = C->getTotalComponentsNum();
12440
12441 SmallVector<Expr *, 16> Vars;
12442 Vars.reserve(NumVars);
12443 for (unsigned i = 0; i != NumVars; ++i)
12444 Vars.push_back(Record.readSubExpr());
12445 C->setVarRefs(Vars);
12446
Michael Kruse0336c752019-02-25 20:34:15 +000012447 SmallVector<Expr *, 16> UDMappers;
12448 UDMappers.reserve(NumVars);
12449 for (unsigned I = 0; I < NumVars; ++I)
12450 UDMappers.push_back(Record.readSubExpr());
12451 C->setUDMapperRefs(UDMappers);
12452
Kelvin Libe286f52018-09-15 13:54:15 +000012453 SmallVector<ValueDecl *, 16> Decls;
12454 Decls.reserve(UniqueDecls);
12455 for (unsigned i = 0; i < UniqueDecls; ++i)
12456 Decls.push_back(Record.readDeclAs<ValueDecl>());
12457 C->setUniqueDecls(Decls);
12458
12459 SmallVector<unsigned, 16> ListsPerDecl;
12460 ListsPerDecl.reserve(UniqueDecls);
12461 for (unsigned i = 0; i < UniqueDecls; ++i)
12462 ListsPerDecl.push_back(Record.readInt());
12463 C->setDeclNumLists(ListsPerDecl);
12464
12465 SmallVector<unsigned, 32> ListSizes;
12466 ListSizes.reserve(TotalLists);
12467 for (unsigned i = 0; i < TotalLists; ++i)
12468 ListSizes.push_back(Record.readInt());
12469 C->setComponentListSizes(ListSizes);
12470
12471 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12472 Components.reserve(TotalComponents);
12473 for (unsigned i = 0; i < TotalComponents; ++i) {
12474 Expr *AssociatedExpr = Record.readSubExpr();
12475 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12476 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12477 AssociatedExpr, AssociatedDecl));
12478 }
12479 C->setComponents(Components, ListSizes);
12480}
12481
12482void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12483 C->setLParenLoc(Record.readSourceLocation());
12484 auto NumVars = C->varlist_size();
12485 auto UniqueDecls = C->getUniqueDeclarationsNum();
12486 auto TotalLists = C->getTotalComponentListNum();
12487 auto TotalComponents = C->getTotalComponentsNum();
12488
12489 SmallVector<Expr *, 16> Vars;
12490 Vars.reserve(NumVars);
12491 for (unsigned i = 0; i != NumVars; ++i)
12492 Vars.push_back(Record.readSubExpr());
12493 C->setVarRefs(Vars);
12494 Vars.clear();
12495 for (unsigned i = 0; i != NumVars; ++i)
12496 Vars.push_back(Record.readSubExpr());
12497 C->setPrivateCopies(Vars);
12498 Vars.clear();
12499 for (unsigned i = 0; i != NumVars; ++i)
12500 Vars.push_back(Record.readSubExpr());
12501 C->setInits(Vars);
12502
12503 SmallVector<ValueDecl *, 16> Decls;
12504 Decls.reserve(UniqueDecls);
12505 for (unsigned i = 0; i < UniqueDecls; ++i)
12506 Decls.push_back(Record.readDeclAs<ValueDecl>());
12507 C->setUniqueDecls(Decls);
12508
12509 SmallVector<unsigned, 16> ListsPerDecl;
12510 ListsPerDecl.reserve(UniqueDecls);
12511 for (unsigned i = 0; i < UniqueDecls; ++i)
12512 ListsPerDecl.push_back(Record.readInt());
12513 C->setDeclNumLists(ListsPerDecl);
12514
12515 SmallVector<unsigned, 32> ListSizes;
12516 ListSizes.reserve(TotalLists);
12517 for (unsigned i = 0; i < TotalLists; ++i)
12518 ListSizes.push_back(Record.readInt());
12519 C->setComponentListSizes(ListSizes);
12520
12521 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12522 Components.reserve(TotalComponents);
12523 for (unsigned i = 0; i < TotalComponents; ++i) {
12524 Expr *AssociatedExpr = Record.readSubExpr();
12525 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12526 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12527 AssociatedExpr, AssociatedDecl));
12528 }
12529 C->setComponents(Components, ListSizes);
12530}
12531
12532void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12533 C->setLParenLoc(Record.readSourceLocation());
12534 auto NumVars = C->varlist_size();
12535 auto UniqueDecls = C->getUniqueDeclarationsNum();
12536 auto TotalLists = C->getTotalComponentListNum();
12537 auto TotalComponents = C->getTotalComponentsNum();
12538
12539 SmallVector<Expr *, 16> Vars;
12540 Vars.reserve(NumVars);
12541 for (unsigned i = 0; i != NumVars; ++i)
12542 Vars.push_back(Record.readSubExpr());
12543 C->setVarRefs(Vars);
12544 Vars.clear();
12545
12546 SmallVector<ValueDecl *, 16> Decls;
12547 Decls.reserve(UniqueDecls);
12548 for (unsigned i = 0; i < UniqueDecls; ++i)
12549 Decls.push_back(Record.readDeclAs<ValueDecl>());
12550 C->setUniqueDecls(Decls);
12551
12552 SmallVector<unsigned, 16> ListsPerDecl;
12553 ListsPerDecl.reserve(UniqueDecls);
12554 for (unsigned i = 0; i < UniqueDecls; ++i)
12555 ListsPerDecl.push_back(Record.readInt());
12556 C->setDeclNumLists(ListsPerDecl);
12557
12558 SmallVector<unsigned, 32> ListSizes;
12559 ListSizes.reserve(TotalLists);
12560 for (unsigned i = 0; i < TotalLists; ++i)
12561 ListSizes.push_back(Record.readInt());
12562 C->setComponentListSizes(ListSizes);
12563
12564 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12565 Components.reserve(TotalComponents);
12566 for (unsigned i = 0; i < TotalComponents; ++i) {
12567 Expr *AssociatedExpr = Record.readSubExpr();
12568 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12569 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12570 AssociatedExpr, AssociatedDecl));
12571 }
12572 C->setComponents(Components, ListSizes);
12573}
Alexey Bataevb6e70842019-12-16 15:54:17 -050012574
12575void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
12576 C->setLParenLoc(Record.readSourceLocation());
12577 unsigned NumVars = C->varlist_size();
12578 SmallVector<Expr *, 16> Vars;
12579 Vars.reserve(NumVars);
12580 for (unsigned i = 0; i != NumVars; ++i)
12581 Vars.push_back(Record.readSubExpr());
12582 C->setVarRefs(Vars);
Alexey Bataev0860db92019-12-19 10:01:10 -050012583 Vars.clear();
12584 Vars.reserve(NumVars);
12585 for (unsigned i = 0; i != NumVars; ++i)
12586 Vars.push_back(Record.readSubExpr());
12587 C->setPrivateRefs(Vars);
Alexey Bataevb6e70842019-12-16 15:54:17 -050012588}
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012589
12590void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
12591 C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
12592 C->setLParenLoc(Record.readSourceLocation());
12593 C->setKindKwLoc(Record.readSourceLocation());
12594}