blob: 55bec61693a3782fca431443298b67a17b54ccad [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
13#include "clang/Serialization/ASTReader.h"
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000018#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/ASTUnresolvedSet.h"
20#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000021#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000022#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000023#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000024#include "clang/AST/DeclGroup.h"
25#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000027#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000028#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000030#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000032#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000034#include "clang/AST/TemplateBase.h"
35#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000037#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000039#include "clang/AST/UnresolvedSet.h"
40#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000041#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000042#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000043#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000046#include "clang/Basic/IdentifierTable.h"
47#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include "clang/Basic/LangOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000049#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Basic/ObjCRuntime.h"
51#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000052#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000053#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000054#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Basic/SourceManager.h"
56#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000057#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000058#include "clang/Basic/TargetInfo.h"
59#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Basic/Version.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000062#include "clang/Lex/HeaderSearch.h"
63#include "clang/Lex/HeaderSearchOptions.h"
64#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000066#include "clang/Lex/PreprocessingRecord.h"
67#include "clang/Lex/Preprocessor.h"
68#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000069#include "clang/Lex/Token.h"
70#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000071#include "clang/Sema/Scope.h"
72#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000074#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000076#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000077#include "clang/Serialization/GlobalModuleIndex.h"
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000078#include "clang/Serialization/InMemoryModuleCache.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000079#include "clang/Serialization/Module.h"
80#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000081#include "clang/Serialization/ModuleManager.h"
Richard Trieuf3b00462018-12-12 02:53:59 +000082#include "clang/Serialization/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000084#include "llvm/ADT/APFloat.h"
85#include "llvm/ADT/APInt.h"
86#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000087#include "llvm/ADT/ArrayRef.h"
88#include "llvm/ADT/DenseMap.h"
89#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000090#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000091#include "llvm/ADT/IntrusiveRefCntPtr.h"
92#include "llvm/ADT/None.h"
93#include "llvm/ADT/Optional.h"
94#include "llvm/ADT/STLExtras.h"
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +000095#include "llvm/ADT/ScopeExit.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000096#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000097#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000098#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +000099#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000100#include "llvm/ADT/StringMap.h"
101#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000102#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000103#include "llvm/ADT/iterator_range.h"
Francis Visoiu Mistrihe0308272019-07-03 22:40:07 +0000104#include "llvm/Bitstream/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000105#include "llvm/Support/Casting.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000106#include "llvm/Support/Compiler.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000107#include "llvm/Support/Compression.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000108#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000109#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000110#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000111#include "llvm/Support/ErrorHandling.h"
112#include "llvm/Support/FileSystem.h"
113#include "llvm/Support/MemoryBuffer.h"
114#include "llvm/Support/Path.h"
115#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000116#include "llvm/Support/Timer.h"
Pavel Labathd8c62902018-06-11 10:28:04 +0000117#include "llvm/Support/VersionTuple.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +0000118#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000119#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000120#include <cassert>
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000121#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000122#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +0000123#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000124#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +0000125#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000126#include <limits>
127#include <map>
128#include <memory>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000129#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +0000130#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000131#include <tuple>
132#include <utility>
133#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000134
135using namespace clang;
Vedant Kumar48b4f762018-04-14 01:40:48 +0000136using namespace clang::serialization;
137using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000138using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000139
Ben Langmuircb69b572014-03-07 06:40:32 +0000140//===----------------------------------------------------------------------===//
141// ChainedASTReaderListener implementation
142//===----------------------------------------------------------------------===//
143
144bool
145ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
146 return First->ReadFullVersionInformation(FullVersion) ||
147 Second->ReadFullVersionInformation(FullVersion);
148}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000149
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000150void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
151 First->ReadModuleName(ModuleName);
152 Second->ReadModuleName(ModuleName);
153}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000154
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000155void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
156 First->ReadModuleMapFile(ModuleMapPath);
157 Second->ReadModuleMapFile(ModuleMapPath);
158}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000159
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000160bool
161ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
162 bool Complain,
163 bool AllowCompatibleDifferences) {
164 return First->ReadLanguageOptions(LangOpts, Complain,
165 AllowCompatibleDifferences) ||
166 Second->ReadLanguageOptions(LangOpts, Complain,
167 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000169
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000170bool ChainedASTReaderListener::ReadTargetOptions(
171 const TargetOptions &TargetOpts, bool Complain,
172 bool AllowCompatibleDifferences) {
173 return First->ReadTargetOptions(TargetOpts, Complain,
174 AllowCompatibleDifferences) ||
175 Second->ReadTargetOptions(TargetOpts, Complain,
176 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000177}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000178
Ben Langmuircb69b572014-03-07 06:40:32 +0000179bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000180 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000181 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
182 Second->ReadDiagnosticOptions(DiagOpts, Complain);
183}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000184
Ben Langmuircb69b572014-03-07 06:40:32 +0000185bool
186ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
187 bool Complain) {
188 return First->ReadFileSystemOptions(FSOpts, Complain) ||
189 Second->ReadFileSystemOptions(FSOpts, Complain);
190}
191
192bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000193 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
194 bool Complain) {
195 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
196 Complain) ||
197 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
198 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000199}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000200
Ben Langmuircb69b572014-03-07 06:40:32 +0000201bool ChainedASTReaderListener::ReadPreprocessorOptions(
202 const PreprocessorOptions &PPOpts, bool Complain,
203 std::string &SuggestedPredefines) {
204 return First->ReadPreprocessorOptions(PPOpts, Complain,
205 SuggestedPredefines) ||
206 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
207}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000208
Ben Langmuircb69b572014-03-07 06:40:32 +0000209void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
210 unsigned Value) {
211 First->ReadCounter(M, Value);
212 Second->ReadCounter(M, Value);
213}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000214
Ben Langmuircb69b572014-03-07 06:40:32 +0000215bool ChainedASTReaderListener::needsInputFileVisitation() {
216 return First->needsInputFileVisitation() ||
217 Second->needsInputFileVisitation();
218}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000219
Ben Langmuircb69b572014-03-07 06:40:32 +0000220bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
221 return First->needsSystemInputFileVisitation() ||
222 Second->needsSystemInputFileVisitation();
223}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000224
Richard Smith216a3bd2015-08-13 17:57:10 +0000225void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
226 ModuleKind Kind) {
227 First->visitModuleFile(Filename, Kind);
228 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000230
Ben Langmuircb69b572014-03-07 06:40:32 +0000231bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000232 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000233 bool isOverridden,
234 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000235 bool Continue = false;
236 if (First->needsInputFileVisitation() &&
237 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000238 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
239 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000240 if (Second->needsInputFileVisitation() &&
241 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000242 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
243 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000244 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000245}
246
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000247void ChainedASTReaderListener::readModuleFileExtension(
248 const ModuleFileExtensionMetadata &Metadata) {
249 First->readModuleFileExtension(Metadata);
250 Second->readModuleFileExtension(Metadata);
251}
252
Guy Benyei11169dd2012-12-18 14:30:41 +0000253//===----------------------------------------------------------------------===//
254// PCH validator implementation
255//===----------------------------------------------------------------------===//
256
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000257ASTReaderListener::~ASTReaderListener() = default;
Guy Benyei11169dd2012-12-18 14:30:41 +0000258
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000259/// Compare the given set of language options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000260/// language options.
261///
262/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000263/// \param AllowCompatibleDifferences If true, differences between compatible
264/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000265///
266/// \returns true if the languagae options mis-match, false otherwise.
267static bool checkLanguageOptions(const LangOptions &LangOpts,
268 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000269 DiagnosticsEngine *Diags,
270 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000271#define LANGOPT(Name, Bits, Default, Description) \
272 if (ExistingLangOpts.Name != LangOpts.Name) { \
273 if (Diags) \
274 Diags->Report(diag::err_pch_langopt_mismatch) \
275 << Description << LangOpts.Name << ExistingLangOpts.Name; \
276 return true; \
277 }
278
279#define VALUE_LANGOPT(Name, Bits, Default, Description) \
280 if (ExistingLangOpts.Name != LangOpts.Name) { \
281 if (Diags) \
282 Diags->Report(diag::err_pch_langopt_value_mismatch) \
283 << Description; \
284 return true; \
285 }
286
287#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
288 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
289 if (Diags) \
290 Diags->Report(diag::err_pch_langopt_value_mismatch) \
291 << Description; \
292 return true; \
293 }
294
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000295#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
296 if (!AllowCompatibleDifferences) \
297 LANGOPT(Name, Bits, Default, Description)
298
299#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
300 if (!AllowCompatibleDifferences) \
301 ENUM_LANGOPT(Name, Bits, Default, Description)
302
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000303#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
304 if (!AllowCompatibleDifferences) \
305 VALUE_LANGOPT(Name, Bits, Default, Description)
306
Guy Benyei11169dd2012-12-18 14:30:41 +0000307#define BENIGN_LANGOPT(Name, Bits, Default, Description)
308#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000309#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310#include "clang/Basic/LangOptions.def"
311
Ben Langmuircd98cb72015-06-23 18:20:18 +0000312 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
313 if (Diags)
314 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
315 return true;
316 }
317
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
319 if (Diags)
320 Diags->Report(diag::err_pch_langopt_value_mismatch)
321 << "target Objective-C runtime";
322 return true;
323 }
324
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000325 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
326 LangOpts.CommentOpts.BlockCommandNames) {
327 if (Diags)
328 Diags->Report(diag::err_pch_langopt_value_mismatch)
329 << "block command names";
330 return true;
331 }
332
Vedant Kumar85a83c22017-06-01 20:01:01 +0000333 // Sanitizer feature mismatches are treated as compatible differences. If
334 // compatible differences aren't allowed, we still only want to check for
335 // mismatches of non-modular sanitizers (the only ones which can affect AST
336 // generation).
337 if (!AllowCompatibleDifferences) {
338 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
339 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
340 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
341 ExistingSanitizers.clear(ModularSanitizers);
342 ImportedSanitizers.clear(ModularSanitizers);
343 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
344 const std::string Flag = "-fsanitize=";
345 if (Diags) {
346#define SANITIZER(NAME, ID) \
347 { \
348 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
349 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
350 if (InExistingModule != InImportedModule) \
351 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
352 << InExistingModule << (Flag + NAME); \
353 }
354#include "clang/Basic/Sanitizers.def"
355 }
356 return true;
357 }
358 }
359
Guy Benyei11169dd2012-12-18 14:30:41 +0000360 return false;
361}
362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000363/// Compare the given set of target options against an existing set of
Guy Benyei11169dd2012-12-18 14:30:41 +0000364/// target options.
365///
366/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
367///
368/// \returns true if the target options mis-match, false otherwise.
369static bool checkTargetOptions(const TargetOptions &TargetOpts,
370 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000371 DiagnosticsEngine *Diags,
372 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000373#define CHECK_TARGET_OPT(Field, Name) \
374 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
375 if (Diags) \
376 Diags->Report(diag::err_pch_targetopt_mismatch) \
377 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
378 return true; \
379 }
380
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000381 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000382 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000384
385 // We can tolerate different CPUs in many cases, notably when one CPU
386 // supports a strict superset of another. When allowing compatible
387 // differences skip this check.
388 if (!AllowCompatibleDifferences)
389 CHECK_TARGET_OPT(CPU, "target CPU");
390
Guy Benyei11169dd2012-12-18 14:30:41 +0000391#undef CHECK_TARGET_OPT
392
393 // Compare feature sets.
394 SmallVector<StringRef, 4> ExistingFeatures(
395 ExistingTargetOpts.FeaturesAsWritten.begin(),
396 ExistingTargetOpts.FeaturesAsWritten.end());
397 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
398 TargetOpts.FeaturesAsWritten.end());
Fangrui Song55fab262018-09-26 22:16:28 +0000399 llvm::sort(ExistingFeatures);
400 llvm::sort(ReadFeatures);
Guy Benyei11169dd2012-12-18 14:30:41 +0000401
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000402 // We compute the set difference in both directions explicitly so that we can
403 // diagnose the differences differently.
404 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
405 std::set_difference(
406 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
407 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
408 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
409 ExistingFeatures.begin(), ExistingFeatures.end(),
410 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000411
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000412 // If we are allowing compatible differences and the read feature set is
413 // a strict subset of the existing feature set, there is nothing to diagnose.
414 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
415 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000417 if (Diags) {
418 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000420 << /* is-existing-feature */ false << Feature;
421 for (StringRef Feature : UnmatchedExistingFeatures)
422 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
423 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 }
425
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000426 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000427}
428
429bool
430PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000431 bool Complain,
432 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000433 const LangOptions &ExistingLangOpts = PP.getLangOpts();
434 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000435 Complain ? &Reader.Diags : nullptr,
436 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000437}
438
439bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000440 bool Complain,
441 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
443 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000444 Complain ? &Reader.Diags : nullptr,
445 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000446}
447
448namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000449
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000450using MacroDefinitionsMap =
451 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
452using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000453
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000454} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000455
Ben Langmuirb92de022014-04-29 16:25:26 +0000456static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
457 DiagnosticsEngine &Diags,
458 bool Complain) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000459 using Level = DiagnosticsEngine::Level;
Ben Langmuirb92de022014-04-29 16:25:26 +0000460
461 // Check current mappings for new -Werror mappings, and the stored mappings
462 // for cases that were explicitly mapped to *not* be errors that are now
463 // errors because of options like -Werror.
464 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
465
Vedant Kumar48b4f762018-04-14 01:40:48 +0000466 for (DiagnosticsEngine *MappingSource : MappingSources) {
Ben Langmuirb92de022014-04-29 16:25:26 +0000467 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
468 diag::kind DiagID = DiagIDMappingPair.first;
469 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
470 if (CurLevel < DiagnosticsEngine::Error)
471 continue; // not significant
472 Level StoredLevel =
473 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
474 if (StoredLevel < DiagnosticsEngine::Error) {
475 if (Complain)
476 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
477 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
478 return true;
479 }
480 }
481 }
482
483 return false;
484}
485
Alp Tokerac4e8e52014-06-22 21:58:33 +0000486static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
487 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
488 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
489 return true;
490 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000491}
492
493static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
494 DiagnosticsEngine &Diags,
495 bool IsSystem, bool Complain) {
496 // Top-level options
497 if (IsSystem) {
498 if (Diags.getSuppressSystemWarnings())
499 return false;
500 // If -Wsystem-headers was not enabled before, be conservative
501 if (StoredDiags.getSuppressSystemWarnings()) {
502 if (Complain)
503 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
504 return true;
505 }
506 }
507
508 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
509 if (Complain)
510 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
511 return true;
512 }
513
514 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
515 !StoredDiags.getEnableAllWarnings()) {
516 if (Complain)
517 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
518 return true;
519 }
520
521 if (isExtHandlingFromDiagsError(Diags) &&
522 !isExtHandlingFromDiagsError(StoredDiags)) {
523 if (Complain)
524 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
525 return true;
526 }
527
528 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
529}
530
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000531/// Return the top import module if it is implicit, nullptr otherwise.
532static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
533 Preprocessor &PP) {
534 // If the original import came from a file explicitly generated by the user,
535 // don't check the diagnostic mappings.
536 // FIXME: currently this is approximated by checking whether this is not a
537 // module import of an implicitly-loaded module file.
538 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
539 // the transitive closure of its imports, since unrelated modules cannot be
540 // imported until after this module finishes validation.
541 ModuleFile *TopImport = &*ModuleMgr.rbegin();
542 while (!TopImport->ImportedBy.empty())
543 TopImport = TopImport->ImportedBy[0];
544 if (TopImport->Kind != MK_ImplicitModule)
545 return nullptr;
546
547 StringRef ModuleName = TopImport->ModuleName;
548 assert(!ModuleName.empty() && "diagnostic options read before module name");
549
550 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
551 assert(M && "missing module");
552 return M;
553}
554
Ben Langmuirb92de022014-04-29 16:25:26 +0000555bool PCHValidator::ReadDiagnosticOptions(
556 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
557 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
558 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
559 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000560 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000561 // This should never fail, because we would have processed these options
562 // before writing them to an ASTFile.
563 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
564
565 ModuleManager &ModuleMgr = Reader.getModuleManager();
566 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
567
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000568 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
569 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000570 return false;
571
Ben Langmuirb92de022014-04-29 16:25:26 +0000572 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
573 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000574 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
575 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000576}
577
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000578/// Collect the macro definitions provided by the given preprocessor
Guy Benyei11169dd2012-12-18 14:30:41 +0000579/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000580static void
581collectMacroDefinitions(const PreprocessorOptions &PPOpts,
582 MacroDefinitionsMap &Macros,
583 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000584 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
585 StringRef Macro = PPOpts.Macros[I].first;
586 bool IsUndef = PPOpts.Macros[I].second;
Guy Benyei11169dd2012-12-18 14:30:41 +0000587
588 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
589 StringRef MacroName = MacroPair.first;
590 StringRef MacroBody = MacroPair.second;
591
592 // For an #undef'd macro, we only care about the name.
593 if (IsUndef) {
594 if (MacroNames && !Macros.count(MacroName))
595 MacroNames->push_back(MacroName);
596
597 Macros[MacroName] = std::make_pair("", true);
598 continue;
599 }
600
601 // For a #define'd macro, figure out the actual definition.
602 if (MacroName.size() == Macro.size())
603 MacroBody = "1";
604 else {
605 // Note: GCC drops anything following an end-of-line character.
606 StringRef::size_type End = MacroBody.find_first_of("\n\r");
607 MacroBody = MacroBody.substr(0, End);
608 }
609
610 if (MacroNames && !Macros.count(MacroName))
611 MacroNames->push_back(MacroName);
612 Macros[MacroName] = std::make_pair(MacroBody, false);
613 }
614}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000615
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000616/// Check the preprocessor options deserialized from the control block
Guy Benyei11169dd2012-12-18 14:30:41 +0000617/// against the preprocessor options in an existing preprocessor.
618///
619/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000620/// \param Validate If true, validate preprocessor options. If false, allow
621/// macros defined by \p ExistingPPOpts to override those defined by
622/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000623static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
624 const PreprocessorOptions &ExistingPPOpts,
625 DiagnosticsEngine *Diags,
626 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000627 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000628 const LangOptions &LangOpts,
629 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000630 // Check macro definitions.
631 MacroDefinitionsMap ASTFileMacros;
632 collectMacroDefinitions(PPOpts, ASTFileMacros);
633 MacroDefinitionsMap ExistingMacros;
634 SmallVector<StringRef, 4> ExistingMacroNames;
635 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
636
Vedant Kumar48b4f762018-04-14 01:40:48 +0000637 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000638 // Dig out the macro definition in the existing preprocessor options.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000639 StringRef MacroName = ExistingMacroNames[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
641
642 // Check whether we know anything about this macro name or not.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000643 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
644 ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000645 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 // FIXME: Check whether this identifier was referenced anywhere in the
647 // AST file. If so, we should reject the AST file. Unfortunately, this
648 // information isn't in the control block. What shall we do about it?
649
650 if (Existing.second) {
651 SuggestedPredefines += "#undef ";
652 SuggestedPredefines += MacroName.str();
653 SuggestedPredefines += '\n';
654 } else {
655 SuggestedPredefines += "#define ";
656 SuggestedPredefines += MacroName.str();
657 SuggestedPredefines += ' ';
658 SuggestedPredefines += Existing.first.str();
659 SuggestedPredefines += '\n';
660 }
661 continue;
662 }
663
664 // If the macro was defined in one but undef'd in the other, we have a
665 // conflict.
666 if (Existing.second != Known->second.second) {
667 if (Diags) {
668 Diags->Report(diag::err_pch_macro_def_undef)
669 << MacroName << Known->second.second;
670 }
671 return true;
672 }
673
674 // If the macro was #undef'd in both, or if the macro bodies are identical,
675 // it's fine.
676 if (Existing.second || Existing.first == Known->second.first)
677 continue;
678
679 // The macro bodies differ; complain.
680 if (Diags) {
681 Diags->Report(diag::err_pch_macro_def_conflict)
682 << MacroName << Known->second.first << Existing.first;
683 }
684 return true;
685 }
686
687 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000688 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000689 if (Diags) {
690 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
691 }
692 return true;
693 }
694
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000695 // Detailed record is important since it is used for the module cache hash.
696 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000697 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000698 if (Diags) {
699 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
700 }
701 return true;
702 }
703
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 // Compute the #include and #include_macros lines we need.
Vedant Kumar48b4f762018-04-14 01:40:48 +0000705 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
706 StringRef File = ExistingPPOpts.Includes[I];
Erich Keane76675de2018-07-05 17:22:13 +0000707
708 if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
709 !ExistingPPOpts.PCHThroughHeader.empty()) {
710 // In case the through header is an include, we must add all the includes
711 // to the predefines so the start point can be determined.
712 SuggestedPredefines += "#include \"";
713 SuggestedPredefines += File;
714 SuggestedPredefines += "\"\n";
715 continue;
716 }
717
Guy Benyei11169dd2012-12-18 14:30:41 +0000718 if (File == ExistingPPOpts.ImplicitPCHInclude)
719 continue;
720
721 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
722 != PPOpts.Includes.end())
723 continue;
724
725 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000726 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000727 SuggestedPredefines += "\"\n";
728 }
729
Vedant Kumar48b4f762018-04-14 01:40:48 +0000730 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
731 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
733 File)
734 != PPOpts.MacroIncludes.end())
735 continue;
736
737 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000738 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 SuggestedPredefines += "\"\n##\n";
740 }
741
742 return false;
743}
744
745bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
746 bool Complain,
747 std::string &SuggestedPredefines) {
748 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
749
750 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000751 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000752 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000753 SuggestedPredefines,
754 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000755}
756
Yaxun Liu43712e02016-09-07 18:40:20 +0000757bool SimpleASTReaderListener::ReadPreprocessorOptions(
758 const PreprocessorOptions &PPOpts,
759 bool Complain,
760 std::string &SuggestedPredefines) {
761 return checkPreprocessorOptions(PPOpts,
762 PP.getPreprocessorOpts(),
763 nullptr,
764 PP.getFileManager(),
765 SuggestedPredefines,
766 PP.getLangOpts(),
767 false);
768}
769
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000770/// Check the header search options deserialized from the control block
771/// against the header search options in an existing preprocessor.
772///
773/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
774static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
775 StringRef SpecificModuleCachePath,
776 StringRef ExistingModuleCachePath,
777 DiagnosticsEngine *Diags,
778 const LangOptions &LangOpts) {
779 if (LangOpts.Modules) {
780 if (SpecificModuleCachePath != ExistingModuleCachePath) {
781 if (Diags)
782 Diags->Report(diag::err_pch_modulecache_mismatch)
783 << SpecificModuleCachePath << ExistingModuleCachePath;
784 return true;
785 }
786 }
787
788 return false;
789}
790
791bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
792 StringRef SpecificModuleCachePath,
793 bool Complain) {
794 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
795 PP.getHeaderSearchInfo().getModuleCachePath(),
796 Complain ? &Reader.Diags : nullptr,
797 PP.getLangOpts());
798}
799
Guy Benyei11169dd2012-12-18 14:30:41 +0000800void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
801 PP.setCounterValue(Value);
802}
803
804//===----------------------------------------------------------------------===//
805// AST reader implementation
806//===----------------------------------------------------------------------===//
807
Nico Weber824285e2014-05-08 04:26:47 +0000808void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
809 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000810 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000811 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000812}
813
Guy Benyei11169dd2012-12-18 14:30:41 +0000814unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
815 return serialization::ComputeHash(Sel);
816}
817
Guy Benyei11169dd2012-12-18 14:30:41 +0000818std::pair<unsigned, unsigned>
819ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000820 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000821
Justin Bogner57ba0b22014-03-28 22:03:24 +0000822 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
823 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 return std::make_pair(KeyLen, DataLen);
825}
826
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000827ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000828ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000829 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000830
Guy Benyei11169dd2012-12-18 14:30:41 +0000831 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
833 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
834 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000835 if (N == 0)
836 return SelTable.getNullarySelector(FirstII);
837 else if (N == 1)
838 return SelTable.getUnarySelector(FirstII);
839
840 SmallVector<IdentifierInfo *, 16> Args;
841 Args.push_back(FirstII);
842 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000843 Args.push_back(Reader.getLocalIdentifier(
844 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000845
846 return SelTable.getSelector(N, Args.data());
847}
848
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000849ASTSelectorLookupTrait::data_type
850ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000851 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000852 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000853
854 data_type Result;
855
Justin Bogner57ba0b22014-03-28 22:03:24 +0000856 Result.ID = Reader.getGlobalSelectorID(
857 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000858 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
859 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
860 Result.InstanceBits = FullInstanceBits & 0x3;
861 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
862 Result.FactoryBits = FullFactoryBits & 0x3;
863 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
864 unsigned NumInstanceMethods = FullInstanceBits >> 3;
865 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000866
867 // Load instance methods
868 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000869 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000870 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000871 Result.Instance.push_back(Method);
872 }
873
874 // Load factory methods
875 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000876 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000877 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000878 Result.Factory.push_back(Method);
879 }
880
881 return Result;
882}
883
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000884unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000885 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000886}
887
888std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000890 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000891
Justin Bogner57ba0b22014-03-28 22:03:24 +0000892 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
893 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000894 return std::make_pair(KeyLen, DataLen);
895}
896
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000897ASTIdentifierLookupTraitBase::internal_key_type
898ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000900 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000901}
902
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000903/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000904static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
905 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000906 return II.hadMacroDefinition() ||
907 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000908 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000909 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000910 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Bruno Ricci366ba732018-09-21 12:53:22 +0000911 II.getFETokenInfo());
Douglas Gregordcf25082013-02-11 18:16:18 +0000912}
913
Richard Smith76c2f2c2015-07-17 20:09:43 +0000914static bool readBit(unsigned &Bits) {
915 bool Value = Bits & 0x1;
916 Bits >>= 1;
917 return Value;
918}
919
Richard Smith79bf9202015-08-24 03:33:22 +0000920IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
921 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000922
Richard Smith79bf9202015-08-24 03:33:22 +0000923 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
924 return Reader.getGlobalIdentifierID(F, RawID >> 1);
925}
926
Richard Smitheb4b58f62016-02-05 01:40:54 +0000927static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
928 if (!II.isFromAST()) {
929 II.setIsFromAST();
930 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
931 if (isInterestingIdentifier(Reader, II, IsModule))
932 II.setChangedSinceDeserialization();
933 }
934}
935
Guy Benyei11169dd2012-12-18 14:30:41 +0000936IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
937 const unsigned char* d,
938 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000939 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000940
Justin Bogner57ba0b22014-03-28 22:03:24 +0000941 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000942 bool IsInteresting = RawID & 0x01;
943
944 // Wipe out the "is interesting" bit.
945 RawID = RawID >> 1;
946
Richard Smith76c2f2c2015-07-17 20:09:43 +0000947 // Build the IdentifierInfo and link the identifier ID with it.
948 IdentifierInfo *II = KnownII;
949 if (!II) {
950 II = &Reader.getIdentifierTable().getOwn(k);
951 KnownII = II;
952 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000953 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000954 Reader.markIdentifierUpToDate(II);
955
Guy Benyei11169dd2012-12-18 14:30:41 +0000956 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
957 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000958 // For uninteresting identifiers, there's nothing else to do. Just notify
959 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000960 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961 return II;
962 }
963
Justin Bogner57ba0b22014-03-28 22:03:24 +0000964 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
965 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000966 bool CPlusPlusOperatorKeyword = readBit(Bits);
967 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000968 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000969 bool Poisoned = readBit(Bits);
970 bool ExtensionToken = readBit(Bits);
971 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972
973 assert(Bits == 0 && "Extra bits in the identifier?");
974 DataLen -= 8;
975
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 // Set or check the various bits in the IdentifierInfo structure.
977 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000978 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000979 II->revertTokenIDToIdentifier();
980 if (!F.isModule())
981 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
982 else if (HasRevertedBuiltin && II->getBuiltinID()) {
983 II->revertBuiltin();
984 assert((II->hasRevertedBuiltin() ||
985 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
986 "Incorrect ObjC keyword or builtin ID");
987 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 assert(II->isExtensionToken() == ExtensionToken &&
989 "Incorrect extension token flag");
990 (void)ExtensionToken;
991 if (Poisoned)
992 II->setIsPoisoned(true);
993 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
994 "Incorrect C++ operator keyword flag");
995 (void)CPlusPlusOperatorKeyword;
996
997 // If this identifier is a macro, deserialize the macro
998 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000999 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001000 uint32_t MacroDirectivesOffset =
1001 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001002 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001003
Richard Smithd7329392015-04-21 21:46:32 +00001004 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 }
1006
1007 Reader.SetIdentifierInfo(ID, II);
1008
1009 // Read all of the declarations visible at global scope with this
1010 // name.
1011 if (DataLen > 0) {
1012 SmallVector<uint32_t, 4> DeclIDs;
1013 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 DeclIDs.push_back(Reader.getGlobalDeclID(
1015 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1017 }
1018
1019 return II;
1020}
1021
Richard Smitha06c7e62015-08-26 23:55:49 +00001022DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1023 : Kind(Name.getNameKind()) {
1024 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001026 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 break;
1028 case DeclarationName::ObjCZeroArgSelector:
1029 case DeclarationName::ObjCOneArgSelector:
1030 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001034 Data = Name.getCXXOverloadedOperator();
1035 break;
1036 case DeclarationName::CXXLiteralOperatorName:
1037 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1038 break;
Richard Smith35845152017-02-07 01:37:30 +00001039 case DeclarationName::CXXDeductionGuideName:
1040 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1041 ->getDeclName().getAsIdentifierInfo();
1042 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001043 case DeclarationName::CXXConstructorName:
1044 case DeclarationName::CXXDestructorName:
1045 case DeclarationName::CXXConversionFunctionName:
1046 case DeclarationName::CXXUsingDirective:
1047 Data = 0;
1048 break;
1049 }
1050}
1051
1052unsigned DeclarationNameKey::getHash() const {
1053 llvm::FoldingSetNodeID ID;
1054 ID.AddInteger(Kind);
1055
1056 switch (Kind) {
1057 case DeclarationName::Identifier:
1058 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001059 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001060 ID.AddString(((IdentifierInfo*)Data)->getName());
1061 break;
1062 case DeclarationName::ObjCZeroArgSelector:
1063 case DeclarationName::ObjCOneArgSelector:
1064 case DeclarationName::ObjCMultiArgSelector:
1065 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1066 break;
1067 case DeclarationName::CXXOperatorName:
1068 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 break;
1070 case DeclarationName::CXXConstructorName:
1071 case DeclarationName::CXXDestructorName:
1072 case DeclarationName::CXXConversionFunctionName:
1073 case DeclarationName::CXXUsingDirective:
1074 break;
1075 }
1076
1077 return ID.ComputeHash();
1078}
1079
Richard Smithd88a7f12015-09-01 20:35:42 +00001080ModuleFile *
1081ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1082 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001083
Richard Smithd88a7f12015-09-01 20:35:42 +00001084 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1085 return Reader.getLocalModuleFile(F, ModuleFileID);
1086}
1087
Guy Benyei11169dd2012-12-18 14:30:41 +00001088std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001089ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001090 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001091
Justin Bogner57ba0b22014-03-28 22:03:24 +00001092 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1093 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 return std::make_pair(KeyLen, DataLen);
1095}
1096
Richard Smitha06c7e62015-08-26 23:55:49 +00001097ASTDeclContextNameLookupTrait::internal_key_type
1098ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001099 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100
Vedant Kumar48b4f762018-04-14 01:40:48 +00001101 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001102 uint64_t Data;
1103 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001105 case DeclarationName::CXXLiteralOperatorName:
1106 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001107 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001108 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 break;
1110 case DeclarationName::ObjCZeroArgSelector:
1111 case DeclarationName::ObjCOneArgSelector:
1112 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001113 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001114 (uint64_t)Reader.getLocalSelector(
1115 F, endian::readNext<uint32_t, little, unaligned>(
1116 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 break;
1118 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001119 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 case DeclarationName::CXXConstructorName:
1122 case DeclarationName::CXXDestructorName:
1123 case DeclarationName::CXXConversionFunctionName:
1124 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001125 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001126 break;
1127 }
1128
Richard Smitha06c7e62015-08-26 23:55:49 +00001129 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001130}
1131
Richard Smithd88a7f12015-09-01 20:35:42 +00001132void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1133 const unsigned char *d,
1134 unsigned DataLen,
1135 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001136 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001137
Richard Smithd88a7f12015-09-01 20:35:42 +00001138 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1139 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1140 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1141 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001142}
1143
Richard Smith0f4e2c42015-08-06 04:23:48 +00001144bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1145 BitstreamCursor &Cursor,
1146 uint64_t Offset,
1147 DeclContext *DC) {
1148 assert(Offset != 0);
1149
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001151 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1152 Error(std::move(Err));
1153 return true;
1154 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001155
Richard Smith0f4e2c42015-08-06 04:23:48 +00001156 RecordData Record;
1157 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001158 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1159 if (!MaybeCode) {
1160 Error(MaybeCode.takeError());
1161 return true;
1162 }
1163 unsigned Code = MaybeCode.get();
1164
1165 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1166 if (!MaybeRecCode) {
1167 Error(MaybeRecCode.takeError());
1168 return true;
1169 }
1170 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001171 if (RecCode != DECL_CONTEXT_LEXICAL) {
1172 Error("Expected lexical block");
1173 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 }
1175
Richard Smith82f8fcd2015-08-06 22:07:25 +00001176 assert(!isa<TranslationUnitDecl>(DC) &&
1177 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001178 // If we are handling a C++ class template instantiation, we can see multiple
1179 // lexical updates for the same record. It's important that we select only one
1180 // of them, so that field numbering works properly. Just pick the first one we
1181 // see.
1182 auto &Lex = LexicalDecls[DC];
1183 if (!Lex.first) {
1184 Lex = std::make_pair(
1185 &M, llvm::makeArrayRef(
1186 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1187 Blob.data()),
1188 Blob.size() / 4));
1189 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001190 DC->setHasExternalLexicalStorage(true);
1191 return false;
1192}
Guy Benyei11169dd2012-12-18 14:30:41 +00001193
Richard Smith0f4e2c42015-08-06 04:23:48 +00001194bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1195 BitstreamCursor &Cursor,
1196 uint64_t Offset,
1197 DeclID ID) {
1198 assert(Offset != 0);
1199
1200 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00001201 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1202 Error(std::move(Err));
1203 return true;
1204 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001205
1206 RecordData Record;
1207 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001208 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1209 if (!MaybeCode) {
1210 Error(MaybeCode.takeError());
1211 return true;
1212 }
1213 unsigned Code = MaybeCode.get();
1214
1215 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
1216 if (!MaybeRecCode) {
1217 Error(MaybeRecCode.takeError());
1218 return true;
1219 }
1220 unsigned RecCode = MaybeRecCode.get();
Richard Smith0f4e2c42015-08-06 04:23:48 +00001221 if (RecCode != DECL_CONTEXT_VISIBLE) {
1222 Error("Expected visible lookup table block");
1223 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 }
1225
Richard Smith0f4e2c42015-08-06 04:23:48 +00001226 // We can't safely determine the primary context yet, so delay attaching the
1227 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001228 auto *Data = (const unsigned char*)Blob.data();
1229 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 return false;
1231}
1232
Richard Smith37a93df2017-02-18 00:32:02 +00001233void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001234 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001235 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001236 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001237 Diag(diag::note_module_cache_path)
1238 << PP.getHeaderSearchInfo().getModuleCachePath();
1239 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001240}
1241
1242void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001243 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 if (Diags.isDiagnosticInFlight())
1245 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1246 else
1247 Diag(DiagID) << Arg1 << Arg2;
1248}
1249
JF Bastien0e828952019-06-26 19:50:12 +00001250void ASTReader::Error(llvm::Error &&Err) const {
1251 Error(toString(std::move(Err)));
1252}
1253
Guy Benyei11169dd2012-12-18 14:30:41 +00001254//===----------------------------------------------------------------------===//
1255// Source Manager Deserialization
1256//===----------------------------------------------------------------------===//
1257
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001258/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001259/// \returns true if there was an error.
1260bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001261 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001262 unsigned Idx = 0;
1263 LineTableInfo &LineTable = SourceMgr.getLineTable();
1264
1265 // Parse the file names
1266 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001267 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001268 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001270 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001271 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1272 }
Richard Smith63078492015-09-01 07:41:55 +00001273 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001274
1275 // Parse the line entries
1276 std::vector<LineEntry> Entries;
1277 while (Idx < Record.size()) {
1278 int FID = Record[Idx++];
1279 assert(FID >= 0 && "Serialized line entries for non-local file.");
1280 // Remap FileID from 1-based old view.
1281 FID += F.SLocEntryBaseID - 1;
1282
1283 // Extract the line entries
1284 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001285 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001286 Entries.clear();
1287 Entries.reserve(NumEntries);
1288 for (unsigned I = 0; I != NumEntries; ++I) {
1289 unsigned FileOffset = Record[Idx++];
1290 unsigned LineNo = Record[Idx++];
1291 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001292 SrcMgr::CharacteristicKind FileKind
1293 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 unsigned IncludeOffset = Record[Idx++];
1295 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1296 FileKind, IncludeOffset));
1297 }
1298 LineTable.AddEntry(FileID::get(FID), Entries);
1299 }
1300
1301 return false;
1302}
1303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001304/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001305bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1306 using namespace SrcMgr;
1307
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001308 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001309
1310 // Set the source-location entry cursor to the current position in
1311 // the stream. This cursor will be used to read the contents of the
1312 // source manager block initially, and then lazily read
1313 // source-location entries as needed.
1314 SLocEntryCursor = F.Stream;
1315
1316 // The stream itself is going to skip over the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001317 if (llvm::Error Err = F.Stream.SkipBlock()) {
1318 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001319 return true;
1320 }
1321
1322 // Enter the source manager block.
JF Bastien0e828952019-06-26 19:50:12 +00001323 if (llvm::Error Err =
1324 SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1325 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00001326 return true;
1327 }
1328
1329 RecordData Record;
1330 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001331 Expected<llvm::BitstreamEntry> MaybeE =
1332 SLocEntryCursor.advanceSkippingSubblocks();
1333 if (!MaybeE) {
1334 Error(MaybeE.takeError());
1335 return true;
1336 }
1337 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001338
Chris Lattnere7b154b2013-01-19 21:39:22 +00001339 switch (E.Kind) {
1340 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1341 case llvm::BitstreamEntry::Error:
1342 Error("malformed block record in AST file");
1343 return true;
1344 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001345 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001346 case llvm::BitstreamEntry::Record:
1347 // The interesting case.
1348 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001349 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001350
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001353 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001354 Expected<unsigned> MaybeRecord =
1355 SLocEntryCursor.readRecord(E.ID, Record, &Blob);
1356 if (!MaybeRecord) {
1357 Error(MaybeRecord.takeError());
1358 return true;
1359 }
1360 switch (MaybeRecord.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 default: // Default behavior: ignore.
1362 break;
1363
1364 case SM_SLOC_FILE_ENTRY:
1365 case SM_SLOC_BUFFER_ENTRY:
1366 case SM_SLOC_EXPANSION_ENTRY:
1367 // Once we hit one of the source location entries, we're done.
1368 return false;
1369 }
1370 }
1371}
1372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001373/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001374/// and the PCH file was moved from its original location, try to resolve the
1375/// file by assuming that header+PCH were moved together and the header is in
1376/// the same place relative to the PCH.
1377static std::string
1378resolveFileRelativeToOriginalDir(const std::string &Filename,
1379 const std::string &OriginalDir,
1380 const std::string &CurrDir) {
1381 assert(OriginalDir != CurrDir &&
1382 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001383
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001385
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 SmallString<128> filePath(Filename);
1387 fs::make_absolute(filePath);
1388 assert(path::is_absolute(OriginalDir));
1389 SmallString<128> currPCHPath(CurrDir);
1390
1391 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1392 fileDirE = path::end(path::parent_path(filePath));
1393 path::const_iterator origDirI = path::begin(OriginalDir),
1394 origDirE = path::end(OriginalDir);
1395 // Skip the common path components from filePath and OriginalDir.
1396 while (fileDirI != fileDirE && origDirI != origDirE &&
1397 *fileDirI == *origDirI) {
1398 ++fileDirI;
1399 ++origDirI;
1400 }
1401 for (; origDirI != origDirE; ++origDirI)
1402 path::append(currPCHPath, "..");
1403 path::append(currPCHPath, fileDirI, fileDirE);
1404 path::append(currPCHPath, path::filename(Filename));
1405 return currPCHPath.str();
1406}
1407
1408bool ASTReader::ReadSLocEntry(int ID) {
1409 if (ID == 0)
1410 return false;
1411
1412 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1413 Error("source location entry ID out-of-range for AST file");
1414 return true;
1415 }
1416
Richard Smithaada85c2016-02-06 02:06:43 +00001417 // Local helper to read the (possibly-compressed) buffer data following the
1418 // entry record.
1419 auto ReadBuffer = [this](
1420 BitstreamCursor &SLocEntryCursor,
1421 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1422 RecordData Record;
1423 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001424 Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
1425 if (!MaybeCode) {
1426 Error(MaybeCode.takeError());
1427 return nullptr;
1428 }
1429 unsigned Code = MaybeCode.get();
1430
1431 Expected<unsigned> MaybeRecCode =
1432 SLocEntryCursor.readRecord(Code, Record, &Blob);
1433 if (!MaybeRecCode) {
1434 Error(MaybeRecCode.takeError());
1435 return nullptr;
1436 }
1437 unsigned RecCode = MaybeRecCode.get();
Richard Smithaada85c2016-02-06 02:06:43 +00001438
1439 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001440 if (!llvm::zlib::isAvailable()) {
1441 Error("zlib is not available");
1442 return nullptr;
1443 }
Richard Smithaada85c2016-02-06 02:06:43 +00001444 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001445 if (llvm::Error E =
1446 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1447 Error("could not decompress embedded file contents: " +
1448 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001449 return nullptr;
1450 }
1451 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1452 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1453 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1454 } else {
1455 Error("AST record has invalid code");
1456 return nullptr;
1457 }
1458 };
1459
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
JF Bastien0e828952019-06-26 19:50:12 +00001461 if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
1462 F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
1463 Error(std::move(Err));
1464 return true;
1465 }
1466
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001467 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 unsigned BaseOffset = F->SLocEntryBaseOffset;
1469
1470 ++NumSLocEntriesRead;
JF Bastien0e828952019-06-26 19:50:12 +00001471 Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
1472 if (!MaybeEntry) {
1473 Error(MaybeEntry.takeError());
1474 return true;
1475 }
1476 llvm::BitstreamEntry Entry = MaybeEntry.get();
1477
Chris Lattnere7b154b2013-01-19 21:39:22 +00001478 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 Error("incorrectly-formatted source location entry in AST file");
1480 return true;
1481 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001482
Guy Benyei11169dd2012-12-18 14:30:41 +00001483 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001484 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00001485 Expected<unsigned> MaybeSLOC =
1486 SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
1487 if (!MaybeSLOC) {
1488 Error(MaybeSLOC.takeError());
1489 return true;
1490 }
1491 switch (MaybeSLOC.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 default:
1493 Error("incorrectly-formatted source location entry in AST file");
1494 return true;
1495
1496 case SM_SLOC_FILE_ENTRY: {
1497 // We will detect whether a file changed and return 'Failure' for it, but
1498 // we will also try to fail gracefully by setting up the SLocEntry.
1499 unsigned InputID = Record[4];
1500 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001501 const FileEntry *File = IF.getFile();
1502 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001503
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001504 // Note that we only check if a File was returned. If it was out-of-date
1505 // we have complained but we will continue creating a FileID to recover
1506 // gracefully.
1507 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 return true;
1509
1510 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1511 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1512 // This is the module's main file.
1513 IncludeLoc = getImportLocation(F);
1514 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001515 SrcMgr::CharacteristicKind
1516 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Alex Lorenz4dc55732019-08-22 18:15:50 +00001517 // FIXME: The FileID should be created from the FileEntryRef.
Guy Benyei11169dd2012-12-18 14:30:41 +00001518 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1519 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001520 SrcMgr::FileInfo &FileInfo =
1521 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 FileInfo.NumCreatedFIDs = Record[5];
1523 if (Record[3])
1524 FileInfo.setHasLineDirectives();
1525
1526 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1527 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001528 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1530 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1531 NumFileDecls));
1532 }
Richard Smithaada85c2016-02-06 02:06:43 +00001533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001535 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001537 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1538 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001539 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1540 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001542 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 }
1544
1545 break;
1546 }
1547
1548 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001549 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001551 SrcMgr::CharacteristicKind
1552 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001554 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 IncludeLoc = getImportLocation(F);
1556 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001557
Richard Smithaada85c2016-02-06 02:06:43 +00001558 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1559 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001561 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001562 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 break;
1564 }
1565
1566 case SM_SLOC_EXPANSION_ENTRY: {
1567 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1568 SourceMgr.createExpansionLoc(SpellingLoc,
1569 ReadSourceLocation(*F, Record[2]),
1570 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001571 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001572 Record[4],
1573 ID,
1574 BaseOffset + Record[0]);
1575 break;
1576 }
1577 }
1578
1579 return false;
1580}
1581
1582std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1583 if (ID == 0)
1584 return std::make_pair(SourceLocation(), "");
1585
1586 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1587 Error("source location entry ID out-of-range for AST file");
1588 return std::make_pair(SourceLocation(), "");
1589 }
1590
1591 // Find which module file this entry lands in.
1592 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001593 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001594 return std::make_pair(SourceLocation(), "");
1595
1596 // FIXME: Can we map this down to a particular submodule? That would be
1597 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001598 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001599}
1600
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001601/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001602SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1603 if (F->ImportLoc.isValid())
1604 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001605
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 // Otherwise we have a PCH. It's considered to be "imported" at the first
1607 // location of its includer.
1608 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001609 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001610 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001611 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001613 return F->ImportedBy[0]->FirstLoc;
1614}
1615
JF Bastien0e828952019-06-26 19:50:12 +00001616/// Enter a subblock of the specified BlockID with the specified cursor. Read
1617/// the abbreviations that are at the top of the block and then leave the cursor
1618/// pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001619bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00001620 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
1621 // FIXME this drops errors on the floor.
1622 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00001623 return true;
JF Bastien0e828952019-06-26 19:50:12 +00001624 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001625
1626 while (true) {
1627 uint64_t Offset = Cursor.GetCurrentBitNo();
JF Bastien0e828952019-06-26 19:50:12 +00001628 Expected<unsigned> MaybeCode = Cursor.ReadCode();
1629 if (!MaybeCode) {
1630 // FIXME this drops errors on the floor.
1631 consumeError(MaybeCode.takeError());
1632 return true;
1633 }
1634 unsigned Code = MaybeCode.get();
Guy Benyei11169dd2012-12-18 14:30:41 +00001635
1636 // We expect all abbrevs to be at the start of the block.
1637 if (Code != llvm::bitc::DEFINE_ABBREV) {
JF Bastien0e828952019-06-26 19:50:12 +00001638 if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
1639 // FIXME this drops errors on the floor.
1640 consumeError(std::move(Err));
1641 return true;
1642 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 return false;
1644 }
JF Bastien0e828952019-06-26 19:50:12 +00001645 if (llvm::Error Err = Cursor.ReadAbbrevRecord()) {
1646 // FIXME this drops errors on the floor.
1647 consumeError(std::move(Err));
1648 return true;
1649 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 }
1651}
1652
Richard Smithe40f2ba2013-08-07 21:41:30 +00001653Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001654 unsigned &Idx) {
1655 Token Tok;
1656 Tok.startToken();
1657 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1658 Tok.setLength(Record[Idx++]);
1659 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1660 Tok.setIdentifierInfo(II);
1661 Tok.setKind((tok::TokenKind)Record[Idx++]);
1662 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1663 return Tok;
1664}
1665
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001666MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001667 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001668
1669 // Keep track of where we are in the stream, then jump back there
1670 // after reading this macro.
1671 SavedStreamPosition SavedPosition(Stream);
1672
JF Bastien0e828952019-06-26 19:50:12 +00001673 if (llvm::Error Err = Stream.JumpToBit(Offset)) {
1674 // FIXME this drops errors on the floor.
1675 consumeError(std::move(Err));
1676 return nullptr;
1677 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001678 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001679 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001680 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001681
Guy Benyei11169dd2012-12-18 14:30:41 +00001682 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001683 // Advance to the next record, but if we get to the end of the block, don't
1684 // pop it (removing all the abbreviations from the cursor) since we want to
1685 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001686 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
JF Bastien0e828952019-06-26 19:50:12 +00001687 Expected<llvm::BitstreamEntry> MaybeEntry =
1688 Stream.advanceSkippingSubblocks(Flags);
1689 if (!MaybeEntry) {
1690 Error(MaybeEntry.takeError());
1691 return Macro;
1692 }
1693 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001694
Chris Lattnerefa77172013-01-20 00:00:22 +00001695 switch (Entry.Kind) {
1696 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1697 case llvm::BitstreamEntry::Error:
1698 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001699 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001700 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001701 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001702 case llvm::BitstreamEntry::Record:
1703 // The interesting case.
1704 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 }
1706
1707 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001709 PreprocessorRecordTypes RecType;
1710 if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
1711 RecType = (PreprocessorRecordTypes)MaybeRecType.get();
1712 else {
1713 Error(MaybeRecType.takeError());
1714 return Macro;
1715 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001717 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001718 case PP_MACRO_DIRECTIVE_HISTORY:
1719 return Macro;
1720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 case PP_MACRO_OBJECT_LIKE:
1722 case PP_MACRO_FUNCTION_LIKE: {
1723 // If we already have a macro, that means that we've hit the end
1724 // of the definition of the macro we were looking for. We're
1725 // done.
1726 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001727 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001728
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001729 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001731 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001732 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001733 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001734 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001735
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1737 // Decode function-like macro info.
1738 bool isC99VarArgs = Record[NextIndex++];
1739 bool isGNUVarArgs = Record[NextIndex++];
1740 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001741 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001742 unsigned NumArgs = Record[NextIndex++];
1743 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001744 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001745
1746 // Install function-like macro info.
1747 MI->setIsFunctionLike();
1748 if (isC99VarArgs) MI->setIsC99Varargs();
1749 if (isGNUVarArgs) MI->setIsGNUVarargs();
1750 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001751 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 }
1753
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 // Remember that we saw this macro last so that we add the tokens that
1755 // form its body to it.
1756 Macro = MI;
1757
1758 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1759 Record[NextIndex]) {
1760 // We have a macro definition. Register the association
1761 PreprocessedEntityID
1762 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1763 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001764 PreprocessingRecord::PPEntityID PPID =
1765 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001766 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001767 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001768 if (PPDef)
1769 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001770 }
1771
1772 ++NumMacrosRead;
1773 break;
1774 }
1775
1776 case PP_TOKEN: {
1777 // If we see a TOKEN before a PP_MACRO_*, then the file is
1778 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001779 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001780
John McCallf413f5e2013-05-03 00:10:13 +00001781 unsigned Idx = 0;
1782 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001783 Macro->AddTokenToBody(Tok);
1784 break;
1785 }
1786 }
1787 }
1788}
1789
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001790PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001791ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1792 unsigned LocalID) const {
1793 if (!M.ModuleOffsetMap.empty())
1794 ReadModuleOffsetMap(M);
1795
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001796 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001798 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001800
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 return LocalID + I->second;
1802}
1803
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001804unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1805 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001806}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001807
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001808HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001809HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001810 internal_key_type ikey = {FE->getSize(),
1811 M.HasTimestamps ? FE->getModificationTime() : 0,
1812 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001813 return ikey;
1814}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001815
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001816bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001817 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 return false;
1819
Mehdi Amini004b9c72016-10-10 22:52:47 +00001820 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001821 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001822
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001824 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001825 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
Harlan Haskins8d323d12019-08-01 21:31:56 +00001826 if (!Key.Imported) {
1827 if (auto File = FileMgr.getFile(Key.Filename))
1828 return *File;
1829 return nullptr;
1830 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00001831
1832 std::string Resolved = Key.Filename;
1833 Reader.ResolveImportedPath(M, Resolved);
Harlan Haskins8d323d12019-08-01 21:31:56 +00001834 if (auto File = FileMgr.getFile(Resolved))
1835 return *File;
1836 return nullptr;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001837 };
1838
1839 const FileEntry *FEA = GetFile(a);
1840 const FileEntry *FEB = GetFile(b);
1841 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001842}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001843
Guy Benyei11169dd2012-12-18 14:30:41 +00001844std::pair<unsigned, unsigned>
1845HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001846 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001847
Vedant Kumar48b4f762018-04-14 01:40:48 +00001848 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1849 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001850 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001851}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001852
1853HeaderFileInfoTrait::internal_key_type
1854HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001855 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001856
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001857 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001858 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1859 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001860 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001861 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001862 return ikey;
1863}
1864
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001865HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001866HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001868 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001869
1870 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001871 HeaderFileInfo HFI;
1872 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001873 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001874 HFI.isImport |= (Flags >> 5) & 0x01;
1875 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1876 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001877 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001878 // FIXME: Find a better way to handle this. Maybe just store a
1879 // "has been included" flag?
1880 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1881 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001882 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1883 M, endian::readNext<uint32_t, little, unaligned>(d));
1884 if (unsigned FrameworkOffset =
1885 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001886 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 // since 0 is used as an indicator for "no framework name".
1888 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1889 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1890 }
Richard Smith386bb072015-08-18 23:42:23 +00001891
1892 assert((End - d) % 4 == 0 &&
1893 "Wrong data length in HeaderFileInfo deserialization");
1894 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001895 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001896 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1897 LocalSMID >>= 2;
1898
1899 // This header is part of a module. Associate it with the module to enable
1900 // implicit module import.
1901 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1902 Module *Mod = Reader.getSubmodule(GlobalSMID);
1903 FileManager &FileMgr = Reader.getFileManager();
1904 ModuleMap &ModMap =
1905 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1906
1907 std::string Filename = key.Filename;
1908 if (key.Imported)
1909 Reader.ResolveImportedPath(M, Filename);
1910 // FIXME: This is not always the right filename-as-written, but we're not
1911 // going to use this information to rebuild the module, so it doesn't make
1912 // a lot of difference.
Harlan Haskins8d323d12019-08-01 21:31:56 +00001913 Module::Header H = { key.Filename, *FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001914 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1915 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001916 }
1917
Guy Benyei11169dd2012-12-18 14:30:41 +00001918 // This HeaderFileInfo was externally loaded.
1919 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001920 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 return HFI;
1922}
1923
Richard Smithd7329392015-04-21 21:46:32 +00001924void ASTReader::addPendingMacro(IdentifierInfo *II,
1925 ModuleFile *M,
1926 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001927 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1928 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001929}
1930
1931void ASTReader::ReadDefinedMacros() {
1932 // Note that we are loading defined macros.
1933 Deserializing Macros(this);
1934
Vedant Kumar48b4f762018-04-14 01:40:48 +00001935 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001936 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001937
1938 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001939 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001940 continue;
1941
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001942 BitstreamCursor Cursor = MacroCursor;
JF Bastien0e828952019-06-26 19:50:12 +00001943 if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
1944 Error(std::move(Err));
1945 return;
1946 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001947
1948 RecordData Record;
1949 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00001950 Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
1951 if (!MaybeE) {
1952 Error(MaybeE.takeError());
1953 return;
1954 }
1955 llvm::BitstreamEntry E = MaybeE.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001956
Chris Lattnere7b154b2013-01-19 21:39:22 +00001957 switch (E.Kind) {
1958 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1959 case llvm::BitstreamEntry::Error:
1960 Error("malformed block record in AST file");
1961 return;
1962 case llvm::BitstreamEntry::EndBlock:
1963 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001964
JF Bastien0e828952019-06-26 19:50:12 +00001965 case llvm::BitstreamEntry::Record: {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001966 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00001967 Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
1968 if (!MaybeRecord) {
1969 Error(MaybeRecord.takeError());
1970 return;
1971 }
1972 switch (MaybeRecord.get()) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001973 default: // Default behavior: ignore.
1974 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001975
Chris Lattnere7b154b2013-01-19 21:39:22 +00001976 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001977 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001978 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001979 if (II->isOutOfDate())
1980 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001981 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001982 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001983
Chris Lattnere7b154b2013-01-19 21:39:22 +00001984 case PP_TOKEN:
1985 // Ignore tokens.
1986 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001988 break;
1989 }
JF Bastien0e828952019-06-26 19:50:12 +00001990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001991 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001992 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 }
1994}
1995
1996namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001997
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001998 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00001999 class IdentifierLookupVisitor {
2000 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00002001 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002003 unsigned &NumIdentifierLookups;
2004 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002005 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00002006
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00002008 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
2009 unsigned &NumIdentifierLookups,
2010 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00002011 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
2012 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00002013 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002014 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002015
2016 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002017 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00002018 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00002020
Vedant Kumar48b4f762018-04-14 01:40:48 +00002021 ASTIdentifierLookupTable *IdTable
2022 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002023 if (!IdTable)
2024 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002025
2026 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00002027 Found);
2028 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00002029 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00002030 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 if (Pos == IdTable->end())
2032 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002033
Guy Benyei11169dd2012-12-18 14:30:41 +00002034 // Dereferencing the iterator has the effect of building the
2035 // IdentifierInfo node and populating it with the various
2036 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00002037 ++NumIdentifierLookupHits;
2038 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 return true;
2040 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002042 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 // files.
2044 IdentifierInfo *getIdentifierInfo() const { return Found; }
2045 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002046
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002047} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00002048
2049void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
2050 // Note that we are loading an identifier.
2051 Deserializing AnIdentifier(this);
2052
2053 unsigned PriorGeneration = 0;
2054 if (getContext().getLangOpts().Modules)
2055 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00002056
2057 // If there is a global index, look there first to determine which modules
2058 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00002059 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00002060 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00002061 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00002062 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
2063 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00002064 }
2065 }
2066
Douglas Gregor7211ac12013-01-25 23:32:03 +00002067 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00002068 NumIdentifierLookups,
2069 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00002070 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002071 markIdentifierUpToDate(&II);
2072}
2073
2074void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
2075 if (!II)
2076 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002077
Guy Benyei11169dd2012-12-18 14:30:41 +00002078 II->setOutOfDate(false);
2079
2080 // Update the generation for this identifier.
2081 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00002082 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00002083}
2084
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002085void ASTReader::resolvePendingMacro(IdentifierInfo *II,
2086 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00002087 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002088
2089 BitstreamCursor &Cursor = M.MacroCursor;
2090 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002091 if (llvm::Error Err = Cursor.JumpToBit(PMInfo.MacroDirectivesOffset)) {
2092 Error(std::move(Err));
2093 return;
2094 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002095
Richard Smith713369b2015-04-23 20:40:50 +00002096 struct ModuleMacroRecord {
2097 SubmoduleID SubModID;
2098 MacroInfo *MI;
2099 SmallVector<SubmoduleID, 8> Overrides;
2100 };
2101 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002102
Richard Smithd7329392015-04-21 21:46:32 +00002103 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
2104 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
2105 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002106 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00002107 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002108 Expected<llvm::BitstreamEntry> MaybeEntry =
Richard Smithd7329392015-04-21 21:46:32 +00002109 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
JF Bastien0e828952019-06-26 19:50:12 +00002110 if (!MaybeEntry) {
2111 Error(MaybeEntry.takeError());
2112 return;
2113 }
2114 llvm::BitstreamEntry Entry = MaybeEntry.get();
2115
Richard Smithd7329392015-04-21 21:46:32 +00002116 if (Entry.Kind != llvm::BitstreamEntry::Record) {
2117 Error("malformed block record in AST file");
2118 return;
2119 }
2120
2121 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002122 Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
2123 if (!MaybePP) {
2124 Error(MaybePP.takeError());
2125 return;
2126 }
2127 switch ((PreprocessorRecordTypes)MaybePP.get()) {
Richard Smithd7329392015-04-21 21:46:32 +00002128 case PP_MACRO_DIRECTIVE_HISTORY:
2129 break;
2130
2131 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00002132 ModuleMacros.push_back(ModuleMacroRecord());
2133 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00002134 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
2135 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00002136 for (int I = 2, N = Record.size(); I != N; ++I)
2137 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00002138 continue;
2139 }
2140
2141 default:
2142 Error("malformed block record in AST file");
2143 return;
2144 }
2145
2146 // We found the macro directive history; that's the last record
2147 // for this macro.
2148 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002149 }
2150
Richard Smithd7329392015-04-21 21:46:32 +00002151 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002152 {
2153 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002154 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002155 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002156 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002157 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002158 Module *Mod = getSubmodule(ModID);
2159 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002160 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002161 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002162 }
2163
2164 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002165 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002166 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002167 }
2168 }
2169
2170 // Don't read the directive history for a module; we don't have anywhere
2171 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002172 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002173 return;
2174
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002175 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002176 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002177 unsigned Idx = 0, N = Record.size();
2178 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002179 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002180 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002181 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002182 switch (K) {
2183 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002184 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002185 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002186 break;
2187 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002188 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002189 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002190 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002191 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002192 bool isPublic = Record[Idx++];
2193 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2194 break;
2195 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002196
2197 if (!Latest)
2198 Latest = MD;
2199 if (Earliest)
2200 Earliest->setPrevious(MD);
2201 Earliest = MD;
2202 }
2203
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002204 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002205 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002206}
2207
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002208ASTReader::InputFileInfo
2209ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002210 // Go find this input file.
2211 BitstreamCursor &Cursor = F.InputFilesCursor;
2212 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002213 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2214 // FIXME this drops errors on the floor.
2215 consumeError(std::move(Err));
2216 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002217
JF Bastien0e828952019-06-26 19:50:12 +00002218 Expected<unsigned> MaybeCode = Cursor.ReadCode();
2219 if (!MaybeCode) {
2220 // FIXME this drops errors on the floor.
2221 consumeError(MaybeCode.takeError());
2222 }
2223 unsigned Code = MaybeCode.get();
Ben Langmuir198c1682014-03-07 07:27:49 +00002224 RecordData Record;
2225 StringRef Blob;
2226
JF Bastien0e828952019-06-26 19:50:12 +00002227 if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
2228 assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
2229 "invalid record type for input file");
2230 else {
2231 // FIXME this drops errors on the floor.
2232 consumeError(Maybe.takeError());
2233 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002234
2235 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002236 InputFileInfo R;
2237 R.StoredSize = static_cast<off_t>(Record[1]);
2238 R.StoredTime = static_cast<time_t>(Record[2]);
2239 R.Overridden = static_cast<bool>(Record[3]);
2240 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002241 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002242 R.Filename = Blob;
2243 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002244 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002245}
2246
Manman Renc8c94152016-10-21 23:35:03 +00002247static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002248InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 // If this ID is bogus, just return an empty input file.
2250 if (ID == 0 || ID > F.InputFilesLoaded.size())
2251 return InputFile();
2252
2253 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002254 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 return F.InputFilesLoaded[ID-1];
2256
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002257 if (F.InputFilesLoaded[ID-1].isNotFound())
2258 return InputFile();
2259
Guy Benyei11169dd2012-12-18 14:30:41 +00002260 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002261 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002262 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00002263 if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
2264 // FIXME this drops errors on the floor.
2265 consumeError(std::move(Err));
2266 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002267
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002268 InputFileInfo FI = readInputFileInfo(F, ID);
2269 off_t StoredSize = FI.StoredSize;
2270 time_t StoredTime = FI.StoredTime;
2271 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002272 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002273 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002274
Harlan Haskins8d323d12019-08-01 21:31:56 +00002275 const FileEntry *File = nullptr;
2276 if (auto FE = FileMgr.getFile(Filename, /*OpenFile=*/false))
2277 File = *FE;
2278
Ben Langmuir198c1682014-03-07 07:27:49 +00002279 // If we didn't find the file, resolve it relative to the
2280 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002281 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2282 F.OriginalDir != F.BaseDirectory) {
2283 std::string Resolved = resolveFileRelativeToOriginalDir(
2284 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002285 if (!Resolved.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00002286 if (auto FE = FileMgr.getFile(Resolved))
2287 File = *FE;
Ben Langmuir198c1682014-03-07 07:27:49 +00002288 }
2289
2290 // For an overridden file, create a virtual file with the stored
2291 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002292 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002293 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002294
Craig Toppera13603a2014-05-22 05:54:18 +00002295 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002296 if (Complain) {
2297 std::string ErrorStr = "could not find file '";
2298 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002299 ErrorStr += "' referenced by AST file '";
2300 ErrorStr += F.FileName;
2301 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002302 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002303 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002304 // Record that we didn't find the file.
2305 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2306 return InputFile();
2307 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002308
Ben Langmuir198c1682014-03-07 07:27:49 +00002309 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002310 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002311 // can lead to problems when lexing using the source locations from the
2312 // PCH.
2313 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002314 // FIXME: Reject if the overrides are different.
2315 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002316 if (Complain)
2317 Error(diag::err_fe_pch_file_overridden, Filename);
Duncan P. N. Exon Smithe1b7f222019-08-30 22:59:25 +00002318
2319 // After emitting the diagnostic, bypass the overriding file to recover
2320 // (this creates a separate FileEntry).
2321 File = SM.bypassFileContentsOverride(*File);
2322 if (!File) {
2323 F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
2324 return InputFile();
2325 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002326 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002327
Ben Langmuir198c1682014-03-07 07:27:49 +00002328 bool IsOutOfDate = false;
2329
2330 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002331 if (!Overridden && //
2332 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002333 (StoredTime && StoredTime != File->getModificationTime() &&
2334 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002335 )) {
2336 if (Complain) {
2337 // Build a list of the PCH imports that got us here (in reverse).
2338 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002339 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002340 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002341
Ben Langmuir198c1682014-03-07 07:27:49 +00002342 // The top-level PCH is stale.
2343 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002344 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2345 if (DiagnosticKind == 0)
2346 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2347 else if (DiagnosticKind == 1)
2348 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2349 else
2350 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002351
Ben Langmuir198c1682014-03-07 07:27:49 +00002352 // Print the import stack.
2353 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2354 Diag(diag::note_pch_required_by)
2355 << Filename << ImportStack[0]->FileName;
2356 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002357 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002358 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002359 }
2360
Ben Langmuir198c1682014-03-07 07:27:49 +00002361 if (!Diags.isDiagnosticInFlight())
2362 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 }
2364
Ben Langmuir198c1682014-03-07 07:27:49 +00002365 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002367 // FIXME: If the file is overridden and we've already opened it,
2368 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002369
Richard Smitha8cfffa2015-11-26 02:04:16 +00002370 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002371
2372 // Note that we've loaded this input file.
2373 F.InputFilesLoaded[ID-1] = IF;
2374 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002375}
2376
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002377/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002378/// is not an absolute path, add the system or module root to the beginning of
2379/// the file name.
2380void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2381 // Resolve relative to the base directory, if we have one.
2382 if (!M.BaseDirectory.empty())
2383 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002384}
2385
Richard Smith7ed1bc92014-12-05 22:42:13 +00002386void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002387 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2388 return;
2389
Richard Smith7ed1bc92014-12-05 22:42:13 +00002390 SmallString<128> Buffer;
2391 llvm::sys::path::append(Buffer, Prefix, Filename);
2392 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002393}
2394
Richard Smith0f99d6a2015-08-09 08:48:41 +00002395static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2396 switch (ARR) {
2397 case ASTReader::Failure: return true;
2398 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2399 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2400 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2401 case ASTReader::ConfigurationMismatch:
2402 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2403 case ASTReader::HadErrors: return true;
2404 case ASTReader::Success: return false;
2405 }
2406
2407 llvm_unreachable("unknown ASTReadResult");
2408}
2409
Richard Smith0516b182015-09-08 19:40:14 +00002410ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2411 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2412 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002413 std::string &SuggestedPredefines) {
JF Bastien0e828952019-06-26 19:50:12 +00002414 if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
2415 // FIXME this drops errors on the floor.
2416 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002417 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00002418 }
Richard Smith0516b182015-09-08 19:40:14 +00002419
2420 // Read all of the records in the options block.
2421 RecordData Record;
2422 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002423 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002424 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2425 if (!MaybeEntry) {
2426 // FIXME this drops errors on the floor.
2427 consumeError(MaybeEntry.takeError());
2428 return Failure;
2429 }
2430 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002431
Richard Smith0516b182015-09-08 19:40:14 +00002432 switch (Entry.Kind) {
2433 case llvm::BitstreamEntry::Error:
2434 case llvm::BitstreamEntry::SubBlock:
2435 return Failure;
2436
2437 case llvm::BitstreamEntry::EndBlock:
2438 return Result;
2439
2440 case llvm::BitstreamEntry::Record:
2441 // The interesting case.
2442 break;
2443 }
2444
2445 // Read and process a record.
2446 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00002447 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
2448 if (!MaybeRecordType) {
2449 // FIXME this drops errors on the floor.
2450 consumeError(MaybeRecordType.takeError());
2451 return Failure;
2452 }
2453 switch ((OptionsRecordTypes)MaybeRecordType.get()) {
Richard Smith0516b182015-09-08 19:40:14 +00002454 case LANGUAGE_OPTIONS: {
2455 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2456 if (ParseLanguageOptions(Record, Complain, Listener,
2457 AllowCompatibleConfigurationMismatch))
2458 Result = ConfigurationMismatch;
2459 break;
2460 }
2461
2462 case TARGET_OPTIONS: {
2463 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2464 if (ParseTargetOptions(Record, Complain, Listener,
2465 AllowCompatibleConfigurationMismatch))
2466 Result = ConfigurationMismatch;
2467 break;
2468 }
2469
Richard Smith0516b182015-09-08 19:40:14 +00002470 case FILE_SYSTEM_OPTIONS: {
2471 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2472 if (!AllowCompatibleConfigurationMismatch &&
2473 ParseFileSystemOptions(Record, Complain, Listener))
2474 Result = ConfigurationMismatch;
2475 break;
2476 }
2477
2478 case HEADER_SEARCH_OPTIONS: {
2479 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2480 if (!AllowCompatibleConfigurationMismatch &&
2481 ParseHeaderSearchOptions(Record, Complain, Listener))
2482 Result = ConfigurationMismatch;
2483 break;
2484 }
2485
2486 case PREPROCESSOR_OPTIONS:
2487 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2488 if (!AllowCompatibleConfigurationMismatch &&
2489 ParsePreprocessorOptions(Record, Complain, Listener,
2490 SuggestedPredefines))
2491 Result = ConfigurationMismatch;
2492 break;
2493 }
2494 }
2495}
2496
Guy Benyei11169dd2012-12-18 14:30:41 +00002497ASTReader::ASTReadResult
2498ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002499 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002500 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002502 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002503 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002504
JF Bastien0e828952019-06-26 19:50:12 +00002505 if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2506 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 return Failure;
2508 }
2509
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002510 // Lambda to read the unhashed control block the first time it's called.
2511 //
2512 // For PCM files, the unhashed control block cannot be read until after the
2513 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2514 // need to look ahead before reading the IMPORTS record. For consistency,
2515 // this block is always read somehow (see BitstreamEntry::EndBlock).
2516 bool HasReadUnhashedControlBlock = false;
2517 auto readUnhashedControlBlockOnce = [&]() {
2518 if (!HasReadUnhashedControlBlock) {
2519 HasReadUnhashedControlBlock = true;
2520 if (ASTReadResult Result =
2521 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2522 return Result;
2523 }
2524 return Success;
2525 };
2526
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 // Read all of the records and blocks in the control block.
2528 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002529 unsigned NumInputs = 0;
2530 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002531 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002532 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002533 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2534 if (!MaybeEntry) {
2535 Error(MaybeEntry.takeError());
2536 return Failure;
2537 }
2538 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002539
Chris Lattnere7b154b2013-01-19 21:39:22 +00002540 switch (Entry.Kind) {
2541 case llvm::BitstreamEntry::Error:
2542 Error("malformed block record in AST file");
2543 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002544 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002545 // Validate the module before returning. This call catches an AST with
2546 // no module name and no imports.
2547 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2548 return Result;
2549
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002550 // Validate input files.
2551 const HeaderSearchOptions &HSOpts =
2552 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002553
Richard Smitha1825302014-10-23 22:18:29 +00002554 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002555 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2556 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002557 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2558 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002560
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002561 // If we are reading a module, we will create a verification timestamp,
2562 // so we verify all input files. Otherwise, verify only user input
2563 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002564
2565 unsigned N = NumUserInputs;
2566 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002567 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002568 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002569 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002570 N = NumInputs;
2571
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002572 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002573 InputFile IF = getInputFile(F, I+1, Complain);
2574 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002576 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002577 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002578
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002579 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002580 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002581
Ben Langmuircb69b572014-03-07 06:40:32 +00002582 if (Listener && Listener->needsInputFileVisitation()) {
2583 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2584 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002585 for (unsigned I = 0; I < N; ++I) {
2586 bool IsSystem = I >= NumUserInputs;
2587 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002588 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002589 F.Kind == MK_ExplicitModule ||
2590 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002591 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002592 }
2593
Richard Smith8a308ec2015-11-05 00:54:55 +00002594 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002595 }
2596
Chris Lattnere7b154b2013-01-19 21:39:22 +00002597 case llvm::BitstreamEntry::SubBlock:
2598 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 case INPUT_FILES_BLOCK_ID:
2600 F.InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002601 if (llvm::Error Err = Stream.SkipBlock()) {
2602 Error(std::move(Err));
2603 return Failure;
2604 }
2605 if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002606 Error("malformed block record in AST file");
2607 return Failure;
2608 }
2609 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002610
2611 case OPTIONS_BLOCK_ID:
2612 // If we're reading the first module for this group, check its options
2613 // are compatible with ours. For modules it imports, no further checking
2614 // is required, because we checked them when we built it.
2615 if (Listener && !ImportedBy) {
2616 // Should we allow the configuration of the module file to differ from
2617 // the configuration of the current translation unit in a compatible
2618 // way?
2619 //
2620 // FIXME: Allow this for files explicitly specified with -include-pch.
2621 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002622 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002623
Richard Smith8a308ec2015-11-05 00:54:55 +00002624 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2625 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002626 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002627 if (Result == Failure) {
2628 Error("malformed block record in AST file");
2629 return Result;
2630 }
2631
Richard Smith8a308ec2015-11-05 00:54:55 +00002632 if (DisableValidation ||
2633 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2634 Result = Success;
2635
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002636 // If we can't load the module, exit early since we likely
2637 // will rebuild the module anyway. The stream may be in the
2638 // middle of a block.
2639 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002640 return Result;
JF Bastien0e828952019-06-26 19:50:12 +00002641 } else if (llvm::Error Err = Stream.SkipBlock()) {
2642 Error(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00002643 return Failure;
2644 }
2645 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002646
Guy Benyei11169dd2012-12-18 14:30:41 +00002647 default:
JF Bastien0e828952019-06-26 19:50:12 +00002648 if (llvm::Error Err = Stream.SkipBlock()) {
2649 Error(std::move(Err));
Chris Lattnere7b154b2013-01-19 21:39:22 +00002650 return Failure;
2651 }
2652 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002654
Chris Lattnere7b154b2013-01-19 21:39:22 +00002655 case llvm::BitstreamEntry::Record:
2656 // The interesting case.
2657 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 }
2659
2660 // Read and process a record.
2661 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002662 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002663 Expected<unsigned> MaybeRecordType =
2664 Stream.readRecord(Entry.ID, Record, &Blob);
2665 if (!MaybeRecordType) {
2666 Error(MaybeRecordType.takeError());
2667 return Failure;
2668 }
2669 switch ((ControlRecordTypes)MaybeRecordType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 case METADATA: {
2671 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2672 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002673 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2674 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 return VersionMismatch;
2676 }
2677
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002678 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2680 Diag(diag::err_pch_with_compiler_errors);
2681 return HadErrors;
2682 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002683 if (hasErrors) {
2684 Diags.ErrorOccurred = true;
2685 Diags.UncompilableErrorOccurred = true;
2686 Diags.UnrecoverableErrorOccurred = true;
2687 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002688
2689 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002690 // Relative paths in a relocatable PCH are relative to our sysroot.
2691 if (F.RelocatablePCH)
2692 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002693
Richard Smithe75ee0f2015-08-17 07:13:32 +00002694 F.HasTimestamps = Record[5];
2695
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002696 F.PCHHasObjectFile = Record[6];
2697
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002699 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002700 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2701 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002702 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 return VersionMismatch;
2704 }
2705 break;
2706 }
2707
2708 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002709 // Validate the AST before processing any imports (otherwise, untangling
2710 // them can be error-prone and expensive). A module will have a name and
2711 // will already have been validated, but this catches the PCH case.
2712 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2713 return Result;
2714
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002715 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 unsigned Idx = 0, N = Record.size();
2717 while (Idx < N) {
2718 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002719 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 // The import location will be the local one for now; we will adjust
2721 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002722 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002724 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002725 off_t StoredSize = (off_t)Record[Idx++];
2726 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002727 ASTFileSignature StoredSignature = {
2728 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2729 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2730 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002731
2732 std::string ImportedName = ReadString(Record, Idx);
2733 std::string ImportedFile;
2734
2735 // For prebuilt and explicit modules first consult the file map for
2736 // an override. Note that here we don't search prebuilt module
2737 // directories, only the explicit name to file mappings. Also, we will
2738 // still verify the size/signature making sure it is essentially the
2739 // same file but perhaps in a different location.
2740 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2741 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2742 ImportedName, /*FileMapOnly*/ true);
2743
2744 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002745 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2746 // ModuleCache as when writing.
2747 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002748 else
2749 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002750
Richard Smith0f99d6a2015-08-09 08:48:41 +00002751 // If our client can't cope with us being out of date, we can't cope with
2752 // our dependency being missing.
2753 unsigned Capabilities = ClientLoadCapabilities;
2754 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2755 Capabilities &= ~ARR_Missing;
2756
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002758 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2759 Loaded, StoredSize, StoredModTime,
2760 StoredSignature, Capabilities);
2761
2762 // If we diagnosed a problem, produce a backtrace.
2763 if (isDiagnosedResult(Result, Capabilities))
2764 Diag(diag::note_module_file_imported_by)
2765 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2766
2767 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 case Failure: return Failure;
2769 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002770 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 case OutOfDate: return OutOfDate;
2772 case VersionMismatch: return VersionMismatch;
2773 case ConfigurationMismatch: return ConfigurationMismatch;
2774 case HadErrors: return HadErrors;
2775 case Success: break;
2776 }
2777 }
2778 break;
2779 }
2780
Guy Benyei11169dd2012-12-18 14:30:41 +00002781 case ORIGINAL_FILE:
2782 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002783 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002785 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 break;
2787
2788 case ORIGINAL_FILE_ID:
2789 F.OriginalSourceFileID = FileID::get(Record[0]);
2790 break;
2791
2792 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002793 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 break;
2795
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002796 case MODULE_NAME:
2797 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002798 Diag(diag::remark_module_import)
2799 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2800 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002801 if (Listener)
2802 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002803
2804 // Validate the AST as soon as we have a name so we can exit early on
2805 // failure.
2806 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2807 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002808
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002809 break;
2810
Richard Smith223d3f22014-12-06 03:21:08 +00002811 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002812 // Save the BaseDirectory as written in the PCM for computing the module
2813 // filename for the ModuleCache.
2814 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002815 assert(!F.ModuleName.empty() &&
2816 "MODULE_DIRECTORY found before MODULE_NAME");
2817 // If we've already loaded a module map file covering this module, we may
2818 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002819 Module *M = PP.getHeaderSearchInfo().lookupModule(
2820 F.ModuleName, /*AllowSearch*/ true,
2821 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002822 if (M && M->Directory) {
2823 // If we're implicitly loading a module, the base directory can't
2824 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002825 // Don't emit module relocation error if we have -fno-validate-pch
2826 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2827 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Harlan Haskins8d323d12019-08-01 21:31:56 +00002828 auto BuildDir = PP.getFileManager().getDirectory(Blob);
2829 if (!BuildDir || *BuildDir != M->Directory) {
Richard Smith223d3f22014-12-06 03:21:08 +00002830 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2831 Diag(diag::err_imported_module_relocated)
2832 << F.ModuleName << Blob << M->Directory->getName();
2833 return OutOfDate;
2834 }
2835 }
2836 F.BaseDirectory = M->Directory->getName();
2837 } else {
2838 F.BaseDirectory = Blob;
2839 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002840 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002841 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002842
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002843 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002844 if (ASTReadResult Result =
2845 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2846 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002847 break;
2848
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002849 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002850 NumInputs = Record[0];
2851 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002852 F.InputFileOffsets =
2853 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002854 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002855 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 break;
2857 }
2858 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002859}
2860
Ben Langmuir2c9af442014-04-10 17:57:43 +00002861ASTReader::ASTReadResult
2862ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002863 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002864
JF Bastien0e828952019-06-26 19:50:12 +00002865 if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID)) {
2866 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002867 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002868 }
2869
2870 // Read all of the records and blocks for the AST file.
2871 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002872 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00002873 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
2874 if (!MaybeEntry) {
2875 Error(MaybeEntry.takeError());
2876 return Failure;
2877 }
2878 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002879
Chris Lattnere7b154b2013-01-19 21:39:22 +00002880 switch (Entry.Kind) {
2881 case llvm::BitstreamEntry::Error:
2882 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002883 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002884 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002885 // Outside of C++, we do not store a lookup map for the translation unit.
2886 // Instead, mark it as needing a lookup map to be built if this module
2887 // contains any declarations lexically within it (which it always does!).
2888 // This usually has no cost, since we very rarely need the lookup map for
2889 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002890 if (ASTContext *Ctx = ContextObj) {
2891 DeclContext *DC = Ctx->getTranslationUnitDecl();
2892 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2893 DC->setMustBuildLookupTable();
2894 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002895
Ben Langmuir2c9af442014-04-10 17:57:43 +00002896 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002897 case llvm::BitstreamEntry::SubBlock:
2898 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 case DECLTYPES_BLOCK_ID:
2900 // We lazily load the decls block, but we want to set up the
2901 // DeclsCursor cursor to point into it. Clone our current bitcode
2902 // cursor to it, enter the block and read the abbrevs in that block.
2903 // With the main cursor, we just skip over it.
2904 F.DeclsCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002905 if (llvm::Error Err = Stream.SkipBlock()) {
2906 Error(std::move(Err));
2907 return Failure;
2908 }
2909 if (ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002911 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 }
2913 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002914
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 case PREPROCESSOR_BLOCK_ID:
2916 F.MacroCursor = Stream;
2917 if (!PP.getExternalSource())
2918 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002919
JF Bastien0e828952019-06-26 19:50:12 +00002920 if (llvm::Error Err = Stream.SkipBlock()) {
2921 Error(std::move(Err));
2922 return Failure;
2923 }
2924 if (ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002926 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 }
2928 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2929 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002930
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 case PREPROCESSOR_DETAIL_BLOCK_ID:
2932 F.PreprocessorDetailCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002933
2934 if (llvm::Error Err = Stream.SkipBlock()) {
2935 Error(std::move(Err));
2936 return Failure;
2937 }
2938 if (ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 PREPROCESSOR_DETAIL_BLOCK_ID)) {
JF Bastien0e828952019-06-26 19:50:12 +00002940 Error("malformed preprocessor detail record in AST file");
2941 return Failure;
2942 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002944 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002945
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 if (!PP.getPreprocessingRecord())
2947 PP.createPreprocessingRecord();
2948 if (!PP.getPreprocessingRecord()->getExternalSource())
2949 PP.getPreprocessingRecord()->SetExternalSource(*this);
2950 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002951
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 case SOURCE_MANAGER_BLOCK_ID:
2953 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002954 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002956
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002958 if (ASTReadResult Result =
2959 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002960 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002962
Guy Benyei11169dd2012-12-18 14:30:41 +00002963 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002964 BitstreamCursor C = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00002965
2966 if (llvm::Error Err = Stream.SkipBlock()) {
2967 Error(std::move(Err));
2968 return Failure;
2969 }
2970 if (ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002972 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 }
2974 CommentsCursors.push_back(std::make_pair(C, &F));
2975 break;
2976 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002977
Guy Benyei11169dd2012-12-18 14:30:41 +00002978 default:
JF Bastien0e828952019-06-26 19:50:12 +00002979 if (llvm::Error Err = Stream.SkipBlock()) {
2980 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00002981 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002982 }
2983 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 }
2985 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002986
Chris Lattnere7b154b2013-01-19 21:39:22 +00002987 case llvm::BitstreamEntry::Record:
2988 // The interesting case.
2989 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002990 }
2991
2992 // Read and process a record.
2993 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002994 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00002995 Expected<unsigned> MaybeRecordType =
2996 Stream.readRecord(Entry.ID, Record, &Blob);
2997 if (!MaybeRecordType) {
2998 Error(MaybeRecordType.takeError());
2999 return Failure;
3000 }
3001 ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
Richard Smithdbafb6c2017-06-29 23:23:46 +00003002
3003 // If we're not loading an AST context, we don't care about most records.
3004 if (!ContextObj) {
3005 switch (RecordType) {
3006 case IDENTIFIER_TABLE:
3007 case IDENTIFIER_OFFSET:
3008 case INTERESTING_IDENTIFIERS:
3009 case STATISTICS:
3010 case PP_CONDITIONAL_STACK:
3011 case PP_COUNTER_VALUE:
3012 case SOURCE_LOCATION_OFFSETS:
3013 case MODULE_OFFSET_MAP:
3014 case SOURCE_MANAGER_LINE_TABLE:
3015 case SOURCE_LOCATION_PRELOADS:
3016 case PPD_ENTITIES_OFFSETS:
3017 case HEADER_SEARCH_TABLE:
3018 case IMPORTED_MODULES:
3019 case MACRO_OFFSET:
3020 break;
3021 default:
3022 continue;
3023 }
3024 }
3025
3026 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 default: // Default behavior: ignore.
3028 break;
3029
3030 case TYPE_OFFSET: {
3031 if (F.LocalNumTypes != 0) {
3032 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003035 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 F.LocalNumTypes = Record[0];
3037 unsigned LocalBaseTypeIndex = Record[1];
3038 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003039
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 if (F.LocalNumTypes > 0) {
3041 // Introduce the global -> local mapping for types within this module.
3042 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003043
Guy Benyei11169dd2012-12-18 14:30:41 +00003044 // Introduce the local -> global mapping for types within this module.
3045 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003046 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003048
3049 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00003050 }
3051 break;
3052 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003053
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 case DECL_OFFSET: {
3055 if (F.LocalNumDecls != 0) {
3056 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003057 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003059 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 F.LocalNumDecls = Record[0];
3061 unsigned LocalBaseDeclID = Record[1];
3062 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003063
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003065 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003066 // module.
3067 GlobalDeclMap.insert(
3068 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003069
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 // Introduce the local -> global mapping for declarations within this
3071 // module.
3072 F.DeclRemap.insertOrReplace(
3073 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003074
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 // Introduce the global -> local mapping for declarations within this
3076 // module.
3077 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00003078
Ben Langmuir52ca6782014-10-20 16:27:32 +00003079 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
3080 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003081 break;
3082 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003083
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003085 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00003086 LexicalContents Contents(
3087 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
3088 Blob.data()),
3089 static_cast<unsigned int>(Blob.size() / 4));
3090 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 TU->setHasExternalLexicalStorage(true);
3092 break;
3093 }
3094
3095 case UPDATE_VISIBLE: {
3096 unsigned Idx = 0;
3097 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00003098 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00003099 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00003100 // If we've already loaded the decl, perform the updates when we finish
3101 // loading this block.
3102 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003103 PendingUpdateRecords.push_back(
3104 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00003105 break;
3106 }
3107
3108 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003109 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00003111 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
3112 (const unsigned char *)F.IdentifierTableData + Record[0],
3113 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
3114 (const unsigned char *)F.IdentifierTableData,
3115 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003116
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 PP.getIdentifierTable().setExternalIdentifierLookup(this);
3118 }
3119 break;
3120
3121 case IDENTIFIER_OFFSET: {
3122 if (F.LocalNumIdentifiers != 0) {
3123 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003124 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003126 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 F.LocalNumIdentifiers = Record[0];
3128 unsigned LocalBaseIdentifierID = Record[1];
3129 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003130
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 if (F.LocalNumIdentifiers > 0) {
3132 // Introduce the global -> local mapping for identifiers within this
3133 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003134 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003136
Guy Benyei11169dd2012-12-18 14:30:41 +00003137 // Introduce the local -> global mapping for identifiers within this
3138 // module.
3139 F.IdentifierRemap.insertOrReplace(
3140 std::make_pair(LocalBaseIdentifierID,
3141 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00003142
Ben Langmuir52ca6782014-10-20 16:27:32 +00003143 IdentifiersLoaded.resize(IdentifiersLoaded.size()
3144 + F.LocalNumIdentifiers);
3145 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 break;
3147 }
3148
Richard Smith33e0f7e2015-07-22 02:08:40 +00003149 case INTERESTING_IDENTIFIERS:
3150 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
3151 break;
3152
Ben Langmuir332aafe2014-01-31 01:06:56 +00003153 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00003154 // FIXME: Skip reading this record if our ASTConsumer doesn't care
3155 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00003156 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00003157 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00003158 break;
3159
David Blaikie9ffe5a32017-01-30 05:00:26 +00003160 case MODULAR_CODEGEN_DECLS:
3161 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
3162 // them (ie: if we're not codegenerating this module).
3163 if (F.Kind == MK_MainFile)
3164 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3165 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
3166 break;
3167
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00003169 if (SpecialTypes.empty()) {
3170 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3171 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
3172 break;
3173 }
3174
3175 if (SpecialTypes.size() != Record.size()) {
3176 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003177 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00003178 }
3179
3180 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3181 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
3182 if (!SpecialTypes[I])
3183 SpecialTypes[I] = ID;
3184 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
3185 // merge step?
3186 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 break;
3188
3189 case STATISTICS:
3190 TotalNumStatements += Record[0];
3191 TotalNumMacros += Record[1];
3192 TotalLexicalDeclContexts += Record[2];
3193 TotalVisibleDeclContexts += Record[3];
3194 break;
3195
3196 case UNUSED_FILESCOPED_DECLS:
3197 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3198 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
3199 break;
3200
3201 case DELEGATING_CTORS:
3202 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3203 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3204 break;
3205
3206 case WEAK_UNDECLARED_IDENTIFIERS:
3207 if (Record.size() % 4 != 0) {
3208 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003209 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003211
3212 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 // files. This isn't the way to do it :)
3214 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003215
Guy Benyei11169dd2012-12-18 14:30:41 +00003216 // Translate the weak, undeclared identifiers into global IDs.
3217 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3218 WeakUndeclaredIdentifiers.push_back(
3219 getGlobalIdentifierID(F, Record[I++]));
3220 WeakUndeclaredIdentifiers.push_back(
3221 getGlobalIdentifierID(F, Record[I++]));
3222 WeakUndeclaredIdentifiers.push_back(
3223 ReadSourceLocation(F, Record, I).getRawEncoding());
3224 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3225 }
3226 break;
3227
Guy Benyei11169dd2012-12-18 14:30:41 +00003228 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003229 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003230 F.LocalNumSelectors = Record[0];
3231 unsigned LocalBaseSelectorID = Record[1];
3232 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003233
Guy Benyei11169dd2012-12-18 14:30:41 +00003234 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003235 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 // module.
3237 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003238
3239 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003240 // module.
3241 F.SelectorRemap.insertOrReplace(
3242 std::make_pair(LocalBaseSelectorID,
3243 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003244
3245 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003246 }
3247 break;
3248 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003249
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003251 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 if (Record[0])
3253 F.SelectorLookupTable
3254 = ASTSelectorLookupTable::Create(
3255 F.SelectorLookupTableData + Record[0],
3256 F.SelectorLookupTableData,
3257 ASTSelectorLookupTrait(*this, F));
3258 TotalNumMethodPoolEntries += Record[1];
3259 break;
3260
3261 case REFERENCED_SELECTOR_POOL:
3262 if (!Record.empty()) {
3263 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003264 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 Record[Idx++]));
3266 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3267 getRawEncoding());
3268 }
3269 }
3270 break;
3271
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003272 case PP_CONDITIONAL_STACK:
3273 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003274 unsigned Idx = 0, End = Record.size() - 1;
3275 bool ReachedEOFWhileSkipping = Record[Idx++];
3276 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3277 if (ReachedEOFWhileSkipping) {
3278 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3279 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3280 bool FoundNonSkipPortion = Record[Idx++];
3281 bool FoundElse = Record[Idx++];
3282 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3283 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3284 FoundElse, ElseLoc);
3285 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003286 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003287 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003288 auto Loc = ReadSourceLocation(F, Record, Idx);
3289 bool WasSkipping = Record[Idx++];
3290 bool FoundNonSkip = Record[Idx++];
3291 bool FoundElse = Record[Idx++];
3292 ConditionalStack.push_back(
3293 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3294 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003295 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003296 }
3297 break;
3298
Guy Benyei11169dd2012-12-18 14:30:41 +00003299 case PP_COUNTER_VALUE:
3300 if (!Record.empty() && Listener)
3301 Listener->ReadCounter(F, Record[0]);
3302 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003303
Guy Benyei11169dd2012-12-18 14:30:41 +00003304 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003305 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 F.NumFileSortedDecls = Record[0];
3307 break;
3308
3309 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003310 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003311 F.LocalNumSLocEntries = Record[0];
3312 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003313 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003314 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003316 if (!F.SLocEntryBaseID) {
3317 Error("ran out of source locations");
3318 break;
3319 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003320 // Make our entry in the range map. BaseID is negative and growing, so
3321 // we invert it. Because we invert it, though, we need the other end of
3322 // the range.
3323 unsigned RangeStart =
3324 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3325 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3326 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3327
3328 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3329 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3330 GlobalSLocOffsetMap.insert(
3331 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3332 - SLocSpaceSize,&F));
3333
3334 // Initialize the remapping table.
3335 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003336 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003337 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003338 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003339 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003340
Guy Benyei11169dd2012-12-18 14:30:41 +00003341 TotalNumSLocEntries += F.LocalNumSLocEntries;
3342 break;
3343 }
3344
Richard Smith37a93df2017-02-18 00:32:02 +00003345 case MODULE_OFFSET_MAP:
3346 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003347 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003348
3349 case SOURCE_MANAGER_LINE_TABLE:
3350 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003351 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 break;
3353
3354 case SOURCE_LOCATION_PRELOADS: {
3355 // Need to transform from the local view (1-based IDs) to the global view,
3356 // which is based off F.SLocEntryBaseID.
3357 if (!F.PreloadSLocEntries.empty()) {
3358 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003359 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003360 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 F.PreloadSLocEntries.swap(Record);
3363 break;
3364 }
3365
3366 case EXT_VECTOR_DECLS:
3367 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3368 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3369 break;
3370
3371 case VTABLE_USES:
3372 if (Record.size() % 3 != 0) {
3373 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003374 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003375 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003376
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 // Later tables overwrite earlier ones.
3378 // FIXME: Modules will have some trouble with this. This is clearly not
3379 // the right way to do this.
3380 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003381
Guy Benyei11169dd2012-12-18 14:30:41 +00003382 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3383 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3384 VTableUses.push_back(
3385 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3386 VTableUses.push_back(Record[Idx++]);
3387 }
3388 break;
3389
Guy Benyei11169dd2012-12-18 14:30:41 +00003390 case PENDING_IMPLICIT_INSTANTIATIONS:
3391 if (PendingInstantiations.size() % 2 != 0) {
3392 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003393 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 }
3395
3396 if (Record.size() % 2 != 0) {
3397 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003398 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003399 }
3400
3401 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3402 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3403 PendingInstantiations.push_back(
3404 ReadSourceLocation(F, Record, I).getRawEncoding());
3405 }
3406 break;
3407
3408 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003409 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003410 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003411 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003412 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3414 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3415 break;
3416
3417 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003418 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3419 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3420 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003421
3422 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003423
Guy Benyei11169dd2012-12-18 14:30:41 +00003424 unsigned StartingID;
3425 if (!PP.getPreprocessingRecord())
3426 PP.createPreprocessingRecord();
3427 if (!PP.getPreprocessingRecord()->getExternalSource())
3428 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003429 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003430 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003431 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003432 F.BasePreprocessedEntityID = StartingID;
3433
3434 if (F.NumPreprocessedEntities > 0) {
3435 // Introduce the global -> local mapping for preprocessed entities in
3436 // this module.
3437 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003438
Guy Benyei11169dd2012-12-18 14:30:41 +00003439 // Introduce the local -> global mapping for preprocessed entities in
3440 // this module.
3441 F.PreprocessedEntityRemap.insertOrReplace(
3442 std::make_pair(LocalBasePreprocessedEntityID,
3443 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3444 }
3445
3446 break;
3447 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003448
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003449 case PPD_SKIPPED_RANGES: {
3450 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3451 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3452 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3453
3454 if (!PP.getPreprocessingRecord())
3455 PP.createPreprocessingRecord();
3456 if (!PP.getPreprocessingRecord()->getExternalSource())
3457 PP.getPreprocessingRecord()->SetExternalSource(*this);
3458 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3459 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003460
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003461 if (F.NumPreprocessedSkippedRanges > 0)
3462 GlobalSkippedRangeMap.insert(
3463 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3464 break;
3465 }
3466
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003467 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003468 if (Record.size() % 2 != 0) {
3469 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003470 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003471 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003472 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3473 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3474 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3475
3476 // If we've already loaded the decl, perform the updates when we finish
3477 // loading this block.
3478 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003479 PendingUpdateRecords.push_back(
3480 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003481 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003483
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003484 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003485 if (F.LocalNumObjCCategoriesInMap != 0) {
3486 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003487 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003488 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003489
Guy Benyei11169dd2012-12-18 14:30:41 +00003490 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003491 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003492 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003493
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 case OBJC_CATEGORIES:
3495 F.ObjCCategories.swap(Record);
3496 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003497
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 case CUDA_SPECIAL_DECL_REFS:
3499 // Later tables overwrite earlier ones.
3500 // FIXME: Modules will have trouble with this.
3501 CUDASpecialDeclRefs.clear();
3502 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3503 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3504 break;
3505
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003506 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003507 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003509 if (Record[0]) {
3510 F.HeaderFileInfoTable
3511 = HeaderFileInfoLookupTable::Create(
3512 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3513 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003514 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003516 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003517
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 PP.getHeaderSearchInfo().SetExternalSource(this);
3519 if (!PP.getHeaderSearchInfo().getExternalLookup())
3520 PP.getHeaderSearchInfo().SetExternalLookup(this);
3521 }
3522 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003523
Guy Benyei11169dd2012-12-18 14:30:41 +00003524 case FP_PRAGMA_OPTIONS:
3525 // Later tables overwrite earlier ones.
3526 FPPragmaOptions.swap(Record);
3527 break;
3528
3529 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003530 for (unsigned I = 0, E = Record.size(); I != E; ) {
3531 auto Name = ReadString(Record, I);
3532 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003533 Opt.Supported = Record[I++] != 0;
3534 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003535 Opt.Avail = Record[I++];
3536 Opt.Core = Record[I++];
3537 }
3538 break;
3539
3540 case OPENCL_EXTENSION_TYPES:
3541 for (unsigned I = 0, E = Record.size(); I != E;) {
3542 auto TypeID = static_cast<::TypeID>(Record[I++]);
3543 auto *Type = GetType(TypeID).getTypePtr();
3544 auto NumExt = static_cast<unsigned>(Record[I++]);
3545 for (unsigned II = 0; II != NumExt; ++II) {
3546 auto Ext = ReadString(Record, I);
3547 OpenCLTypeExtMap[Type].insert(Ext);
3548 }
3549 }
3550 break;
3551
3552 case OPENCL_EXTENSION_DECLS:
3553 for (unsigned I = 0, E = Record.size(); I != E;) {
3554 auto DeclID = static_cast<::DeclID>(Record[I++]);
3555 auto *Decl = GetDecl(DeclID);
3556 auto NumExt = static_cast<unsigned>(Record[I++]);
3557 for (unsigned II = 0; II != NumExt; ++II) {
3558 auto Ext = ReadString(Record, I);
3559 OpenCLDeclExtMap[Decl].insert(Ext);
3560 }
3561 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 break;
3563
3564 case TENTATIVE_DEFINITIONS:
3565 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3566 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3567 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003568
Guy Benyei11169dd2012-12-18 14:30:41 +00003569 case KNOWN_NAMESPACES:
3570 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3571 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3572 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003573
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003574 case UNDEFINED_BUT_USED:
3575 if (UndefinedButUsed.size() % 2 != 0) {
3576 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003577 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003578 }
3579
3580 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003581 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003582 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003583 }
3584 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003585 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3586 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003587 ReadSourceLocation(F, Record, I).getRawEncoding());
3588 }
3589 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003590
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003591 case DELETE_EXPRS_TO_ANALYZE:
3592 for (unsigned I = 0, N = Record.size(); I != N;) {
3593 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3594 const uint64_t Count = Record[I++];
3595 DelayedDeleteExprs.push_back(Count);
3596 for (uint64_t C = 0; C < Count; ++C) {
3597 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3598 bool IsArrayForm = Record[I++] == 1;
3599 DelayedDeleteExprs.push_back(IsArrayForm);
3600 }
3601 }
3602 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003603
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003604 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003605 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003606 // If we aren't loading a module (which has its own exports), make
3607 // all of the imported modules visible.
3608 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003609 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3610 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3611 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003612 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003613 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003614 if (DeserializationListener)
3615 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3616 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 }
3618 }
3619 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003620
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 case MACRO_OFFSET: {
3622 if (F.LocalNumMacros != 0) {
3623 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003624 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003625 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003626 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 F.LocalNumMacros = Record[0];
3628 unsigned LocalBaseMacroID = Record[1];
3629 F.BaseMacroID = getTotalNumMacros();
3630
3631 if (F.LocalNumMacros > 0) {
3632 // Introduce the global -> local mapping for macros within this module.
3633 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3634
3635 // Introduce the local -> global mapping for macros within this module.
3636 F.MacroRemap.insertOrReplace(
3637 std::make_pair(LocalBaseMacroID,
3638 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003639
3640 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003641 }
3642 break;
3643 }
3644
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003645 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003646 LateParsedTemplates.append(Record.begin(), Record.end());
3647 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003648
3649 case OPTIMIZE_PRAGMA_OPTIONS:
3650 if (Record.size() != 1) {
3651 Error("invalid pragma optimize record");
3652 return Failure;
3653 }
3654 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3655 break;
Nico Weber72889432014-09-06 01:25:55 +00003656
Nico Weber779355f2016-03-02 23:22:00 +00003657 case MSSTRUCT_PRAGMA_OPTIONS:
3658 if (Record.size() != 1) {
3659 Error("invalid pragma ms_struct record");
3660 return Failure;
3661 }
3662 PragmaMSStructState = Record[0];
3663 break;
3664
Nico Weber42932312016-03-03 00:17:35 +00003665 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3666 if (Record.size() != 2) {
3667 Error("invalid pragma ms_struct record");
3668 return Failure;
3669 }
3670 PragmaMSPointersToMembersState = Record[0];
3671 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3672 break;
3673
Nico Weber72889432014-09-06 01:25:55 +00003674 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3675 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3676 UnusedLocalTypedefNameCandidates.push_back(
3677 getGlobalDeclID(F, Record[I]));
3678 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003679
3680 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3681 if (Record.size() != 1) {
3682 Error("invalid cuda pragma options record");
3683 return Failure;
3684 }
3685 ForceCUDAHostDeviceDepth = Record[0];
3686 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003687
3688 case PACK_PRAGMA_OPTIONS: {
3689 if (Record.size() < 3) {
3690 Error("invalid pragma pack record");
3691 return Failure;
3692 }
3693 PragmaPackCurrentValue = Record[0];
3694 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3695 unsigned NumStackEntries = Record[2];
3696 unsigned Idx = 3;
3697 // Reset the stack when importing a new module.
3698 PragmaPackStack.clear();
3699 for (unsigned I = 0; I < NumStackEntries; ++I) {
3700 PragmaPackStackEntry Entry;
3701 Entry.Value = Record[Idx++];
3702 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003703 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003704 PragmaPackStrings.push_back(ReadString(Record, Idx));
3705 Entry.SlotLabel = PragmaPackStrings.back();
3706 PragmaPackStack.push_back(Entry);
3707 }
3708 break;
3709 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003710 }
3711 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003712}
3713
Richard Smith37a93df2017-02-18 00:32:02 +00003714void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3715 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3716
3717 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003718 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003719 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3720 F.ModuleOffsetMap = StringRef();
3721
3722 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3723 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3724 F.SLocRemap.insert(std::make_pair(0U, 0));
3725 F.SLocRemap.insert(std::make_pair(2U, 1));
3726 }
3727
3728 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003729 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003730 RemapBuilder SLocRemap(F.SLocRemap);
3731 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3732 RemapBuilder MacroRemap(F.MacroRemap);
3733 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3734 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3735 RemapBuilder SelectorRemap(F.SelectorRemap);
3736 RemapBuilder DeclRemap(F.DeclRemap);
3737 RemapBuilder TypeRemap(F.TypeRemap);
3738
3739 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003740 // FIXME: Looking up dependency modules by filename is horrible. Let's
3741 // start fixing this with prebuilt and explicit modules and see how it
3742 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003743 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003744 ModuleKind Kind = static_cast<ModuleKind>(
3745 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003746 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3747 StringRef Name = StringRef((const char*)Data, Len);
3748 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003749 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3750 ? ModuleMgr.lookupByModuleName(Name)
3751 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003752 if (!OM) {
3753 std::string Msg =
3754 "SourceLocation remap refers to unknown module, cannot find ";
3755 Msg.append(Name);
3756 Error(Msg);
3757 return;
3758 }
3759
3760 uint32_t SLocOffset =
3761 endian::readNext<uint32_t, little, unaligned>(Data);
3762 uint32_t IdentifierIDOffset =
3763 endian::readNext<uint32_t, little, unaligned>(Data);
3764 uint32_t MacroIDOffset =
3765 endian::readNext<uint32_t, little, unaligned>(Data);
3766 uint32_t PreprocessedEntityIDOffset =
3767 endian::readNext<uint32_t, little, unaligned>(Data);
3768 uint32_t SubmoduleIDOffset =
3769 endian::readNext<uint32_t, little, unaligned>(Data);
3770 uint32_t SelectorIDOffset =
3771 endian::readNext<uint32_t, little, unaligned>(Data);
3772 uint32_t DeclIDOffset =
3773 endian::readNext<uint32_t, little, unaligned>(Data);
3774 uint32_t TypeIndexOffset =
3775 endian::readNext<uint32_t, little, unaligned>(Data);
3776
3777 uint32_t None = std::numeric_limits<uint32_t>::max();
3778
3779 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3780 RemapBuilder &Remap) {
3781 if (Offset != None)
3782 Remap.insert(std::make_pair(Offset,
3783 static_cast<int>(BaseOffset - Offset)));
3784 };
3785 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3786 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3787 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3788 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3789 PreprocessedEntityRemap);
3790 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3791 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3792 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3793 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3794
3795 // Global -> local mappings.
3796 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3797 }
3798}
3799
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003800ASTReader::ASTReadResult
3801ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3802 const ModuleFile *ImportedBy,
3803 unsigned ClientLoadCapabilities) {
3804 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003805 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003806
3807 // Try to resolve ModuleName in the current header search context and
3808 // verify that it is found in the same module map file as we saved. If the
3809 // top-level AST file is a main file, skip this check because there is no
3810 // usable header search context.
3811 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003812 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003813 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003814 // An implicitly-loaded module file should have its module listed in some
3815 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003816 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003817 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3818 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003819 // Don't emit module relocation error if we have -fno-validate-pch
3820 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003821 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003822 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003823 // This module was defined by an imported (explicit) module.
3824 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3825 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003826 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003827 // This module was built with a different module map.
3828 Diag(diag::err_imported_module_not_found)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003829 << F.ModuleName << F.FileName
3830 << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
3831 << !ImportedBy;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003832 // In case it was imported by a PCH, there's a chance the user is
3833 // just missing to include the search path to the directory containing
3834 // the modulemap.
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003835 if (ImportedBy && ImportedBy->Kind == MK_PCH)
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003836 Diag(diag::note_imported_by_pch_module_not_found)
3837 << llvm::sys::path::parent_path(F.ModuleMapPath);
3838 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003839 }
3840 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003841 }
3842
Richard Smithe842a472014-10-22 02:05:46 +00003843 assert(M->Name == F.ModuleName && "found module with different name");
3844
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003845 // Check the primary module map file.
Harlan Haskins8d323d12019-08-01 21:31:56 +00003846 auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
3847 if (!StoredModMap || *StoredModMap != ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003848 assert(ModMap && "found module is missing module map file");
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003849 assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
3850 "top-level import should be verified");
3851 bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003852 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3853 Diag(diag::err_imported_module_modmap_changed)
Bruno Cardoso Lopes4625c182019-08-29 23:14:08 +00003854 << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
3855 << ModMap->getName() << F.ModuleMapPath << NotImported;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003856 return OutOfDate;
3857 }
3858
3859 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3860 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3861 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003862 std::string Filename = ReadPath(F, Record, Idx);
Harlan Haskins8d323d12019-08-01 21:31:56 +00003863 auto F = FileMgr.getFile(Filename, false, false);
3864 if (!F) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003865 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3866 Error("could not find file '" + Filename +"' referenced by AST file");
3867 return OutOfDate;
3868 }
Harlan Haskins8d323d12019-08-01 21:31:56 +00003869 AdditionalStoredMaps.insert(*F);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003870 }
3871
3872 // Check any additional module map files (e.g. module.private.modulemap)
3873 // that are not in the pcm.
3874 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003875 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003876 // Remove files that match
3877 // Note: SmallPtrSet::erase is really remove
3878 if (!AdditionalStoredMaps.erase(ModMap)) {
3879 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3880 Diag(diag::err_module_different_modmap)
3881 << F.ModuleName << /*new*/0 << ModMap->getName();
3882 return OutOfDate;
3883 }
3884 }
3885 }
3886
3887 // Check any additional module map files that are in the pcm, but not
3888 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003889 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003890 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3891 Diag(diag::err_module_different_modmap)
3892 << F.ModuleName << /*not new*/1 << ModMap->getName();
3893 return OutOfDate;
3894 }
3895 }
3896
3897 if (Listener)
3898 Listener->ReadModuleMapFile(F.ModuleMapPath);
3899 return Success;
3900}
3901
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003902/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003903static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3904 // Find the entry for this selector in the method pool.
3905 Sema::GlobalMethodPool::iterator Known
3906 = S.MethodPool.find(Method->getSelector());
3907 if (Known == S.MethodPool.end())
3908 return;
3909
3910 // Retrieve the appropriate method list.
3911 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3912 : Known->second.second;
3913 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003914 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003915 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003916 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003917 Found = true;
3918 } else {
3919 // Keep searching.
3920 continue;
3921 }
3922 }
3923
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003924 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003925 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003926 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003927 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003928 }
3929}
3930
Richard Smithde711422015-04-23 21:20:19 +00003931void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003932 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003933 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003934 bool wasHidden = D->isHidden();
3935 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003936
Vedant Kumar48b4f762018-04-14 01:40:48 +00003937 if (wasHidden && SemaObj) {
3938 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003939 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003940 }
3941 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 }
3943}
3944
Richard Smith49f906a2014-03-01 00:08:04 +00003945void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003946 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003947 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003949 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003950 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003952 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003953
3954 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003955 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003956 // there is nothing more to do.
3957 continue;
3958 }
Richard Smith49f906a2014-03-01 00:08:04 +00003959
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 if (!Mod->isAvailable()) {
3961 // Modules that aren't available cannot be made visible.
3962 continue;
3963 }
3964
3965 // Update the module's name visibility.
3966 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003967
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 // If we've already deserialized any names from this module,
3969 // mark them as visible.
3970 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3971 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003972 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003974 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003975 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3976 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003977 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003978
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003980 SmallVector<Module *, 16> Exports;
3981 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003982 for (SmallVectorImpl<Module *>::iterator
3983 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3984 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003985 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003986 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003987 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 }
3989}
3990
Richard Smith6561f922016-09-12 21:06:40 +00003991/// We've merged the definition \p MergedDef into the existing definition
3992/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3993/// visible.
3994void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3995 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00003996 if (Def->isHidden()) {
3997 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003998 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003999 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00004000 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004001 getContext().mergeDefinitionIntoModule(
4002 Def, MergedDef->getImportedOwningModule(),
4003 /*NotifyListeners*/ false);
4004 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00004005 }
Richard Smith6561f922016-09-12 21:06:40 +00004006 }
4007}
4008
Douglas Gregore060e572013-01-25 01:03:03 +00004009bool ASTReader::loadGlobalIndex() {
4010 if (GlobalIndex)
4011 return false;
4012
4013 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00004014 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00004015 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004016
Douglas Gregore060e572013-01-25 01:03:03 +00004017 // Try to load the global index.
4018 TriedLoadingGlobalIndex = true;
4019 StringRef ModuleCachePath
4020 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
JF Bastien0e828952019-06-26 19:50:12 +00004021 std::pair<GlobalModuleIndex *, llvm::Error> Result =
4022 GlobalModuleIndex::readIndex(ModuleCachePath);
4023 if (llvm::Error Err = std::move(Result.second)) {
4024 assert(!Result.first);
4025 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Douglas Gregore060e572013-01-25 01:03:03 +00004026 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004027 }
Douglas Gregore060e572013-01-25 01:03:03 +00004028
4029 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00004030 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00004031 return false;
4032}
4033
4034bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004035 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00004036 !hasGlobalIndex() && TriedLoadingGlobalIndex;
4037}
4038
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004039static void updateModuleTimestamp(ModuleFile &MF) {
4040 // Overwrite the timestamp file contents so that file's mtime changes.
4041 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00004042 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +00004043 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::OF_Text);
Rafael Espindoladae941a2014-08-25 18:17:04 +00004044 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004045 return;
4046 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00004047 OS.close();
4048 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004049}
4050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004051/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004052/// cursor into the start of the given block ID, returning false on success and
4053/// true on failure.
4054static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004055 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004056 Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
4057 if (!MaybeEntry) {
4058 // FIXME this drops errors on the floor.
4059 consumeError(MaybeEntry.takeError());
4060 return true;
4061 }
4062 llvm::BitstreamEntry Entry = MaybeEntry.get();
4063
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004064 switch (Entry.Kind) {
4065 case llvm::BitstreamEntry::Error:
4066 case llvm::BitstreamEntry::EndBlock:
4067 return true;
4068
4069 case llvm::BitstreamEntry::Record:
4070 // Ignore top-level records.
JF Bastien0e828952019-06-26 19:50:12 +00004071 if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
4072 break;
4073 else {
4074 // FIXME this drops errors on the floor.
4075 consumeError(Skipped.takeError());
4076 return true;
4077 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004078
4079 case llvm::BitstreamEntry::SubBlock:
4080 if (Entry.ID == BlockID) {
JF Bastien0e828952019-06-26 19:50:12 +00004081 if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
4082 // FIXME this drops the error on the floor.
4083 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004084 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004085 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004086 // Found it!
4087 return false;
4088 }
4089
JF Bastien0e828952019-06-26 19:50:12 +00004090 if (llvm::Error Err = Cursor.SkipBlock()) {
4091 // FIXME this drops the error on the floor.
4092 consumeError(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004093 return true;
JF Bastien0e828952019-06-26 19:50:12 +00004094 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004095 }
4096 }
4097}
4098
Benjamin Kramer0772c422016-02-13 13:42:54 +00004099ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00004100 ModuleKind Type,
4101 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00004102 unsigned ClientLoadCapabilities,
4103 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00004104 llvm::SaveAndRestore<SourceLocation>
4105 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
4106
Richard Smithd1c46742014-04-30 02:24:17 +00004107 // Defer any pending actions until we get to the end of reading the AST file.
4108 Deserializing AnASTFile(this);
4109
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00004111 unsigned PreviousGeneration = 0;
4112 if (ContextObj)
4113 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00004114
4115 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004116 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004117 switch (ASTReadResult ReadResult =
4118 ReadASTCore(FileName, Type, ImportLoc,
4119 /*ImportedBy=*/nullptr, Loaded, 0, 0,
4120 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00004122 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 case OutOfDate:
4124 case VersionMismatch:
4125 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00004126 case HadErrors: {
4127 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004128 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00004129 LoadedSet.insert(IM.Mod);
4130
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004131 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00004132 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00004133 ? &PP.getHeaderSearchInfo().getModuleMap()
4134 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00004135
4136 // If we find that any modules are unusable, the global index is going
4137 // to be out-of-date. Just remove it.
4138 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00004139 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004140 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00004141 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004142 case Success:
4143 break;
4144 }
4145
4146 // Here comes stuff that we only do once the entire chain is loaded.
4147
4148 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004149 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4150 MEnd = Loaded.end();
4151 M != MEnd; ++M) {
4152 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00004153
4154 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00004155 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
4156 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00004157
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004158 // Read the extension blocks.
4159 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
4160 if (ASTReadResult Result = ReadExtensionBlock(F))
4161 return Result;
4162 }
4163
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004164 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00004165 // bits of all files we've seen.
4166 F.GlobalBitOffset = TotalModulesSizeInBits;
4167 TotalModulesSizeInBits += F.SizeInBits;
4168 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004169
Guy Benyei11169dd2012-12-18 14:30:41 +00004170 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004171 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
4172 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 // Load it through the SourceManager and don't call ReadSLocEntry()
4174 // directly because the entry may have already been loaded in which case
4175 // calling ReadSLocEntry() directly would trigger an assertion in
4176 // SourceManager.
4177 SourceMgr.getLoadedSLocEntryByID(Index);
4178 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00004179
Richard Smithea741482017-05-01 22:10:47 +00004180 // Map the original source file ID into the ID space of the current
4181 // compilation.
4182 if (F.OriginalSourceFileID.isValid()) {
4183 F.OriginalSourceFileID = FileID::get(
4184 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
4185 }
4186
Richard Smith33e0f7e2015-07-22 02:08:40 +00004187 // Preload all the pending interesting identifiers by marking them out of
4188 // date.
4189 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004190 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00004191 F.IdentifierTableData + Offset);
4192
4193 ASTIdentifierLookupTrait Trait(*this, F);
4194 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
4195 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00004196 auto &II = PP.getIdentifierTable().getOwn(Key);
4197 II.setOutOfDate(true);
4198
4199 // Mark this identifier as being from an AST file so that we can track
4200 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00004201 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00004202
4203 // Associate the ID with the identifier so that the writer can reuse it.
4204 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
4205 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004206 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 }
4208
Douglas Gregor603cd862013-03-22 18:50:14 +00004209 // Setup the import locations and notify the module manager that we've
4210 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004211 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
4212 MEnd = Loaded.end();
4213 M != MEnd; ++M) {
4214 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00004215
4216 ModuleMgr.moduleFileAccepted(&F);
4217
4218 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00004219 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00004220 // FIXME: We assume that locations from PCH / preamble do not need
4221 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004222 if (!M->ImportedBy)
4223 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00004225 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004226 }
4227
Richard Smithdbafb6c2017-06-29 23:23:46 +00004228 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004229 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4230 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004231 // Mark all of the identifiers in the identifier table as being out of date,
4232 // so that various accessors know to check the loaded modules when the
4233 // identifier is used.
4234 //
4235 // For C++ modules, we don't need information on many identifiers (just
4236 // those that provide macros or are poisoned), so we mark all of
4237 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004238 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4239 IdEnd = PP.getIdentifierTable().end();
4240 Id != IdEnd; ++Id)
4241 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004242 }
Manman Rena0f31a02016-04-29 19:04:05 +00004243 // Mark selectors as out of date.
4244 for (auto Sel : SelectorGeneration)
4245 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004246
Guy Benyei11169dd2012-12-18 14:30:41 +00004247 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004248 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4249 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004250 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4251 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004252
4253 switch (Unresolved.Kind) {
4254 case UnresolvedModuleRef::Conflict:
4255 if (ResolvedMod) {
4256 Module::Conflict Conflict;
4257 Conflict.Other = ResolvedMod;
4258 Conflict.Message = Unresolved.String.str();
4259 Unresolved.Mod->Conflicts.push_back(Conflict);
4260 }
4261 continue;
4262
4263 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004264 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004265 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004267
Douglas Gregorfb912652013-03-20 21:10:35 +00004268 case UnresolvedModuleRef::Export:
4269 if (ResolvedMod || Unresolved.IsWildcard)
4270 Unresolved.Mod->Exports.push_back(
4271 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4272 continue;
4273 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004275 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004276
Graydon Hoaree7196af2016-12-09 21:45:49 +00004277 if (Imported)
4278 Imported->append(ImportedModules.begin(),
4279 ImportedModules.end());
4280
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004281 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4282 // Might be unnecessary as use declarations are only used to build the
4283 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004284
Richard Smithdbafb6c2017-06-29 23:23:46 +00004285 if (ContextObj)
4286 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004287
Richard Smith3d8e97e2013-10-18 06:54:39 +00004288 if (SemaObj)
4289 UpdateSema();
4290
Guy Benyei11169dd2012-12-18 14:30:41 +00004291 if (DeserializationListener)
4292 DeserializationListener->ReaderInitialized(this);
4293
4294 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004295 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 // If this AST file is a precompiled preamble, then set the
4297 // preamble file ID of the source manager to the file source file
4298 // from which the preamble was built.
4299 if (Type == MK_Preamble) {
4300 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4301 } else if (Type == MK_MainFile) {
4302 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4303 }
4304 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004305
Guy Benyei11169dd2012-12-18 14:30:41 +00004306 // For any Objective-C class definitions we have already loaded, make sure
4307 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004308 if (ContextObj) {
4309 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4310 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4311 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004312 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004313 }
4314 }
Douglas Gregore060e572013-01-25 01:03:03 +00004315
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004316 if (PP.getHeaderSearchInfo()
4317 .getHeaderSearchOpts()
4318 .ModulesValidateOncePerBuildSession) {
4319 // Now we are certain that the module and all modules it depends on are
4320 // up to date. Create or update timestamp files for modules that are
4321 // located in the module cache (not for PCH files that could be anywhere
4322 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004323 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4324 ImportedModule &M = Loaded[I];
4325 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004326 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004327 }
4328 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004329 }
4330
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 return Success;
4332}
4333
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004334static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004335
JF Bastien0e828952019-06-26 19:50:12 +00004336/// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
4337static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
4338 // FIXME checking magic headers is done in other places such as
4339 // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
4340 // always done the same. Unify it all with a helper.
4341 if (!Stream.canSkipToPos(4))
4342 return llvm::createStringError(std::errc::illegal_byte_sequence,
4343 "file too small to contain AST file magic");
4344 for (unsigned C : {'C', 'P', 'C', 'H'})
4345 if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
4346 if (Res.get() != C)
4347 return llvm::createStringError(
4348 std::errc::illegal_byte_sequence,
4349 "file doesn't start with AST file magic");
4350 } else
4351 return Res.takeError();
4352 return llvm::Error::success();
Ben Langmuir70a1b812015-03-24 04:43:52 +00004353}
4354
Richard Smith0f99d6a2015-08-09 08:48:41 +00004355static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4356 switch (Kind) {
4357 case MK_PCH:
4358 return 0; // PCH
4359 case MK_ImplicitModule:
4360 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004361 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004362 return 1; // module
4363 case MK_MainFile:
4364 case MK_Preamble:
4365 return 2; // main source file
4366 }
4367 llvm_unreachable("unknown module kind");
4368}
4369
Guy Benyei11169dd2012-12-18 14:30:41 +00004370ASTReader::ASTReadResult
4371ASTReader::ReadASTCore(StringRef FileName,
4372 ModuleKind Type,
4373 SourceLocation ImportLoc,
4374 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004375 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004376 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004377 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004378 unsigned ClientLoadCapabilities) {
4379 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004381 ModuleManager::AddModuleResult AddResult
4382 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004383 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004384 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004385 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004386
Douglas Gregor7029ce12013-03-19 00:28:20 +00004387 switch (AddResult) {
4388 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004389 Diag(diag::remark_module_import)
4390 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4391 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004392 return Success;
4393
4394 case ModuleManager::NewlyLoaded:
4395 // Load module file below.
4396 break;
4397
4398 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004399 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004400 // it.
4401 if (ClientLoadCapabilities & ARR_Missing)
4402 return Missing;
4403
4404 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004405 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004406 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004407 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004408 return Failure;
4409
4410 case ModuleManager::OutOfDate:
4411 // We couldn't load the module file because it is out-of-date. If the
4412 // client can handle out-of-date, return it.
4413 if (ClientLoadCapabilities & ARR_OutOfDate)
4414 return OutOfDate;
4415
4416 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004417 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004418 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004419 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004420 return Failure;
4421 }
4422
Douglas Gregor7029ce12013-03-19 00:28:20 +00004423 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004424
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004425 bool ShouldFinalizePCM = false;
4426 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4427 auto &MC = getModuleManager().getModuleCache();
4428 if (ShouldFinalizePCM)
4429 MC.finalizePCM(FileName);
4430 else
4431 MC.tryToDropPCM(FileName);
4432 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004434 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004435 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004436 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004437
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004439 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4440 Diag(diag::err_module_file_invalid)
4441 << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
Guy Benyei11169dd2012-12-18 14:30:41 +00004442 return Failure;
4443 }
4444
4445 // This is used for compatibility with older PCH formats.
4446 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004447 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004448 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4449 if (!MaybeEntry) {
4450 Error(MaybeEntry.takeError());
4451 return Failure;
4452 }
4453 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004454
Chris Lattnerefa77172013-01-20 00:00:22 +00004455 switch (Entry.Kind) {
4456 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004457 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004458 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 Error("invalid record at top-level of AST file");
4460 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004461
Chris Lattnerefa77172013-01-20 00:00:22 +00004462 case llvm::BitstreamEntry::SubBlock:
4463 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004464 }
4465
Chris Lattnerefa77172013-01-20 00:00:22 +00004466 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 case CONTROL_BLOCK_ID:
4468 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004469 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004471 // Check that we didn't try to load a non-module AST file as a module.
4472 //
4473 // FIXME: Should we also perform the converse check? Loading a module as
4474 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004475 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4476 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004477 F.ModuleName.empty()) {
4478 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4479 if (Result != OutOfDate ||
4480 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4481 Diag(diag::err_module_file_not_module) << FileName;
4482 return Result;
4483 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004484 break;
4485
4486 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004487 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 case OutOfDate: return OutOfDate;
4489 case VersionMismatch: return VersionMismatch;
4490 case ConfigurationMismatch: return ConfigurationMismatch;
4491 case HadErrors: return HadErrors;
4492 }
4493 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004494
Guy Benyei11169dd2012-12-18 14:30:41 +00004495 case AST_BLOCK_ID:
4496 if (!HaveReadControlBlock) {
4497 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004498 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 return VersionMismatch;
4500 }
4501
4502 // Record that we've loaded this module.
4503 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004504 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 return Success;
4506
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004507 case UNHASHED_CONTROL_BLOCK_ID:
4508 // This block is handled using look-ahead during ReadControlBlock. We
4509 // shouldn't get here!
4510 Error("malformed block record in AST file");
4511 return Failure;
4512
Guy Benyei11169dd2012-12-18 14:30:41 +00004513 default:
JF Bastien0e828952019-06-26 19:50:12 +00004514 if (llvm::Error Err = Stream.SkipBlock()) {
4515 Error(std::move(Err));
Guy Benyei11169dd2012-12-18 14:30:41 +00004516 return Failure;
4517 }
4518 break;
4519 }
4520 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004521
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004522 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004523}
4524
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004525ASTReader::ASTReadResult
4526ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4527 unsigned ClientLoadCapabilities) {
4528 const HeaderSearchOptions &HSOpts =
4529 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4530 bool AllowCompatibleConfigurationMismatch =
4531 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4532
4533 ASTReadResult Result = readUnhashedControlBlockImpl(
4534 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4535 Listener.get(),
4536 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4537
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004538 // If F was directly imported by another module, it's implicitly validated by
4539 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004540 if (DisableValidation || WasImportedBy ||
4541 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4542 return Success;
4543
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004544 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004545 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004546 return Failure;
4547 }
4548
4549 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004550 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004551 // with it; we can only load a single version of each module.
4552 //
4553 // This can happen when a module is imported in two contexts: in one, as a
4554 // user module; in another, as a system module (due to an import from
4555 // another module marked with the [system] flag). It usually indicates a
4556 // bug in the module map: this module should also be marked with [system].
4557 //
4558 // If -Wno-system-headers (the default), and the first import is as a
4559 // system module, then validation will fail during the as-user import,
4560 // since -Werror flags won't have been validated. However, it's reasonable
4561 // to treat this consistently as a system module.
4562 //
4563 // If -Wsystem-headers, the PCM on disk was built with
4564 // -Wno-system-headers, and the first import is as a user module, then
4565 // validation will fail during the as-system import since the PCM on disk
4566 // doesn't guarantee that -Werror was respected. However, the -Werror
4567 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004568 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004569 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4570 return Success;
4571 }
4572 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004573
4574 return Result;
4575}
4576
4577ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4578 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4579 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4580 bool ValidateDiagnosticOptions) {
4581 // Initialize a stream.
4582 BitstreamCursor Stream(StreamData);
4583
4584 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004585 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4586 // FIXME this drops the error on the floor.
4587 consumeError(std::move(Err));
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004588 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004589 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004590
4591 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4592 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4593 return Failure;
4594
4595 // Read all of the records in the options block.
4596 RecordData Record;
4597 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004598 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004599 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4600 if (!MaybeEntry) {
4601 // FIXME this drops the error on the floor.
4602 consumeError(MaybeEntry.takeError());
4603 return Failure;
4604 }
4605 llvm::BitstreamEntry Entry = MaybeEntry.get();
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004606
4607 switch (Entry.Kind) {
4608 case llvm::BitstreamEntry::Error:
4609 case llvm::BitstreamEntry::SubBlock:
4610 return Failure;
4611
4612 case llvm::BitstreamEntry::EndBlock:
4613 return Result;
4614
4615 case llvm::BitstreamEntry::Record:
4616 // The interesting case.
4617 break;
4618 }
4619
4620 // Read and process a record.
4621 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00004622 Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
4623 if (!MaybeRecordType) {
4624 // FIXME this drops the error.
4625 return Failure;
4626 }
4627 switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004628 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004629 if (F)
4630 std::copy(Record.begin(), Record.end(), F->Signature.data());
4631 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004632 case DIAGNOSTIC_OPTIONS: {
4633 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4634 if (Listener && ValidateDiagnosticOptions &&
4635 !AllowCompatibleConfigurationMismatch &&
4636 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004637 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004638 break;
4639 }
4640 case DIAG_PRAGMA_MAPPINGS:
4641 if (!F)
4642 break;
4643 if (F->PragmaDiagMappings.empty())
4644 F->PragmaDiagMappings.swap(Record);
4645 else
4646 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4647 Record.begin(), Record.end());
4648 break;
4649 }
4650 }
4651}
4652
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004653/// Parse a record and blob containing module file extension metadata.
4654static bool parseModuleFileExtensionMetadata(
4655 const SmallVectorImpl<uint64_t> &Record,
4656 StringRef Blob,
4657 ModuleFileExtensionMetadata &Metadata) {
4658 if (Record.size() < 4) return true;
4659
4660 Metadata.MajorVersion = Record[0];
4661 Metadata.MinorVersion = Record[1];
4662
4663 unsigned BlockNameLen = Record[2];
4664 unsigned UserInfoLen = Record[3];
4665
4666 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4667
4668 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4669 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4670 Blob.data() + BlockNameLen + UserInfoLen);
4671 return false;
4672}
4673
4674ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4675 BitstreamCursor &Stream = F.Stream;
4676
4677 RecordData Record;
4678 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004679 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4680 if (!MaybeEntry) {
4681 Error(MaybeEntry.takeError());
4682 return Failure;
4683 }
4684 llvm::BitstreamEntry Entry = MaybeEntry.get();
4685
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004686 switch (Entry.Kind) {
4687 case llvm::BitstreamEntry::SubBlock:
JF Bastien0e828952019-06-26 19:50:12 +00004688 if (llvm::Error Err = Stream.SkipBlock()) {
4689 Error(std::move(Err));
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004690 return Failure;
JF Bastien0e828952019-06-26 19:50:12 +00004691 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004692 continue;
4693
4694 case llvm::BitstreamEntry::EndBlock:
4695 return Success;
4696
4697 case llvm::BitstreamEntry::Error:
4698 return HadErrors;
4699
4700 case llvm::BitstreamEntry::Record:
4701 break;
4702 }
4703
4704 Record.clear();
4705 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004706 Expected<unsigned> MaybeRecCode =
4707 Stream.readRecord(Entry.ID, Record, &Blob);
4708 if (!MaybeRecCode) {
4709 Error(MaybeRecCode.takeError());
4710 return Failure;
4711 }
4712 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004713 case EXTENSION_METADATA: {
4714 ModuleFileExtensionMetadata Metadata;
4715 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4716 return Failure;
4717
4718 // Find a module file extension with this block name.
4719 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4720 if (Known == ModuleFileExtensions.end()) break;
4721
4722 // Form a reader.
4723 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4724 F, Stream)) {
4725 F.ExtensionReaders.push_back(std::move(Reader));
4726 }
4727
4728 break;
4729 }
4730 }
4731 }
4732
4733 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004734}
4735
Richard Smitha7e2cc62015-05-01 01:53:09 +00004736void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004737 assert(ContextObj && "no context to initialize");
4738 ASTContext &Context = *ContextObj;
4739
Guy Benyei11169dd2012-12-18 14:30:41 +00004740 // If there's a listener, notify them that we "read" the translation unit.
4741 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004742 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004743 Context.getTranslationUnitDecl());
4744
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 // FIXME: Find a better way to deal with collisions between these
4746 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004747
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 // Load the special types.
4749 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4750 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4751 if (!Context.CFConstantStringTypeDecl)
4752 Context.setCFConstantStringType(GetType(String));
4753 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004754
Guy Benyei11169dd2012-12-18 14:30:41 +00004755 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4756 QualType FileType = GetType(File);
4757 if (FileType.isNull()) {
4758 Error("FILE type is NULL");
4759 return;
4760 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004761
Guy Benyei11169dd2012-12-18 14:30:41 +00004762 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004763 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004764 Context.setFILEDecl(Typedef->getDecl());
4765 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004766 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004767 if (!Tag) {
4768 Error("Invalid FILE type in AST file");
4769 return;
4770 }
4771 Context.setFILEDecl(Tag->getDecl());
4772 }
4773 }
4774 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004775
Guy Benyei11169dd2012-12-18 14:30:41 +00004776 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4777 QualType Jmp_bufType = GetType(Jmp_buf);
4778 if (Jmp_bufType.isNull()) {
4779 Error("jmp_buf type is NULL");
4780 return;
4781 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004782
Guy Benyei11169dd2012-12-18 14:30:41 +00004783 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004784 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 Context.setjmp_bufDecl(Typedef->getDecl());
4786 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004787 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 if (!Tag) {
4789 Error("Invalid jmp_buf type in AST file");
4790 return;
4791 }
4792 Context.setjmp_bufDecl(Tag->getDecl());
4793 }
4794 }
4795 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004796
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4798 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4799 if (Sigjmp_bufType.isNull()) {
4800 Error("sigjmp_buf type is NULL");
4801 return;
4802 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004803
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004805 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004806 Context.setsigjmp_bufDecl(Typedef->getDecl());
4807 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004808 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004809 assert(Tag && "Invalid sigjmp_buf type in AST file");
4810 Context.setsigjmp_bufDecl(Tag->getDecl());
4811 }
4812 }
4813 }
4814
4815 if (unsigned ObjCIdRedef
4816 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4817 if (Context.ObjCIdRedefinitionType.isNull())
4818 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4819 }
4820
4821 if (unsigned ObjCClassRedef
4822 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4823 if (Context.ObjCClassRedefinitionType.isNull())
4824 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4825 }
4826
4827 if (unsigned ObjCSelRedef
4828 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4829 if (Context.ObjCSelRedefinitionType.isNull())
4830 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4831 }
4832
4833 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4834 QualType Ucontext_tType = GetType(Ucontext_t);
4835 if (Ucontext_tType.isNull()) {
4836 Error("ucontext_t type is NULL");
4837 return;
4838 }
4839
4840 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004841 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004842 Context.setucontext_tDecl(Typedef->getDecl());
4843 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004844 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 assert(Tag && "Invalid ucontext_t type in AST file");
4846 Context.setucontext_tDecl(Tag->getDecl());
4847 }
4848 }
4849 }
4850 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004851
Guy Benyei11169dd2012-12-18 14:30:41 +00004852 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4853
4854 // If there were any CUDA special declarations, deserialize them.
4855 if (!CUDASpecialDeclRefs.empty()) {
4856 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4857 Context.setcudaConfigureCallDecl(
4858 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4859 }
Richard Smith56be7542014-03-21 00:33:59 +00004860
Guy Benyei11169dd2012-12-18 14:30:41 +00004861 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004862 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004863 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004864 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004865 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004866 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004867 if (Import.ImportLoc.isValid())
4868 PP.makeModuleVisible(Imported, Import.ImportLoc);
4869 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004870 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004871 }
4872 ImportedModules.clear();
4873}
4874
4875void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004876 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004877}
4878
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004879/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004880/// else returns 0.
4881static ASTFileSignature readASTFileSignature(StringRef PCH) {
4882 BitstreamCursor Stream(PCH);
JF Bastien0e828952019-06-26 19:50:12 +00004883 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4884 // FIXME this drops the error on the floor.
4885 consumeError(std::move(Err));
Vedant Kumar48b4f762018-04-14 01:40:48 +00004886 return ASTFileSignature();
JF Bastien0e828952019-06-26 19:50:12 +00004887 }
Ben Langmuir487ea142014-10-23 18:05:36 +00004888
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004889 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4890 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004891 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004892
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004893 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004894 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004895 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004896 Expected<llvm::BitstreamEntry> MaybeEntry =
4897 Stream.advanceSkippingSubblocks();
4898 if (!MaybeEntry) {
4899 // FIXME this drops the error on the floor.
4900 consumeError(MaybeEntry.takeError());
4901 return ASTFileSignature();
4902 }
4903 llvm::BitstreamEntry Entry = MaybeEntry.get();
4904
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004905 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004906 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004907
4908 Record.clear();
4909 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004910 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4911 if (!MaybeRecord) {
4912 // FIXME this drops the error on the floor.
4913 consumeError(MaybeRecord.takeError());
4914 return ASTFileSignature();
4915 }
4916 if (SIGNATURE == MaybeRecord.get())
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004917 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4918 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004919 }
4920}
4921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004922/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004923/// directly from the AST file, without actually loading the AST
4924/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004925std::string ASTReader::getOriginalSourceFile(
4926 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004927 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004928 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004929 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004930 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004931 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4932 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004933 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004934 }
4935
4936 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004937 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004938
4939 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00004940 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
4941 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004942 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004943 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004944
Chris Lattnere7b154b2013-01-19 21:39:22 +00004945 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004946 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004947 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004948 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004949 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004950
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004951 // Scan for ORIGINAL_FILE inside the control block.
4952 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004953 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00004954 Expected<llvm::BitstreamEntry> MaybeEntry =
4955 Stream.advanceSkippingSubblocks();
4956 if (!MaybeEntry) {
4957 // FIXME this drops errors on the floor.
4958 consumeError(MaybeEntry.takeError());
4959 return std::string();
4960 }
4961 llvm::BitstreamEntry Entry = MaybeEntry.get();
4962
Chris Lattnere7b154b2013-01-19 21:39:22 +00004963 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004964 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004965
Chris Lattnere7b154b2013-01-19 21:39:22 +00004966 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4967 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004968 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004969 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004970
Guy Benyei11169dd2012-12-18 14:30:41 +00004971 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004972 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00004973 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
4974 if (!MaybeRecord) {
4975 // FIXME this drops the errors on the floor.
4976 consumeError(MaybeRecord.takeError());
4977 return std::string();
4978 }
4979 if (ORIGINAL_FILE == MaybeRecord.get())
Chris Lattner0e6c9402013-01-20 02:38:54 +00004980 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004982}
4983
4984namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004985
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 class SimplePCHValidator : public ASTReaderListener {
4987 const LangOptions &ExistingLangOpts;
4988 const TargetOptions &ExistingTargetOpts;
4989 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004990 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004992
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 public:
4994 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4995 const TargetOptions &ExistingTargetOpts,
4996 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004997 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 FileManager &FileMgr)
4999 : ExistingLangOpts(ExistingLangOpts),
5000 ExistingTargetOpts(ExistingTargetOpts),
5001 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005002 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005003 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005004
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005005 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
5006 bool AllowCompatibleDifferences) override {
5007 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
5008 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005010
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005011 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
5012 bool AllowCompatibleDifferences) override {
5013 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
5014 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005015 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005016
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005017 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
5018 StringRef SpecificModuleCachePath,
5019 bool Complain) override {
5020 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5021 ExistingModuleCachePath,
5022 nullptr, ExistingLangOpts);
5023 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005024
Craig Topper3e89dfe2014-03-13 02:13:41 +00005025 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
5026 bool Complain,
5027 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00005028 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005029 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 }
5031 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005032
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005033} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005034
Adrian Prantlbb165fb2015-06-20 18:53:08 +00005035bool ASTReader::readASTFileControlBlock(
5036 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005037 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005038 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00005039 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005040 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00005041 // FIXME: This allows use of the VFS; we do not allow use of the
5042 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00005043 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 if (!Buffer) {
5045 return true;
5046 }
5047
5048 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005049 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
5050 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00005051
5052 // Sniff for the signature.
JF Bastien0e828952019-06-26 19:50:12 +00005053 if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
5054 consumeError(std::move(Err)); // FIXME this drops errors on the floor.
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005057
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005058 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005059 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005060 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005061
5062 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00005063 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00005064 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005065 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005066
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005068 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005069 bool DoneWithControlBlock = false;
5070 while (!DoneWithControlBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005071 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5072 if (!MaybeEntry) {
5073 // FIXME this drops the error on the floor.
5074 consumeError(MaybeEntry.takeError());
5075 return true;
5076 }
5077 llvm::BitstreamEntry Entry = MaybeEntry.get();
Richard Smith0516b182015-09-08 19:40:14 +00005078
5079 switch (Entry.Kind) {
5080 case llvm::BitstreamEntry::SubBlock: {
5081 switch (Entry.ID) {
5082 case OPTIONS_BLOCK_ID: {
5083 std::string IgnoredSuggestedPredefines;
5084 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
5085 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005086 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00005087 return true;
5088 break;
5089 }
5090
5091 case INPUT_FILES_BLOCK_ID:
5092 InputFilesCursor = Stream;
JF Bastien0e828952019-06-26 19:50:12 +00005093 if (llvm::Error Err = Stream.SkipBlock()) {
5094 // FIXME this drops the error on the floor.
5095 consumeError(std::move(Err));
5096 return true;
5097 }
5098 if (NeedsInputFiles &&
5099 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
Richard Smith0516b182015-09-08 19:40:14 +00005100 return true;
5101 break;
5102
5103 default:
JF Bastien0e828952019-06-26 19:50:12 +00005104 if (llvm::Error Err = Stream.SkipBlock()) {
5105 // FIXME this drops the error on the floor.
5106 consumeError(std::move(Err));
Richard Smith0516b182015-09-08 19:40:14 +00005107 return true;
JF Bastien0e828952019-06-26 19:50:12 +00005108 }
Richard Smith0516b182015-09-08 19:40:14 +00005109 break;
5110 }
5111
5112 continue;
5113 }
5114
5115 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005116 DoneWithControlBlock = true;
5117 break;
Richard Smith0516b182015-09-08 19:40:14 +00005118
5119 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005120 return true;
Richard Smith0516b182015-09-08 19:40:14 +00005121
5122 case llvm::BitstreamEntry::Record:
5123 break;
5124 }
5125
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005126 if (DoneWithControlBlock) break;
5127
Guy Benyei11169dd2012-12-18 14:30:41 +00005128 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005129 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005130 Expected<unsigned> MaybeRecCode =
5131 Stream.readRecord(Entry.ID, Record, &Blob);
5132 if (!MaybeRecCode) {
5133 // FIXME this drops the error.
5134 return Failure;
5135 }
5136 switch ((ControlRecordTypes)MaybeRecCode.get()) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005137 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005138 if (Record[0] != VERSION_MAJOR)
5139 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00005140 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005141 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005142 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005143 case MODULE_NAME:
5144 Listener.ReadModuleName(Blob);
5145 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005146 case MODULE_DIRECTORY:
5147 ModuleDir = Blob;
5148 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005149 case MODULE_MAP_FILE: {
5150 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00005151 auto Path = ReadString(Record, Idx);
5152 ResolveImportedPath(Path, ModuleDir);
5153 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00005154 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00005155 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005156 case INPUT_FILE_OFFSETS: {
5157 if (!NeedsInputFiles)
5158 break;
5159
5160 unsigned NumInputFiles = Record[0];
5161 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00005162 const llvm::support::unaligned_uint64_t *InputFileOffs =
5163 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005164 for (unsigned I = 0; I != NumInputFiles; ++I) {
5165 // Go find this input file.
5166 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00005167
5168 if (isSystemFile && !NeedsSystemInputFiles)
5169 break; // the rest are system input files
5170
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005171 BitstreamCursor &Cursor = InputFilesCursor;
5172 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00005173 if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
5174 // FIXME this drops errors on the floor.
5175 consumeError(std::move(Err));
5176 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005177
JF Bastien0e828952019-06-26 19:50:12 +00005178 Expected<unsigned> MaybeCode = Cursor.ReadCode();
5179 if (!MaybeCode) {
5180 // FIXME this drops errors on the floor.
5181 consumeError(MaybeCode.takeError());
5182 }
5183 unsigned Code = MaybeCode.get();
5184
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005185 RecordData Record;
5186 StringRef Blob;
5187 bool shouldContinue = false;
JF Bastien0e828952019-06-26 19:50:12 +00005188 Expected<unsigned> MaybeRecordType =
5189 Cursor.readRecord(Code, Record, &Blob);
5190 if (!MaybeRecordType) {
5191 // FIXME this drops errors on the floor.
5192 consumeError(MaybeRecordType.takeError());
5193 }
5194 switch ((InputFileRecordTypes)MaybeRecordType.get()) {
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005195 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00005196 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005197 std::string Filename = Blob;
5198 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00005199 shouldContinue = Listener.visitInputFile(
5200 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00005201 break;
5202 }
5203 if (!shouldContinue)
5204 break;
5205 }
5206 break;
5207 }
5208
Richard Smithd4b230b2014-10-27 23:01:16 +00005209 case IMPORTS: {
5210 if (!NeedsImports)
5211 break;
5212
5213 unsigned Idx = 0, N = Record.size();
5214 while (Idx < N) {
5215 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005216 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
5217 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00005218 std::string Filename = ReadString(Record, Idx);
5219 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00005220 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00005221 }
5222 break;
5223 }
5224
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005225 default:
5226 // No other validation to perform.
5227 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 }
5229 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005230
5231 // Look for module file extension blocks, if requested.
5232 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005233 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005234 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
5235 bool DoneWithExtensionBlock = false;
5236 while (!DoneWithExtensionBlock) {
JF Bastien0e828952019-06-26 19:50:12 +00005237 Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5238 if (!MaybeEntry) {
5239 // FIXME this drops the error.
5240 return true;
5241 }
5242 llvm::BitstreamEntry Entry = MaybeEntry.get();
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005243
JF Bastien0e828952019-06-26 19:50:12 +00005244 switch (Entry.Kind) {
5245 case llvm::BitstreamEntry::SubBlock:
5246 if (llvm::Error Err = Stream.SkipBlock()) {
5247 // FIXME this drops the error on the floor.
5248 consumeError(std::move(Err));
5249 return true;
5250 }
5251 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005252
JF Bastien0e828952019-06-26 19:50:12 +00005253 case llvm::BitstreamEntry::EndBlock:
5254 DoneWithExtensionBlock = true;
5255 continue;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005256
JF Bastien0e828952019-06-26 19:50:12 +00005257 case llvm::BitstreamEntry::Error:
5258 return true;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005259
JF Bastien0e828952019-06-26 19:50:12 +00005260 case llvm::BitstreamEntry::Record:
5261 break;
5262 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005263
5264 Record.clear();
5265 StringRef Blob;
JF Bastien0e828952019-06-26 19:50:12 +00005266 Expected<unsigned> MaybeRecCode =
5267 Stream.readRecord(Entry.ID, Record, &Blob);
5268 if (!MaybeRecCode) {
5269 // FIXME this drops the error.
5270 return true;
5271 }
5272 switch (MaybeRecCode.get()) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005273 case EXTENSION_METADATA: {
5274 ModuleFileExtensionMetadata Metadata;
5275 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
5276 return true;
5277
5278 Listener.readModuleFileExtension(Metadata);
5279 break;
5280 }
5281 }
5282 }
5283 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005284 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005285 }
5286
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00005287 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
5288 if (readUnhashedControlBlockImpl(
5289 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
5290 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
5291 ValidateDiagnosticOptions) != Success)
5292 return true;
5293
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005294 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00005295}
5296
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00005297bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
5298 const PCHContainerReader &PCHContainerRdr,
5299 const LangOptions &LangOpts,
5300 const TargetOptions &TargetOpts,
5301 const PreprocessorOptions &PPOpts,
5302 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005303 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
5304 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00005305 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00005306 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00005307 validator,
5308 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005309}
5310
Ben Langmuir2c9af442014-04-10 17:57:43 +00005311ASTReader::ASTReadResult
5312ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005313 // Enter the submodule block.
JF Bastien0e828952019-06-26 19:50:12 +00005314 if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
5315 Error(std::move(Err));
Ben Langmuir2c9af442014-04-10 17:57:43 +00005316 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 }
5318
5319 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
5320 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00005321 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 RecordData Record;
5323 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00005324 Expected<llvm::BitstreamEntry> MaybeEntry =
5325 F.Stream.advanceSkippingSubblocks();
5326 if (!MaybeEntry) {
5327 Error(MaybeEntry.takeError());
5328 return Failure;
5329 }
5330 llvm::BitstreamEntry Entry = MaybeEntry.get();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005331
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005332 switch (Entry.Kind) {
5333 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
5334 case llvm::BitstreamEntry::Error:
5335 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005336 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005337 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00005338 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005339 case llvm::BitstreamEntry::Record:
5340 // The interesting case.
5341 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005342 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005343
Guy Benyei11169dd2012-12-18 14:30:41 +00005344 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00005345 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00005347 Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
5348 if (!MaybeKind) {
5349 Error(MaybeKind.takeError());
5350 return Failure;
5351 }
5352 unsigned Kind = MaybeKind.get();
Richard Smith03478d92014-10-23 22:12:14 +00005353
5354 if ((Kind == SUBMODULE_METADATA) != First) {
5355 Error("submodule metadata record should be at beginning of block");
5356 return Failure;
5357 }
5358 First = false;
5359
5360 // Submodule information is only valid if we have a current module.
5361 // FIXME: Should we error on these cases?
5362 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5363 Kind != SUBMODULE_DEFINITION)
5364 continue;
5365
5366 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 default: // Default behavior: ignore.
5368 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005369
Richard Smith03478d92014-10-23 22:12:14 +00005370 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005371 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005373 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005374 }
Richard Smith03478d92014-10-23 22:12:14 +00005375
Chris Lattner0e6c9402013-01-20 02:38:54 +00005376 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005377 unsigned Idx = 0;
5378 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5379 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005380 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005381 bool IsFramework = Record[Idx++];
5382 bool IsExplicit = Record[Idx++];
5383 bool IsSystem = Record[Idx++];
5384 bool IsExternC = Record[Idx++];
5385 bool InferSubmodules = Record[Idx++];
5386 bool InferExplicitSubmodules = Record[Idx++];
5387 bool InferExportWildcard = Record[Idx++];
5388 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005389 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005390
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005391 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005392 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005394
Guy Benyei11169dd2012-12-18 14:30:41 +00005395 // Retrieve this (sub)module from the module map, creating it if
5396 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005397 CurrentModule =
5398 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5399 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005400
5401 // FIXME: set the definition loc for CurrentModule, or call
5402 // ModMap.setInferredModuleAllowedBy()
5403
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5405 if (GlobalIndex >= SubmodulesLoaded.size() ||
5406 SubmodulesLoaded[GlobalIndex]) {
5407 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005408 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005410
Douglas Gregor7029ce12013-03-19 00:28:20 +00005411 if (!ParentModule) {
5412 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005413 // Don't emit module relocation error if we have -fno-validate-pch
5414 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5415 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005416 if (!Diags.isDiagnosticInFlight()) {
5417 Diag(diag::err_module_file_conflict)
5418 << CurrentModule->getTopLevelModuleName()
5419 << CurFile->getName()
5420 << F.File->getName();
5421 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005422 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005423 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005424 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005425
5426 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005427 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005428 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005429
Richard Smithdd8b5332017-09-04 05:37:53 +00005430 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005431 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005432 CurrentModule->IsFromModuleFile = true;
5433 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005434 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005435 CurrentModule->InferSubmodules = InferSubmodules;
5436 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5437 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005438 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005439 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005440 if (DeserializationListener)
5441 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005442
Guy Benyei11169dd2012-12-18 14:30:41 +00005443 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005444
Richard Smith8a3e39a2016-03-28 21:31:09 +00005445 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005446 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005447 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005448 CurrentModule->UnresolvedConflicts.clear();
5449 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005450
5451 // The module is available unless it's missing a requirement; relevant
5452 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5453 // Missing headers that were present when the module was built do not
5454 // make it unavailable -- if we got this far, this must be an explicitly
5455 // imported module file.
5456 CurrentModule->Requirements.clear();
5457 CurrentModule->MissingHeaders.clear();
5458 CurrentModule->IsMissingRequirement =
5459 ParentModule && ParentModule->IsMissingRequirement;
5460 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005461 break;
5462 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005463
Guy Benyei11169dd2012-12-18 14:30:41 +00005464 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005465 std::string Filename = Blob;
5466 ResolveImportedPath(F, Filename);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005467 if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005468 if (!CurrentModule->getUmbrellaHeader())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005469 ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob);
5470 else if (CurrentModule->getUmbrellaHeader().Entry != *Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005471 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5472 Error("mismatched umbrella headers in submodule");
5473 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005474 }
5475 }
5476 break;
5477 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005478
Richard Smith202210b2014-10-24 20:23:01 +00005479 case SUBMODULE_HEADER:
5480 case SUBMODULE_EXCLUDED_HEADER:
5481 case SUBMODULE_PRIVATE_HEADER:
5482 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005483 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5484 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005485 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005486
Richard Smith202210b2014-10-24 20:23:01 +00005487 case SUBMODULE_TEXTUAL_HEADER:
5488 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5489 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5490 // them here.
5491 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005492
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005493 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005494 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005495 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005496
5497 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005498 std::string Dirname = Blob;
5499 ResolveImportedPath(F, Dirname);
Harlan Haskins8d323d12019-08-01 21:31:56 +00005500 if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005501 if (!CurrentModule->getUmbrellaDir())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005502 ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob);
5503 else if (CurrentModule->getUmbrellaDir().Entry != *Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005504 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5505 Error("mismatched umbrella directories in submodule");
5506 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005507 }
5508 }
5509 break;
5510 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005511
Guy Benyei11169dd2012-12-18 14:30:41 +00005512 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 F.BaseSubmoduleID = getTotalNumSubmodules();
5514 F.LocalNumSubmodules = Record[0];
5515 unsigned LocalBaseSubmoduleID = Record[1];
5516 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005517 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005518 // module.
5519 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005520
5521 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005522 // module.
5523 F.SubmoduleRemap.insertOrReplace(
5524 std::make_pair(LocalBaseSubmoduleID,
5525 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005526
Ben Langmuir52ca6782014-10-20 16:27:32 +00005527 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005529 break;
5530 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005531
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005532 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005533 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005534 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005535 Unresolved.File = &F;
5536 Unresolved.Mod = CurrentModule;
5537 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005538 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005540 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005541 }
5542 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005543
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005544 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005545 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005546 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005547 Unresolved.File = &F;
5548 Unresolved.Mod = CurrentModule;
5549 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005550 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005551 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005552 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005553 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005554
5555 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005556 // the parsed, unresolved exports around.
5557 CurrentModule->UnresolvedExports.clear();
5558 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005559
5560 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005561 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5562 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005563 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005564
5565 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005566 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005567 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005568 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005569 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005570
5571 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005572 CurrentModule->ConfigMacros.push_back(Blob.str());
5573 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005574
5575 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005576 UnresolvedModuleRef Unresolved;
5577 Unresolved.File = &F;
5578 Unresolved.Mod = CurrentModule;
5579 Unresolved.ID = Record[0];
5580 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5581 Unresolved.IsWildcard = false;
5582 Unresolved.String = Blob;
5583 UnresolvedModuleRefs.push_back(Unresolved);
5584 break;
5585 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005586
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005587 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005588 if (!ContextObj)
5589 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005590 SmallVector<uint32_t, 16> Inits;
5591 for (auto &ID : Record)
5592 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005593 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005594 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005595 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005596
5597 case SUBMODULE_EXPORT_AS:
5598 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005599 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005600 break;
5601 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005602 }
5603}
5604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005605/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005606/// structure.
5607///
5608/// This routine parses the language options from the AST file and then gives
5609/// them to the AST listener if one is set.
5610///
5611/// \returns true if the listener deems the file unacceptable, false otherwise.
5612bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5613 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005614 ASTReaderListener &Listener,
5615 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 LangOptions LangOpts;
5617 unsigned Idx = 0;
5618#define LANGOPT(Name, Bits, Default, Description) \
5619 LangOpts.Name = Record[Idx++];
5620#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5621 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5622#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005623#define SANITIZER(NAME, ID) \
5624 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005625#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005626
Ben Langmuircd98cb72015-06-23 18:20:18 +00005627 for (unsigned N = Record[Idx++]; N; --N)
5628 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5629
Vedant Kumar48b4f762018-04-14 01:40:48 +00005630 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005631 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5632 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005633
Ben Langmuird4a667a2015-06-23 18:20:23 +00005634 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005635
5636 // Comment options.
5637 for (unsigned N = Record[Idx++]; N; --N) {
5638 LangOpts.CommentOpts.BlockCommandNames.push_back(
5639 ReadString(Record, Idx));
5640 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005641 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005642
Samuel Antaoee8fb302016-01-06 13:42:12 +00005643 // OpenMP offloading options.
5644 for (unsigned N = Record[Idx++]; N; --N) {
5645 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5646 }
5647
5648 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5649
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005650 return Listener.ReadLanguageOptions(LangOpts, Complain,
5651 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005652}
5653
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005654bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5655 ASTReaderListener &Listener,
5656 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005657 unsigned Idx = 0;
5658 TargetOptions TargetOpts;
5659 TargetOpts.Triple = ReadString(Record, Idx);
5660 TargetOpts.CPU = ReadString(Record, Idx);
5661 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 for (unsigned N = Record[Idx++]; N; --N) {
5663 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5664 }
5665 for (unsigned N = Record[Idx++]; N; --N) {
5666 TargetOpts.Features.push_back(ReadString(Record, Idx));
5667 }
5668
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005669 return Listener.ReadTargetOptions(TargetOpts, Complain,
5670 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005671}
5672
5673bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5674 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005675 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005676 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005677#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005678#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005679 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005680#include "clang/Basic/DiagnosticOptions.def"
5681
Richard Smith3be1cb22014-08-07 00:24:21 +00005682 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005683 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005684 for (unsigned N = Record[Idx++]; N; --N)
5685 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005686
5687 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5688}
5689
5690bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5691 ASTReaderListener &Listener) {
5692 FileSystemOptions FSOpts;
5693 unsigned Idx = 0;
5694 FSOpts.WorkingDir = ReadString(Record, Idx);
5695 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5696}
5697
5698bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5699 bool Complain,
5700 ASTReaderListener &Listener) {
5701 HeaderSearchOptions HSOpts;
5702 unsigned Idx = 0;
5703 HSOpts.Sysroot = ReadString(Record, Idx);
5704
5705 // Include entries.
5706 for (unsigned N = Record[Idx++]; N; --N) {
5707 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005708 frontend::IncludeDirGroup Group
5709 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005710 bool IsFramework = Record[Idx++];
5711 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005712 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5713 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005714 }
5715
5716 // System header prefixes.
5717 for (unsigned N = Record[Idx++]; N; --N) {
5718 std::string Prefix = ReadString(Record, Idx);
5719 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005720 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005721 }
5722
5723 HSOpts.ResourceDir = ReadString(Record, Idx);
5724 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005725 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005726 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005727 HSOpts.ImplicitModuleMaps = Record[Idx++];
5728 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005729 HSOpts.UseBuiltinIncludes = Record[Idx++];
5730 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5731 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5732 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005733 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005734
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005735 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5736 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005737}
5738
5739bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5740 bool Complain,
5741 ASTReaderListener &Listener,
5742 std::string &SuggestedPredefines) {
5743 PreprocessorOptions PPOpts;
5744 unsigned Idx = 0;
5745
5746 // Macro definitions/undefs
5747 for (unsigned N = Record[Idx++]; N; --N) {
5748 std::string Macro = ReadString(Record, Idx);
5749 bool IsUndef = Record[Idx++];
5750 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5751 }
5752
5753 // Includes
5754 for (unsigned N = Record[Idx++]; N; --N) {
5755 PPOpts.Includes.push_back(ReadString(Record, Idx));
5756 }
5757
5758 // Macro Includes
5759 for (unsigned N = Record[Idx++]; N; --N) {
5760 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5761 }
5762
5763 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005764 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005765 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005766 PPOpts.ObjCXXARCStandardLibrary =
5767 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5768 SuggestedPredefines.clear();
5769 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5770 SuggestedPredefines);
5771}
5772
5773std::pair<ModuleFile *, unsigned>
5774ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5775 GlobalPreprocessedEntityMapType::iterator
5776 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005777 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 "Corrupted global preprocessed entity map");
5779 ModuleFile *M = I->second;
5780 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5781 return std::make_pair(M, LocalIndex);
5782}
5783
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005784llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005785ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5786 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5787 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5788 Mod.NumPreprocessedEntities);
5789
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005790 return llvm::make_range(PreprocessingRecord::iterator(),
5791 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005792}
5793
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005794llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005795ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005796 return llvm::make_range(
5797 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5798 ModuleDeclIterator(this, &Mod,
5799 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005800}
5801
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005802SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5803 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5804 assert(I != GlobalSkippedRangeMap.end() &&
5805 "Corrupted global skipped range map");
5806 ModuleFile *M = I->second;
5807 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5808 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5809 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5810 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5811 TranslateSourceLocation(*M, RawRange.getEnd()));
5812 assert(Range.isValid());
5813 return Range;
5814}
5815
Guy Benyei11169dd2012-12-18 14:30:41 +00005816PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5817 PreprocessedEntityID PPID = Index+1;
5818 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5819 ModuleFile &M = *PPInfo.first;
5820 unsigned LocalIndex = PPInfo.second;
5821 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5822
Guy Benyei11169dd2012-12-18 14:30:41 +00005823 if (!PP.getPreprocessingRecord()) {
5824 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005825 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005826 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005827
5828 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
JF Bastien0e828952019-06-26 19:50:12 +00005829 if (llvm::Error Err =
5830 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset)) {
5831 Error(std::move(Err));
5832 return nullptr;
5833 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005834
JF Bastien0e828952019-06-26 19:50:12 +00005835 Expected<llvm::BitstreamEntry> MaybeEntry =
5836 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5837 if (!MaybeEntry) {
5838 Error(MaybeEntry.takeError());
5839 return nullptr;
5840 }
5841 llvm::BitstreamEntry Entry = MaybeEntry.get();
5842
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005843 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005844 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005845
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005847 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5848 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005849 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005850 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005851 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00005852 Expected<unsigned> MaybeRecType =
5853 M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
5854 if (!MaybeRecType) {
5855 Error(MaybeRecType.takeError());
5856 return nullptr;
5857 }
5858 switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005859 case PPD_MACRO_EXPANSION: {
5860 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005861 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005862 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005863 if (isBuiltin)
5864 Name = getLocalIdentifier(M, Record[1]);
5865 else {
Richard Smith66a81862015-05-04 02:25:31 +00005866 PreprocessedEntityID GlobalID =
5867 getGlobalPreprocessedEntityID(M, Record[1]);
5868 Def = cast<MacroDefinitionRecord>(
5869 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005870 }
5871
5872 MacroExpansion *ME;
5873 if (isBuiltin)
5874 ME = new (PPRec) MacroExpansion(Name, Range);
5875 else
5876 ME = new (PPRec) MacroExpansion(Def, Range);
5877
5878 return ME;
5879 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005880
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 case PPD_MACRO_DEFINITION: {
5882 // Decode the identifier info and then check again; if the macro is
5883 // still defined and associated with the identifier,
5884 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005885 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005886
5887 if (DeserializationListener)
5888 DeserializationListener->MacroDefinitionRead(PPID, MD);
5889
5890 return MD;
5891 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005892
Guy Benyei11169dd2012-12-18 14:30:41 +00005893 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005894 const char *FullFileNameStart = Blob.data() + Record[0];
5895 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005896 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005897 if (!FullFileName.empty())
Harlan Haskins8d323d12019-08-01 21:31:56 +00005898 if (auto FE = PP.getFileManager().getFile(FullFileName))
5899 File = *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005900
Guy Benyei11169dd2012-12-18 14:30:41 +00005901 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005902 InclusionDirective::InclusionKind Kind
5903 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5904 InclusionDirective *ID
5905 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005906 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 Record[1], Record[3],
5908 File,
5909 Range);
5910 return ID;
5911 }
5912 }
5913
5914 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5915}
5916
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005917/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005918/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005919///
5920/// \param SLocMapI points at a chunk of a module that contains no
5921/// preprocessed entities or the entities it contains are not the ones we are
5922/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005923PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5924 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5925 ++SLocMapI;
5926 for (GlobalSLocOffsetMapType::const_iterator
5927 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5928 ModuleFile &M = *SLocMapI->second;
5929 if (M.NumPreprocessedEntities)
5930 return M.BasePreprocessedEntityID;
5931 }
5932
5933 return getTotalNumPreprocessedEntities();
5934}
5935
5936namespace {
5937
Guy Benyei11169dd2012-12-18 14:30:41 +00005938struct PPEntityComp {
5939 const ASTReader &Reader;
5940 ModuleFile &M;
5941
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005942 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005943
5944 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5945 SourceLocation LHS = getLoc(L);
5946 SourceLocation RHS = getLoc(R);
5947 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5948 }
5949
5950 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5951 SourceLocation LHS = getLoc(L);
5952 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5953 }
5954
5955 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5956 SourceLocation RHS = getLoc(R);
5957 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5958 }
5959
5960 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005961 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005962 }
5963};
5964
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005965} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005966
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005967PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5968 bool EndsAfter) const {
5969 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005970 return getTotalNumPreprocessedEntities();
5971
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005972 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5973 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005974 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5975 "Corrupted global sloc offset map");
5976
5977 if (SLocMapI->second->NumPreprocessedEntities == 0)
5978 return findNextPreprocessedEntity(SLocMapI);
5979
5980 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005981
5982 using pp_iterator = const PPEntityOffset *;
5983
Guy Benyei11169dd2012-12-18 14:30:41 +00005984 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5985 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5986
5987 size_t Count = M.NumPreprocessedEntities;
5988 size_t Half;
5989 pp_iterator First = pp_begin;
5990 pp_iterator PPI;
5991
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005992 if (EndsAfter) {
5993 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005994 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005995 } else {
5996 // Do a binary search manually instead of using std::lower_bound because
5997 // The end locations of entities may be unordered (when a macro expansion
5998 // is inside another macro argument), but for this case it is not important
5999 // whether we get the first macro expansion or its containing macro.
6000 while (Count > 0) {
6001 Half = Count / 2;
6002 PPI = First;
6003 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00006004 if (SourceMgr.isBeforeInTranslationUnit(
6005 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006006 First = PPI;
6007 ++First;
6008 Count = Count - Half - 1;
6009 } else
6010 Count = Half;
6011 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006012 }
6013
6014 if (PPI == pp_end)
6015 return findNextPreprocessedEntity(SLocMapI);
6016
6017 return M.BasePreprocessedEntityID + (PPI - pp_begin);
6018}
6019
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006020/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00006021/// preprocessed entities that \arg Range encompasses.
6022std::pair<unsigned, unsigned>
6023 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
6024 if (Range.isInvalid())
6025 return std::make_pair(0,0);
6026 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
6027
Alp Toker2e9ce4c2014-05-16 18:59:21 +00006028 PreprocessedEntityID BeginID =
6029 findPreprocessedEntity(Range.getBegin(), false);
6030 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00006031 return std::make_pair(BeginID, EndID);
6032}
6033
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006034/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00006035/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00006036Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00006037 FileID FID) {
6038 if (FID.isInvalid())
6039 return false;
6040
6041 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
6042 ModuleFile &M = *PPInfo.first;
6043 unsigned LocalIndex = PPInfo.second;
6044 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006045
Richard Smithcb34bd32016-03-27 07:28:06 +00006046 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00006047 if (Loc.isInvalid())
6048 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006049
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
6051 return true;
6052 else
6053 return false;
6054}
6055
6056namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006057
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006058 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00006060 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00006061 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006062
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006064 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006065
6066 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006067 HeaderFileInfoLookupTable *Table
6068 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00006069 if (!Table)
6070 return false;
6071
6072 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00006073 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00006074 if (Pos == Table->end())
6075 return false;
6076
Richard Smithbdf2d932015-07-30 03:37:16 +00006077 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 return true;
6079 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006080
David Blaikie05785d12013-02-20 22:23:23 +00006081 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00006082 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006083
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006084} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006085
6086HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00006087 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00006088 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00006089 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00006090 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092 return HeaderFileInfo();
6093}
6094
6095void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00006096 using DiagState = DiagnosticsEngine::DiagState;
6097 SmallVector<DiagState *, 32> DiagStates;
6098
Vedant Kumar48b4f762018-04-14 01:40:48 +00006099 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006100 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00006101 auto &Record = F.PragmaDiagMappings;
6102 if (Record.empty())
6103 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006104
Richard Smithd230de22017-01-26 01:01:01 +00006105 DiagStates.clear();
6106
6107 auto ReadDiagState =
6108 [&](const DiagState &BasedOn, SourceLocation Loc,
6109 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
6110 unsigned BackrefID = Record[Idx++];
6111 if (BackrefID != 0)
6112 return DiagStates[BackrefID - 1];
6113
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00006115 Diag.DiagStates.push_back(BasedOn);
6116 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00006117 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00006118 unsigned Size = Record[Idx++];
6119 assert(Idx + Size * 2 <= Record.size() &&
6120 "Invalid data, not enough diag/map pairs");
6121 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00006122 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006123 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00006124 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006125 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
6126 continue;
6127
6128 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
6129
6130 // If this mapping was specified as a warning but the severity was
6131 // upgraded due to diagnostic settings, simulate the current diagnostic
6132 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00006133 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
6134 NewMapping.setSeverity(diag::Severity::Warning);
6135 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006136 }
6137
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006138 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00006139 }
Richard Smithd230de22017-01-26 01:01:01 +00006140 return NewState;
6141 };
6142
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006143 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006144 DiagState *FirstState;
6145 if (F.Kind == MK_ImplicitModule) {
6146 // Implicitly-built modules are reused with different diagnostic
6147 // settings. Use the initial diagnostic state from Diag to simulate this
6148 // compilation's diagnostic settings.
6149 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
6150 DiagStates.push_back(FirstState);
6151
6152 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00006153 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006154 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006155 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006156 assert(Idx < Record.size() &&
6157 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00006158 } else if (F.isModule()) {
6159 // For an explicit module, preserve the flags from the module build
6160 // command line (-w, -Weverything, -Werror, ...) along with any explicit
6161 // -Wblah flags.
6162 unsigned Flags = Record[Idx++];
6163 DiagState Initial;
6164 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
6165 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
6166 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
6167 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
6168 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
6169 Initial.ExtBehavior = (diag::Severity)Flags;
6170 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00006171
Richard Smith6c2b5a82018-02-09 01:15:13 +00006172 assert(F.OriginalSourceFileID.isValid());
6173
Richard Smithe37391c2017-05-03 00:28:49 +00006174 // Set up the root buffer of the module to start with the initial
6175 // diagnostic state of the module itself, to cover files that contain no
6176 // explicit transitions (for which we did not serialize anything).
6177 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
6178 .StateTransitions.push_back({FirstState, 0});
6179 } else {
6180 // For prefix ASTs, start with whatever the user configured on the
6181 // command line.
6182 Idx++; // Skip flags.
6183 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
6184 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00006185 }
Richard Smithd230de22017-01-26 01:01:01 +00006186
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006187 // Read the state transitions.
6188 unsigned NumLocations = Record[Idx++];
6189 while (NumLocations--) {
6190 assert(Idx < Record.size() &&
6191 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00006192 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
6193 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00006194 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00006195 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
6196 unsigned Transitions = Record[Idx++];
6197
6198 // Note that we don't need to set up Parent/ParentOffset here, because
6199 // we won't be changing the diagnostic state within imported FileIDs
6200 // (other than perhaps appending to the main source file, which has no
6201 // parent).
6202 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
6203 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
6204 for (unsigned I = 0; I != Transitions; ++I) {
6205 unsigned Offset = Record[Idx++];
6206 auto *State =
6207 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
6208 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00006209 }
6210 }
Richard Smithd230de22017-01-26 01:01:01 +00006211
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006212 // Read the final state.
6213 assert(Idx < Record.size() &&
6214 "Invalid data, missing final pragma diagnostic state");
6215 SourceLocation CurStateLoc =
6216 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
6217 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
6218
6219 if (!F.isModule()) {
6220 Diag.DiagStatesByLoc.CurDiagState = CurState;
6221 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
6222
6223 // Preserve the property that the imaginary root file describes the
6224 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00006225 FileID NullFile;
6226 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00006227 if (T.empty())
6228 T.push_back({CurState, 0});
6229 else
6230 T[0].State = CurState;
6231 }
6232
Richard Smithd230de22017-01-26 01:01:01 +00006233 // Don't try to read these mappings again.
6234 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 }
6236}
6237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006238/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00006239ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
6240 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
6241 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
6242 ModuleFile *M = I->second;
6243 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
6244}
6245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006246/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00006247///
6248/// The index is the type ID, shifted and minus the number of predefs. This
6249/// routine actually reads the record corresponding to the type at the given
6250/// location. It is a helper routine for GetType, which deals with reading type
6251/// IDs.
6252QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006253 assert(ContextObj && "reading type with no AST context");
6254 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00006255 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006256 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006257
6258 // Keep track of where we are in the stream, then jump back there
6259 // after reading this type.
6260 SavedStreamPosition SavedPosition(DeclsCursor);
6261
6262 ReadingKindTracker ReadingKind(Read_Type, *this);
6263
6264 // Note that we are loading a type record.
6265 Deserializing AType(this);
6266
6267 unsigned Idx = 0;
JF Bastien0e828952019-06-26 19:50:12 +00006268 if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
6269 Error(std::move(Err));
6270 return QualType();
6271 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00006273 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
6274 if (!MaybeCode) {
6275 Error(MaybeCode.takeError());
6276 return QualType();
6277 }
6278 unsigned Code = MaybeCode.get();
6279
6280 Expected<unsigned> MaybeTypeCode = DeclsCursor.readRecord(Code, Record);
6281 if (!MaybeTypeCode) {
6282 Error(MaybeTypeCode.takeError());
6283 return QualType();
6284 }
6285 switch ((TypeCode)MaybeTypeCode.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006286 case TYPE_EXT_QUAL: {
6287 if (Record.size() != 2) {
6288 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006289 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 }
6291 QualType Base = readType(*Loc.F, Record, Idx);
6292 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
6293 return Context.getQualifiedType(Base, Quals);
6294 }
6295
6296 case TYPE_COMPLEX: {
6297 if (Record.size() != 1) {
6298 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006299 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 }
6301 QualType ElemType = readType(*Loc.F, Record, Idx);
6302 return Context.getComplexType(ElemType);
6303 }
6304
6305 case TYPE_POINTER: {
6306 if (Record.size() != 1) {
6307 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006308 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 }
6310 QualType PointeeType = readType(*Loc.F, Record, Idx);
6311 return Context.getPointerType(PointeeType);
6312 }
6313
Reid Kleckner8a365022013-06-24 17:51:48 +00006314 case TYPE_DECAYED: {
6315 if (Record.size() != 1) {
6316 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006317 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00006318 }
6319 QualType OriginalType = readType(*Loc.F, Record, Idx);
6320 QualType DT = Context.getAdjustedParameterType(OriginalType);
6321 if (!isa<DecayedType>(DT))
6322 Error("Decayed type does not decay");
6323 return DT;
6324 }
6325
Reid Kleckner0503a872013-12-05 01:23:43 +00006326 case TYPE_ADJUSTED: {
6327 if (Record.size() != 2) {
6328 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006329 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00006330 }
6331 QualType OriginalTy = readType(*Loc.F, Record, Idx);
6332 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
6333 return Context.getAdjustedType(OriginalTy, AdjustedTy);
6334 }
6335
Guy Benyei11169dd2012-12-18 14:30:41 +00006336 case TYPE_BLOCK_POINTER: {
6337 if (Record.size() != 1) {
6338 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006339 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006340 }
6341 QualType PointeeType = readType(*Loc.F, Record, Idx);
6342 return Context.getBlockPointerType(PointeeType);
6343 }
6344
6345 case TYPE_LVALUE_REFERENCE: {
6346 if (Record.size() != 2) {
6347 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006348 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006349 }
6350 QualType PointeeType = readType(*Loc.F, Record, Idx);
6351 return Context.getLValueReferenceType(PointeeType, Record[1]);
6352 }
6353
6354 case TYPE_RVALUE_REFERENCE: {
6355 if (Record.size() != 1) {
6356 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006357 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006358 }
6359 QualType PointeeType = readType(*Loc.F, Record, Idx);
6360 return Context.getRValueReferenceType(PointeeType);
6361 }
6362
6363 case TYPE_MEMBER_POINTER: {
6364 if (Record.size() != 2) {
6365 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006366 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006367 }
6368 QualType PointeeType = readType(*Loc.F, Record, Idx);
6369 QualType ClassType = readType(*Loc.F, Record, Idx);
6370 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006371 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006372
Guy Benyei11169dd2012-12-18 14:30:41 +00006373 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
6374 }
6375
6376 case TYPE_CONSTANT_ARRAY: {
6377 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006378 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006379 unsigned IndexTypeQuals = Record[2];
6380 unsigned Idx = 3;
6381 llvm::APInt Size = ReadAPInt(Record, Idx);
Richard Smith772e2662019-10-04 01:25:59 +00006382 Expr *SizeExpr = ReadExpr(*Loc.F);
6383 return Context.getConstantArrayType(ElementType, Size, SizeExpr,
Guy Benyei11169dd2012-12-18 14:30:41 +00006384 ASM, IndexTypeQuals);
6385 }
6386
6387 case TYPE_INCOMPLETE_ARRAY: {
6388 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006389 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 unsigned IndexTypeQuals = Record[2];
6391 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
6392 }
6393
6394 case TYPE_VARIABLE_ARRAY: {
6395 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006396 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 unsigned IndexTypeQuals = Record[2];
6398 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6399 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6400 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6401 ASM, IndexTypeQuals,
6402 SourceRange(LBLoc, RBLoc));
6403 }
6404
6405 case TYPE_VECTOR: {
6406 if (Record.size() != 3) {
6407 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006408 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006409 }
6410
6411 QualType ElementType = readType(*Loc.F, Record, Idx);
6412 unsigned NumElements = Record[1];
6413 unsigned VecKind = Record[2];
6414 return Context.getVectorType(ElementType, NumElements,
6415 (VectorType::VectorKind)VecKind);
6416 }
6417
6418 case TYPE_EXT_VECTOR: {
6419 if (Record.size() != 3) {
6420 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006421 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006422 }
6423
6424 QualType ElementType = readType(*Loc.F, Record, Idx);
6425 unsigned NumElements = Record[1];
6426 return Context.getExtVectorType(ElementType, NumElements);
6427 }
6428
6429 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006430 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006432 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006433 }
6434 QualType ResultType = readType(*Loc.F, Record, Idx);
6435 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006436 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006437 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 return Context.getFunctionNoProtoType(ResultType, Info);
6439 }
6440
6441 case TYPE_FUNCTION_PROTO: {
6442 QualType ResultType = readType(*Loc.F, Record, Idx);
6443
6444 FunctionProtoType::ExtProtoInfo EPI;
6445 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6446 /*hasregparm*/ Record[2],
6447 /*regparm*/ Record[3],
6448 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006449 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006450 /*nocallersavedregs*/ Record[6],
6451 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006452
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006453 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006454
6455 EPI.Variadic = Record[Idx++];
6456 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006457 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006458 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006459 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006460 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006461
6462 unsigned NumParams = Record[Idx++];
6463 SmallVector<QualType, 16> ParamTypes;
6464 for (unsigned I = 0; I != NumParams; ++I)
6465 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6466
John McCall18afab72016-03-01 00:49:02 +00006467 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6468 if (Idx != Record.size()) {
6469 for (unsigned I = 0; I != NumParams; ++I)
6470 ExtParameterInfos.push_back(
6471 FunctionProtoType::ExtParameterInfo
6472 ::getFromOpaqueValue(Record[Idx++]));
6473 EPI.ExtParameterInfos = ExtParameterInfos.data();
6474 }
6475
6476 assert(Idx == Record.size());
6477
Jordan Rose5c382722013-03-08 21:51:21 +00006478 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006479 }
6480
6481 case TYPE_UNRESOLVED_USING: {
6482 unsigned Idx = 0;
6483 return Context.getTypeDeclType(
6484 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6485 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006486
Guy Benyei11169dd2012-12-18 14:30:41 +00006487 case TYPE_TYPEDEF: {
6488 if (Record.size() != 2) {
6489 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006490 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006491 }
6492 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006493 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006494 QualType Canonical = readType(*Loc.F, Record, Idx);
6495 if (!Canonical.isNull())
6496 Canonical = Context.getCanonicalType(Canonical);
6497 return Context.getTypedefType(Decl, Canonical);
6498 }
6499
6500 case TYPE_TYPEOF_EXPR:
6501 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6502
6503 case TYPE_TYPEOF: {
6504 if (Record.size() != 1) {
6505 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006506 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006507 }
6508 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6509 return Context.getTypeOfType(UnderlyingType);
6510 }
6511
6512 case TYPE_DECLTYPE: {
6513 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6514 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6515 }
6516
6517 case TYPE_UNARY_TRANSFORM: {
6518 QualType BaseType = readType(*Loc.F, Record, Idx);
6519 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006520 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006521 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6522 }
6523
Richard Smith74aeef52013-04-26 16:15:35 +00006524 case TYPE_AUTO: {
6525 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006526 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smithb2997f52019-05-21 20:10:50 +00006527 bool IsDependent = false, IsPack = false;
6528 if (Deduced.isNull()) {
6529 IsDependent = Record[Idx] > 0;
6530 IsPack = Record[Idx] > 1;
6531 ++Idx;
6532 }
6533 return Context.getAutoType(Deduced, Keyword, IsDependent, IsPack);
Richard Smith74aeef52013-04-26 16:15:35 +00006534 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006535
Richard Smith600b5262017-01-26 20:40:47 +00006536 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6537 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6538 QualType Deduced = readType(*Loc.F, Record, Idx);
6539 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6540 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6541 IsDependent);
6542 }
6543
Guy Benyei11169dd2012-12-18 14:30:41 +00006544 case TYPE_RECORD: {
6545 if (Record.size() != 2) {
6546 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006547 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006548 }
6549 unsigned Idx = 0;
6550 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006551 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6553 QualType T = Context.getRecordType(RD);
6554 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6555 return T;
6556 }
6557
6558 case TYPE_ENUM: {
6559 if (Record.size() != 2) {
6560 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006561 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006562 }
6563 unsigned Idx = 0;
6564 bool IsDependent = Record[Idx++];
6565 QualType T
6566 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6567 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6568 return T;
6569 }
6570
6571 case TYPE_ATTRIBUTED: {
6572 if (Record.size() != 3) {
6573 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006574 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 }
6576 QualType modifiedType = readType(*Loc.F, Record, Idx);
6577 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006578 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006579 return Context.getAttributedType(kind, modifiedType, equivalentType);
6580 }
6581
6582 case TYPE_PAREN: {
6583 if (Record.size() != 1) {
6584 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006585 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006586 }
6587 QualType InnerType = readType(*Loc.F, Record, Idx);
6588 return Context.getParenType(InnerType);
6589 }
6590
Leonard Chanc72aaf62019-05-07 03:20:17 +00006591 case TYPE_MACRO_QUALIFIED: {
6592 if (Record.size() != 2) {
6593 Error("incorrect encoding of macro defined type");
6594 return QualType();
6595 }
6596 QualType UnderlyingTy = readType(*Loc.F, Record, Idx);
6597 IdentifierInfo *MacroII = GetIdentifierInfo(*Loc.F, Record, Idx);
6598 return Context.getMacroQualifiedType(UnderlyingTy, MacroII);
6599 }
6600
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 case TYPE_PACK_EXPANSION: {
6602 if (Record.size() != 2) {
6603 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006604 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006605 }
6606 QualType Pattern = readType(*Loc.F, Record, Idx);
6607 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006608 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006609 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006610 if (Record[1])
6611 NumExpansions = Record[1] - 1;
6612 return Context.getPackExpansionType(Pattern, NumExpansions);
6613 }
6614
6615 case TYPE_ELABORATED: {
6616 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006617 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6619 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006620 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6621 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006622 }
6623
6624 case TYPE_OBJC_INTERFACE: {
6625 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006626 ObjCInterfaceDecl *ItfD
6627 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6629 }
6630
Manman Rene6be26c2016-09-13 17:25:08 +00006631 case TYPE_OBJC_TYPE_PARAM: {
6632 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006633 ObjCTypeParamDecl *Decl
6634 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006635 unsigned NumProtos = Record[Idx++];
6636 SmallVector<ObjCProtocolDecl*, 4> Protos;
6637 for (unsigned I = 0; I != NumProtos; ++I)
6638 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6639 return Context.getObjCTypeParamType(Decl, Protos);
6640 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006641
Guy Benyei11169dd2012-12-18 14:30:41 +00006642 case TYPE_OBJC_OBJECT: {
6643 unsigned Idx = 0;
6644 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006645 unsigned NumTypeArgs = Record[Idx++];
6646 SmallVector<QualType, 4> TypeArgs;
6647 for (unsigned I = 0; I != NumTypeArgs; ++I)
6648 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 unsigned NumProtos = Record[Idx++];
6650 SmallVector<ObjCProtocolDecl*, 4> Protos;
6651 for (unsigned I = 0; I != NumProtos; ++I)
6652 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006653 bool IsKindOf = Record[Idx++];
6654 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006655 }
6656
6657 case TYPE_OBJC_OBJECT_POINTER: {
6658 unsigned Idx = 0;
6659 QualType Pointee = readType(*Loc.F, Record, Idx);
6660 return Context.getObjCObjectPointerType(Pointee);
6661 }
6662
6663 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6664 unsigned Idx = 0;
6665 QualType Parm = readType(*Loc.F, Record, Idx);
6666 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006667 return Context.getSubstTemplateTypeParmType(
6668 cast<TemplateTypeParmType>(Parm),
6669 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006670 }
6671
6672 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6673 unsigned Idx = 0;
6674 QualType Parm = readType(*Loc.F, Record, Idx);
6675 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6676 return Context.getSubstTemplateTypeParmPackType(
6677 cast<TemplateTypeParmType>(Parm),
6678 ArgPack);
6679 }
6680
6681 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006682 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006683 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6684 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6685 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006686 const Type *T = nullptr;
6687 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6688 if (const Type *Existing = DI->getTypeForDecl()) {
6689 T = Existing;
6690 break;
6691 }
6692 }
6693 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006694 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006695 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6696 DI->setTypeForDecl(T);
6697 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006698 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006699 }
6700
6701 case TYPE_TEMPLATE_TYPE_PARM: {
6702 unsigned Idx = 0;
6703 unsigned Depth = Record[Idx++];
6704 unsigned Index = Record[Idx++];
6705 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006706 TemplateTypeParmDecl *D
6707 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6709 }
6710
6711 case TYPE_DEPENDENT_NAME: {
6712 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006713 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006714 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006715 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 QualType Canon = readType(*Loc.F, Record, Idx);
6717 if (!Canon.isNull())
6718 Canon = Context.getCanonicalType(Canon);
6719 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6720 }
6721
6722 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6723 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006724 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006726 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 unsigned NumArgs = Record[Idx++];
6728 SmallVector<TemplateArgument, 8> Args;
6729 Args.reserve(NumArgs);
6730 while (NumArgs--)
6731 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6732 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006733 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006734 }
6735
6736 case TYPE_DEPENDENT_SIZED_ARRAY: {
6737 unsigned Idx = 0;
6738
6739 // ArrayType
6740 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006741 ArrayType::ArraySizeModifier ASM
6742 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 unsigned IndexTypeQuals = Record[Idx++];
6744
6745 // DependentSizedArrayType
6746 Expr *NumElts = ReadExpr(*Loc.F);
6747 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6748
6749 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6750 IndexTypeQuals, Brackets);
6751 }
6752
6753 case TYPE_TEMPLATE_SPECIALIZATION: {
6754 unsigned Idx = 0;
6755 bool IsDependent = Record[Idx++];
6756 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6757 SmallVector<TemplateArgument, 8> Args;
6758 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6759 QualType Underlying = readType(*Loc.F, Record, Idx);
6760 QualType T;
6761 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006762 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006764 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006765 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6766 return T;
6767 }
6768
6769 case TYPE_ATOMIC: {
6770 if (Record.size() != 1) {
6771 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006772 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 }
6774 QualType ValueType = readType(*Loc.F, Record, Idx);
6775 return Context.getAtomicType(ValueType);
6776 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006777
Joey Goulye3c85de2016-12-01 11:30:49 +00006778 case TYPE_PIPE: {
6779 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006780 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006781 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006782 }
6783
6784 // Reading the pipe element type.
6785 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006786 unsigned ReadOnly = Record[1];
6787 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006788 }
6789
Erich Keanef702b022018-07-13 19:46:04 +00006790 case TYPE_DEPENDENT_SIZED_VECTOR: {
6791 unsigned Idx = 0;
6792 QualType ElementType = readType(*Loc.F, Record, Idx);
6793 Expr *SizeExpr = ReadExpr(*Loc.F);
6794 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6795 unsigned VecKind = Record[Idx];
6796
6797 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6798 (VectorType::VectorKind)VecKind);
6799 }
6800
Alex Lorenz00aee432017-03-22 10:04:48 +00006801 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6802 unsigned Idx = 0;
6803
6804 // DependentSizedExtVectorType
6805 QualType ElementType = readType(*Loc.F, Record, Idx);
6806 Expr *SizeExpr = ReadExpr(*Loc.F);
6807 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6808
6809 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6810 AttrLoc);
6811 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006812
6813 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6814 unsigned Idx = 0;
6815
6816 // DependentAddressSpaceType
6817 QualType PointeeType = readType(*Loc.F, Record, Idx);
6818 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6819 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6820
6821 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6822 AttrLoc);
6823 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 }
6825 llvm_unreachable("Invalid TypeCode!");
6826}
6827
Richard Smith564417a2014-03-20 21:47:22 +00006828void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6829 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006830 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006831 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006832 ExceptionSpecificationType EST =
6833 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006834 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006835 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006836 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006837 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006838 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006839 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006840 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006841 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006842 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6843 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006844 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006845 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006846 }
6847}
6848
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006849namespace clang {
6850
6851class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006852 ModuleFile *F;
6853 ASTReader *Reader;
6854 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006855 unsigned &Idx;
6856
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006857 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006858 return Reader->ReadSourceLocation(*F, Record, Idx);
6859 }
6860
6861 TypeSourceInfo *GetTypeSourceInfo() {
6862 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6863 }
6864
6865 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6866 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006867 }
6868
Richard Smithe43e2b32018-08-20 21:47:29 +00006869 Attr *ReadAttr() {
6870 return Reader->ReadAttr(*F, Record, Idx);
6871 }
6872
Guy Benyei11169dd2012-12-18 14:30:41 +00006873public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006874 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006875 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006876 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006877
6878 // We want compile-time assurance that we've enumerated all of
6879 // these, so unfortunately we have to declare them first, then
6880 // define them out-of-line.
6881#define ABSTRACT_TYPELOC(CLASS, PARENT)
6882#define TYPELOC(CLASS, PARENT) \
6883 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6884#include "clang/AST/TypeLocNodes.def"
6885
6886 void VisitFunctionTypeLoc(FunctionTypeLoc);
6887 void VisitArrayTypeLoc(ArrayTypeLoc);
6888};
6889
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006890} // namespace clang
6891
Guy Benyei11169dd2012-12-18 14:30:41 +00006892void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6893 // nothing to do
6894}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006895
Guy Benyei11169dd2012-12-18 14:30:41 +00006896void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006897 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006898 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006899 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6900 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6901 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6902 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006903 }
6904}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006905
Guy Benyei11169dd2012-12-18 14:30:41 +00006906void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006907 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006908}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006909
Guy Benyei11169dd2012-12-18 14:30:41 +00006910void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006911 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006912}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006913
Reid Kleckner8a365022013-06-24 17:51:48 +00006914void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6915 // nothing to do
6916}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006917
Reid Kleckner0503a872013-12-05 01:23:43 +00006918void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6919 // nothing to do
6920}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006921
Leonard Chanc72aaf62019-05-07 03:20:17 +00006922void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6923 TL.setExpansionLoc(ReadSourceLocation());
6924}
6925
Guy Benyei11169dd2012-12-18 14:30:41 +00006926void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006927 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006928}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006929
Guy Benyei11169dd2012-12-18 14:30:41 +00006930void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006931 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006932}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006933
Guy Benyei11169dd2012-12-18 14:30:41 +00006934void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006935 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006936}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006937
Guy Benyei11169dd2012-12-18 14:30:41 +00006938void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006939 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006940 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006941}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006942
Guy Benyei11169dd2012-12-18 14:30:41 +00006943void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006944 TL.setLBracketLoc(ReadSourceLocation());
6945 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006946 if (Record[Idx++])
6947 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 else
Craig Toppera13603a2014-05-22 05:54:18 +00006949 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006950}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006951
Guy Benyei11169dd2012-12-18 14:30:41 +00006952void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6953 VisitArrayTypeLoc(TL);
6954}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006955
Guy Benyei11169dd2012-12-18 14:30:41 +00006956void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6957 VisitArrayTypeLoc(TL);
6958}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006959
Guy Benyei11169dd2012-12-18 14:30:41 +00006960void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6961 VisitArrayTypeLoc(TL);
6962}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006963
Guy Benyei11169dd2012-12-18 14:30:41 +00006964void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6965 DependentSizedArrayTypeLoc TL) {
6966 VisitArrayTypeLoc(TL);
6967}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006968
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006969void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6970 DependentAddressSpaceTypeLoc TL) {
6971
6972 TL.setAttrNameLoc(ReadSourceLocation());
6973 SourceRange range;
6974 range.setBegin(ReadSourceLocation());
6975 range.setEnd(ReadSourceLocation());
6976 TL.setAttrOperandParensRange(range);
6977 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6978}
6979
Guy Benyei11169dd2012-12-18 14:30:41 +00006980void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6981 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006982 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006983}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006984
Guy Benyei11169dd2012-12-18 14:30:41 +00006985void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006986 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006987}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006988
Erich Keanef702b022018-07-13 19:46:04 +00006989void TypeLocReader::VisitDependentVectorTypeLoc(
6990 DependentVectorTypeLoc TL) {
6991 TL.setNameLoc(ReadSourceLocation());
6992}
6993
Guy Benyei11169dd2012-12-18 14:30:41 +00006994void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006995 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006996}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006997
Guy Benyei11169dd2012-12-18 14:30:41 +00006998void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006999 TL.setLocalRangeBegin(ReadSourceLocation());
7000 TL.setLParenLoc(ReadSourceLocation());
7001 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00007002 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
7003 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007004 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00007005 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007006 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007007 }
7008}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
7011 VisitFunctionTypeLoc(TL);
7012}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007013
Guy Benyei11169dd2012-12-18 14:30:41 +00007014void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
7015 VisitFunctionTypeLoc(TL);
7016}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007017
Guy Benyei11169dd2012-12-18 14:30:41 +00007018void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007019 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007020}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007021
Guy Benyei11169dd2012-12-18 14:30:41 +00007022void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007023 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007024}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007025
Guy Benyei11169dd2012-12-18 14:30:41 +00007026void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007027 TL.setTypeofLoc(ReadSourceLocation());
7028 TL.setLParenLoc(ReadSourceLocation());
7029 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007030}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007031
Guy Benyei11169dd2012-12-18 14:30:41 +00007032void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007033 TL.setTypeofLoc(ReadSourceLocation());
7034 TL.setLParenLoc(ReadSourceLocation());
7035 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007036 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007037}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007038
Guy Benyei11169dd2012-12-18 14:30:41 +00007039void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007040 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007041}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007042
Guy Benyei11169dd2012-12-18 14:30:41 +00007043void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007044 TL.setKWLoc(ReadSourceLocation());
7045 TL.setLParenLoc(ReadSourceLocation());
7046 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007047 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00007048}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007049
Guy Benyei11169dd2012-12-18 14:30:41 +00007050void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007051 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007052}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007053
Richard Smith600b5262017-01-26 20:40:47 +00007054void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
7055 DeducedTemplateSpecializationTypeLoc TL) {
7056 TL.setTemplateNameLoc(ReadSourceLocation());
7057}
7058
Guy Benyei11169dd2012-12-18 14:30:41 +00007059void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007060 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007061}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007062
Guy Benyei11169dd2012-12-18 14:30:41 +00007063void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007064 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007065}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007066
Guy Benyei11169dd2012-12-18 14:30:41 +00007067void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00007068 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00007069}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007072 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007073}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007074
Guy Benyei11169dd2012-12-18 14:30:41 +00007075void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
7076 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007077 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007078}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007079
Guy Benyei11169dd2012-12-18 14:30:41 +00007080void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
7081 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007082 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007083}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007084
Guy Benyei11169dd2012-12-18 14:30:41 +00007085void TypeLocReader::VisitTemplateSpecializationTypeLoc(
7086 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007087 TL.setTemplateKeywordLoc(ReadSourceLocation());
7088 TL.setTemplateNameLoc(ReadSourceLocation());
7089 TL.setLAngleLoc(ReadSourceLocation());
7090 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007091 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007092 TL.setArgLocInfo(
7093 i,
7094 Reader->GetTemplateArgumentLocInfo(
7095 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007096}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007097
Guy Benyei11169dd2012-12-18 14:30:41 +00007098void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007099 TL.setLParenLoc(ReadSourceLocation());
7100 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007101}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007102
Guy Benyei11169dd2012-12-18 14:30:41 +00007103void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007104 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007105 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007106}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007107
Guy Benyei11169dd2012-12-18 14:30:41 +00007108void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007109 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007110}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007111
Guy Benyei11169dd2012-12-18 14:30:41 +00007112void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007113 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007114 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007115 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007116}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007117
Guy Benyei11169dd2012-12-18 14:30:41 +00007118void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
7119 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007120 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00007121 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007122 TL.setTemplateKeywordLoc(ReadSourceLocation());
7123 TL.setTemplateNameLoc(ReadSourceLocation());
7124 TL.setLAngleLoc(ReadSourceLocation());
7125 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007126 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007127 TL.setArgLocInfo(
7128 I,
7129 Reader->GetTemplateArgumentLocInfo(
7130 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007132
Guy Benyei11169dd2012-12-18 14:30:41 +00007133void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007134 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007135}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007136
Guy Benyei11169dd2012-12-18 14:30:41 +00007137void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007138 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007139}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007140
Manman Rene6be26c2016-09-13 17:25:08 +00007141void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
7142 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007143 TL.setProtocolLAngleLoc(ReadSourceLocation());
7144 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007145 }
7146 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007147 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00007148}
7149
Guy Benyei11169dd2012-12-18 14:30:41 +00007150void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00007151 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007152 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
7153 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00007154 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00007155 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007156 TL.setProtocolLAngleLoc(ReadSourceLocation());
7157 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007158 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007159 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007160}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007161
Guy Benyei11169dd2012-12-18 14:30:41 +00007162void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007163 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007164}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007165
Guy Benyei11169dd2012-12-18 14:30:41 +00007166void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007167 TL.setKWLoc(ReadSourceLocation());
7168 TL.setLParenLoc(ReadSourceLocation());
7169 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00007170}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007171
Xiuli Pan9c14e282016-01-09 12:53:17 +00007172void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007173 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00007174}
Guy Benyei11169dd2012-12-18 14:30:41 +00007175
Richard Smithc23d7342018-06-29 20:46:25 +00007176void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
7177 unsigned &Idx, TypeLoc TL) {
7178 TypeLocReader TLR(F, *this, Record, Idx);
7179 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
7180 TLR.Visit(TL);
7181}
7182
David L. Jonesbe1557a2016-12-21 00:17:49 +00007183TypeSourceInfo *
7184ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
7185 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007186 QualType InfoTy = readType(F, Record, Idx);
7187 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00007188 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007189
7190 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00007191 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00007192 return TInfo;
7193}
7194
7195QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007196 assert(ContextObj && "reading type with no AST context");
7197 ASTContext &Context = *ContextObj;
7198
Guy Benyei11169dd2012-12-18 14:30:41 +00007199 unsigned FastQuals = ID & Qualifiers::FastMask;
7200 unsigned Index = ID >> Qualifiers::FastWidth;
7201
7202 if (Index < NUM_PREDEF_TYPE_IDS) {
7203 QualType T;
7204 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00007205 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00007206 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00007207 case PREDEF_TYPE_VOID_ID:
7208 T = Context.VoidTy;
7209 break;
7210 case PREDEF_TYPE_BOOL_ID:
7211 T = Context.BoolTy;
7212 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007213 case PREDEF_TYPE_CHAR_U_ID:
7214 case PREDEF_TYPE_CHAR_S_ID:
7215 // FIXME: Check that the signedness of CharTy is correct!
7216 T = Context.CharTy;
7217 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007218 case PREDEF_TYPE_UCHAR_ID:
7219 T = Context.UnsignedCharTy;
7220 break;
7221 case PREDEF_TYPE_USHORT_ID:
7222 T = Context.UnsignedShortTy;
7223 break;
7224 case PREDEF_TYPE_UINT_ID:
7225 T = Context.UnsignedIntTy;
7226 break;
7227 case PREDEF_TYPE_ULONG_ID:
7228 T = Context.UnsignedLongTy;
7229 break;
7230 case PREDEF_TYPE_ULONGLONG_ID:
7231 T = Context.UnsignedLongLongTy;
7232 break;
7233 case PREDEF_TYPE_UINT128_ID:
7234 T = Context.UnsignedInt128Ty;
7235 break;
7236 case PREDEF_TYPE_SCHAR_ID:
7237 T = Context.SignedCharTy;
7238 break;
7239 case PREDEF_TYPE_WCHAR_ID:
7240 T = Context.WCharTy;
7241 break;
7242 case PREDEF_TYPE_SHORT_ID:
7243 T = Context.ShortTy;
7244 break;
7245 case PREDEF_TYPE_INT_ID:
7246 T = Context.IntTy;
7247 break;
7248 case PREDEF_TYPE_LONG_ID:
7249 T = Context.LongTy;
7250 break;
7251 case PREDEF_TYPE_LONGLONG_ID:
7252 T = Context.LongLongTy;
7253 break;
7254 case PREDEF_TYPE_INT128_ID:
7255 T = Context.Int128Ty;
7256 break;
7257 case PREDEF_TYPE_HALF_ID:
7258 T = Context.HalfTy;
7259 break;
7260 case PREDEF_TYPE_FLOAT_ID:
7261 T = Context.FloatTy;
7262 break;
7263 case PREDEF_TYPE_DOUBLE_ID:
7264 T = Context.DoubleTy;
7265 break;
7266 case PREDEF_TYPE_LONGDOUBLE_ID:
7267 T = Context.LongDoubleTy;
7268 break;
Leonard Chanf921d852018-06-04 16:07:52 +00007269 case PREDEF_TYPE_SHORT_ACCUM_ID:
7270 T = Context.ShortAccumTy;
7271 break;
7272 case PREDEF_TYPE_ACCUM_ID:
7273 T = Context.AccumTy;
7274 break;
7275 case PREDEF_TYPE_LONG_ACCUM_ID:
7276 T = Context.LongAccumTy;
7277 break;
7278 case PREDEF_TYPE_USHORT_ACCUM_ID:
7279 T = Context.UnsignedShortAccumTy;
7280 break;
7281 case PREDEF_TYPE_UACCUM_ID:
7282 T = Context.UnsignedAccumTy;
7283 break;
7284 case PREDEF_TYPE_ULONG_ACCUM_ID:
7285 T = Context.UnsignedLongAccumTy;
7286 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00007287 case PREDEF_TYPE_SHORT_FRACT_ID:
7288 T = Context.ShortFractTy;
7289 break;
7290 case PREDEF_TYPE_FRACT_ID:
7291 T = Context.FractTy;
7292 break;
7293 case PREDEF_TYPE_LONG_FRACT_ID:
7294 T = Context.LongFractTy;
7295 break;
7296 case PREDEF_TYPE_USHORT_FRACT_ID:
7297 T = Context.UnsignedShortFractTy;
7298 break;
7299 case PREDEF_TYPE_UFRACT_ID:
7300 T = Context.UnsignedFractTy;
7301 break;
7302 case PREDEF_TYPE_ULONG_FRACT_ID:
7303 T = Context.UnsignedLongFractTy;
7304 break;
7305 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
7306 T = Context.SatShortAccumTy;
7307 break;
7308 case PREDEF_TYPE_SAT_ACCUM_ID:
7309 T = Context.SatAccumTy;
7310 break;
7311 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
7312 T = Context.SatLongAccumTy;
7313 break;
7314 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
7315 T = Context.SatUnsignedShortAccumTy;
7316 break;
7317 case PREDEF_TYPE_SAT_UACCUM_ID:
7318 T = Context.SatUnsignedAccumTy;
7319 break;
7320 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
7321 T = Context.SatUnsignedLongAccumTy;
7322 break;
7323 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
7324 T = Context.SatShortFractTy;
7325 break;
7326 case PREDEF_TYPE_SAT_FRACT_ID:
7327 T = Context.SatFractTy;
7328 break;
7329 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
7330 T = Context.SatLongFractTy;
7331 break;
7332 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
7333 T = Context.SatUnsignedShortFractTy;
7334 break;
7335 case PREDEF_TYPE_SAT_UFRACT_ID:
7336 T = Context.SatUnsignedFractTy;
7337 break;
7338 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
7339 T = Context.SatUnsignedLongFractTy;
7340 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00007341 case PREDEF_TYPE_FLOAT16_ID:
7342 T = Context.Float16Ty;
7343 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00007344 case PREDEF_TYPE_FLOAT128_ID:
7345 T = Context.Float128Ty;
7346 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007347 case PREDEF_TYPE_OVERLOAD_ID:
7348 T = Context.OverloadTy;
7349 break;
7350 case PREDEF_TYPE_BOUND_MEMBER:
7351 T = Context.BoundMemberTy;
7352 break;
7353 case PREDEF_TYPE_PSEUDO_OBJECT:
7354 T = Context.PseudoObjectTy;
7355 break;
7356 case PREDEF_TYPE_DEPENDENT_ID:
7357 T = Context.DependentTy;
7358 break;
7359 case PREDEF_TYPE_UNKNOWN_ANY:
7360 T = Context.UnknownAnyTy;
7361 break;
7362 case PREDEF_TYPE_NULLPTR_ID:
7363 T = Context.NullPtrTy;
7364 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00007365 case PREDEF_TYPE_CHAR8_ID:
7366 T = Context.Char8Ty;
7367 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007368 case PREDEF_TYPE_CHAR16_ID:
7369 T = Context.Char16Ty;
7370 break;
7371 case PREDEF_TYPE_CHAR32_ID:
7372 T = Context.Char32Ty;
7373 break;
7374 case PREDEF_TYPE_OBJC_ID:
7375 T = Context.ObjCBuiltinIdTy;
7376 break;
7377 case PREDEF_TYPE_OBJC_CLASS:
7378 T = Context.ObjCBuiltinClassTy;
7379 break;
7380 case PREDEF_TYPE_OBJC_SEL:
7381 T = Context.ObjCBuiltinSelTy;
7382 break;
Alexey Bader954ba212016-04-08 13:40:33 +00007383#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7384 case PREDEF_TYPE_##Id##_ID: \
7385 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00007386 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00007387#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007388#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7389 case PREDEF_TYPE_##Id##_ID: \
7390 T = Context.Id##Ty; \
7391 break;
7392#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00007393 case PREDEF_TYPE_SAMPLER_ID:
7394 T = Context.OCLSamplerTy;
7395 break;
7396 case PREDEF_TYPE_EVENT_ID:
7397 T = Context.OCLEventTy;
7398 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007399 case PREDEF_TYPE_CLK_EVENT_ID:
7400 T = Context.OCLClkEventTy;
7401 break;
7402 case PREDEF_TYPE_QUEUE_ID:
7403 T = Context.OCLQueueTy;
7404 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007405 case PREDEF_TYPE_RESERVE_ID_ID:
7406 T = Context.OCLReserveIDTy;
7407 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007408 case PREDEF_TYPE_AUTO_DEDUCT:
7409 T = Context.getAutoDeductType();
7410 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007411 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7412 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007413 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7415 T = Context.ARCUnbridgedCastTy;
7416 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 case PREDEF_TYPE_BUILTIN_FN:
7418 T = Context.BuiltinFnTy;
7419 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007420 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7421 T = Context.OMPArraySectionTy;
7422 break;
Richard Sandifordeb485fb2019-08-09 08:52:54 +00007423#define SVE_TYPE(Name, Id, SingletonId) \
7424 case PREDEF_TYPE_##Id##_ID: \
7425 T = Context.SingletonId; \
7426 break;
7427#include "clang/Basic/AArch64SVEACLETypes.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 }
7429
7430 assert(!T.isNull() && "Unknown predefined type");
7431 return T.withFastQualifiers(FastQuals);
7432 }
7433
7434 Index -= NUM_PREDEF_TYPE_IDS;
7435 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7436 if (TypesLoaded[Index].isNull()) {
7437 TypesLoaded[Index] = readTypeRecord(Index);
7438 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007439 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007440
7441 TypesLoaded[Index]->setFromAST();
7442 if (DeserializationListener)
7443 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7444 TypesLoaded[Index]);
7445 }
7446
7447 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7448}
7449
7450QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7451 return GetType(getGlobalTypeID(F, LocalID));
7452}
7453
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007454serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007455ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7456 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7457 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007458
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7460 return LocalID;
7461
Richard Smith37a93df2017-02-18 00:32:02 +00007462 if (!F.ModuleOffsetMap.empty())
7463 ReadModuleOffsetMap(F);
7464
Guy Benyei11169dd2012-12-18 14:30:41 +00007465 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7466 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7467 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007468
Guy Benyei11169dd2012-12-18 14:30:41 +00007469 unsigned GlobalIndex = LocalIndex + I->second;
7470 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7471}
7472
7473TemplateArgumentLocInfo
7474ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7475 TemplateArgument::ArgKind Kind,
7476 const RecordData &Record,
7477 unsigned &Index) {
7478 switch (Kind) {
7479 case TemplateArgument::Expression:
7480 return ReadExpr(F);
7481 case TemplateArgument::Type:
7482 return GetTypeSourceInfo(F, Record, Index);
7483 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007484 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007485 Index);
7486 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7487 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7488 SourceLocation());
7489 }
7490 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007491 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 Index);
7493 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7494 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007495 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007496 EllipsisLoc);
7497 }
7498 case TemplateArgument::Null:
7499 case TemplateArgument::Integral:
7500 case TemplateArgument::Declaration:
7501 case TemplateArgument::NullPtr:
7502 case TemplateArgument::Pack:
7503 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007504 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007505 }
7506 llvm_unreachable("unexpected template argument loc");
7507}
7508
7509TemplateArgumentLoc
7510ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7511 const RecordData &Record, unsigned &Index) {
7512 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7513
7514 if (Arg.getKind() == TemplateArgument::Expression) {
7515 if (Record[Index++]) // bool InfoHasSameExpr.
7516 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7517 }
7518 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7519 Record, Index));
7520}
7521
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007522const ASTTemplateArgumentListInfo*
7523ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7524 const RecordData &Record,
7525 unsigned &Index) {
7526 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7527 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7528 unsigned NumArgsAsWritten = Record[Index++];
7529 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7530 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7531 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7532 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7533}
7534
Guy Benyei11169dd2012-12-18 14:30:41 +00007535Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7536 return GetDecl(ID);
7537}
7538
Richard Smith053f6c62014-05-16 23:01:30 +00007539void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007540 if (NumCurrentElementsDeserializing) {
7541 // We arrange to not care about the complete redeclaration chain while we're
7542 // deserializing. Just remember that the AST has marked this one as complete
7543 // but that it's not actually complete yet, so we know we still need to
7544 // complete it later.
7545 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7546 return;
7547 }
7548
Richard Smith053f6c62014-05-16 23:01:30 +00007549 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7550
Richard Smith053f6c62014-05-16 23:01:30 +00007551 // If this is a named declaration, complete it by looking it up
7552 // within its context.
7553 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007554 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007555 // all mergeable entities within it.
7556 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7557 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7558 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007559 if (!getContext().getLangOpts().CPlusPlus &&
7560 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007561 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007562 // the identifier instead. (For C++ modules, we don't store decls
7563 // in the serialized identifier table, so we do the lookup in the TU.)
7564 auto *II = Name.getAsIdentifierInfo();
7565 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007566 if (II->isOutOfDate())
7567 updateOutOfDateIdentifier(*II);
7568 } else
7569 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007570 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007571 // Find all declarations of this kind from the relevant context.
7572 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7573 auto *DC = cast<DeclContext>(DCDecl);
7574 SmallVector<Decl*, 8> Decls;
7575 FindExternalLexicalDecls(
7576 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7577 }
Richard Smith053f6c62014-05-16 23:01:30 +00007578 }
7579 }
Richard Smith50895422015-01-31 03:04:55 +00007580
7581 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7582 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7583 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7584 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7585 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7586 if (auto *Template = FD->getPrimaryTemplate())
7587 Template->LoadLazySpecializations();
7588 }
Richard Smith053f6c62014-05-16 23:01:30 +00007589}
7590
Richard Smithc2bb8182015-03-24 06:36:48 +00007591CXXCtorInitializer **
7592ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7593 RecordLocation Loc = getLocalBitOffset(Offset);
7594 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7595 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007596 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7597 Error(std::move(Err));
7598 return nullptr;
7599 }
Richard Smithc2bb8182015-03-24 06:36:48 +00007600 ReadingKindTracker ReadingKind(Read_Decl, *this);
7601
7602 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007603 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7604 if (!MaybeCode) {
7605 Error(MaybeCode.takeError());
7606 return nullptr;
7607 }
7608 unsigned Code = MaybeCode.get();
7609
7610 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7611 if (!MaybeRecCode) {
7612 Error(MaybeRecCode.takeError());
7613 return nullptr;
7614 }
7615 if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
Richard Smithc2bb8182015-03-24 06:36:48 +00007616 Error("malformed AST file: missing C++ ctor initializers");
7617 return nullptr;
7618 }
7619
7620 unsigned Idx = 0;
7621 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7622}
7623
Guy Benyei11169dd2012-12-18 14:30:41 +00007624CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007625 assert(ContextObj && "reading base specifiers with no AST context");
7626 ASTContext &Context = *ContextObj;
7627
Guy Benyei11169dd2012-12-18 14:30:41 +00007628 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007629 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 SavedStreamPosition SavedPosition(Cursor);
JF Bastien0e828952019-06-26 19:50:12 +00007631 if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
7632 Error(std::move(Err));
7633 return nullptr;
7634 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007635 ReadingKindTracker ReadingKind(Read_Decl, *this);
7636 RecordData Record;
JF Bastien0e828952019-06-26 19:50:12 +00007637
7638 Expected<unsigned> MaybeCode = Cursor.ReadCode();
7639 if (!MaybeCode) {
7640 Error(MaybeCode.takeError());
7641 return nullptr;
7642 }
7643 unsigned Code = MaybeCode.get();
7644
7645 Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record);
7646 if (!MaybeRecCode) {
7647 Error(MaybeCode.takeError());
7648 return nullptr;
7649 }
7650 unsigned RecCode = MaybeRecCode.get();
7651
Guy Benyei11169dd2012-12-18 14:30:41 +00007652 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007653 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007654 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 }
7656
7657 unsigned Idx = 0;
7658 unsigned NumBases = Record[Idx++];
7659 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007660 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007661 for (unsigned I = 0; I != NumBases; ++I)
7662 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7663 return Bases;
7664}
7665
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007666serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007667ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7668 if (LocalID < NUM_PREDEF_DECL_IDS)
7669 return LocalID;
7670
Richard Smith37a93df2017-02-18 00:32:02 +00007671 if (!F.ModuleOffsetMap.empty())
7672 ReadModuleOffsetMap(F);
7673
Guy Benyei11169dd2012-12-18 14:30:41 +00007674 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7675 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7676 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007677
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 return LocalID + I->second;
7679}
7680
7681bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7682 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007683 // Predefined decls aren't from any module.
7684 if (ID < NUM_PREDEF_DECL_IDS)
7685 return false;
7686
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007687 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007688 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007689}
7690
Douglas Gregor9f782892013-01-21 15:25:38 +00007691ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007692 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007693 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007694 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7695 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7696 return I->second;
7697}
7698
7699SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7700 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007701 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007702
Guy Benyei11169dd2012-12-18 14:30:41 +00007703 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7704
7705 if (Index > DeclsLoaded.size()) {
7706 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007707 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007708 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007709
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 if (Decl *D = DeclsLoaded[Index])
7711 return D->getLocation();
7712
Richard Smithcb34bd32016-03-27 07:28:06 +00007713 SourceLocation Loc;
7714 DeclCursorForID(ID, Loc);
7715 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007716}
7717
Richard Smithfe620d22015-03-05 23:24:12 +00007718static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7719 switch (ID) {
7720 case PREDEF_DECL_NULL_ID:
7721 return nullptr;
7722
7723 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7724 return Context.getTranslationUnitDecl();
7725
7726 case PREDEF_DECL_OBJC_ID_ID:
7727 return Context.getObjCIdDecl();
7728
7729 case PREDEF_DECL_OBJC_SEL_ID:
7730 return Context.getObjCSelDecl();
7731
7732 case PREDEF_DECL_OBJC_CLASS_ID:
7733 return Context.getObjCClassDecl();
7734
7735 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7736 return Context.getObjCProtocolDecl();
7737
7738 case PREDEF_DECL_INT_128_ID:
7739 return Context.getInt128Decl();
7740
7741 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7742 return Context.getUInt128Decl();
7743
7744 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7745 return Context.getObjCInstanceTypeDecl();
7746
7747 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7748 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007749
Richard Smith9b88a4c2015-07-27 05:40:23 +00007750 case PREDEF_DECL_VA_LIST_TAG:
7751 return Context.getVaListTagDecl();
7752
Charles Davisc7d5c942015-09-17 20:55:33 +00007753 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7754 return Context.getBuiltinMSVaListDecl();
7755
Richard Smithf19e1272015-03-07 00:04:49 +00007756 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7757 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007758
7759 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7760 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007761
7762 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7763 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007764
7765 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7766 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007767
7768 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7769 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007770 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007771 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007772}
7773
Richard Smithcd45dbc2014-04-19 03:48:30 +00007774Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007775 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007776 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007777 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007778 if (D) {
7779 // Track that we have merged the declaration with ID \p ID into the
7780 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007781 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007782 if (Merged.empty())
7783 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007784 }
Richard Smithfe620d22015-03-05 23:24:12 +00007785 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007786 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007787
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7789
7790 if (Index >= DeclsLoaded.size()) {
7791 assert(0 && "declaration ID out-of-range for AST file");
7792 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007793 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007795
7796 return DeclsLoaded[Index];
7797}
7798
7799Decl *ASTReader::GetDecl(DeclID ID) {
7800 if (ID < NUM_PREDEF_DECL_IDS)
7801 return GetExistingDecl(ID);
7802
7803 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7804
7805 if (Index >= DeclsLoaded.size()) {
7806 assert(0 && "declaration ID out-of-range for AST file");
7807 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007808 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007809 }
7810
Guy Benyei11169dd2012-12-18 14:30:41 +00007811 if (!DeclsLoaded[Index]) {
7812 ReadDeclRecord(ID);
7813 if (DeserializationListener)
7814 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7815 }
7816
7817 return DeclsLoaded[Index];
7818}
7819
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007820DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007821 DeclID GlobalID) {
7822 if (GlobalID < NUM_PREDEF_DECL_IDS)
7823 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007824
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7826 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7827 ModuleFile *Owner = I->second;
7828
7829 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7830 = M.GlobalToLocalDeclIDs.find(Owner);
7831 if (Pos == M.GlobalToLocalDeclIDs.end())
7832 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007833
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 return GlobalID - Owner->BaseDeclID + Pos->second;
7835}
7836
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007837serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007838 const RecordData &Record,
7839 unsigned &Idx) {
7840 if (Idx >= Record.size()) {
7841 Error("Corrupted AST file");
7842 return 0;
7843 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007844
Guy Benyei11169dd2012-12-18 14:30:41 +00007845 return getGlobalDeclID(F, Record[Idx++]);
7846}
7847
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007848/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007849///
7850/// This operation will read a new statement from the external
7851/// source each time it is called, and is meant to be used via a
7852/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7853Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7854 // Switch case IDs are per Decl.
7855 ClearSwitchCaseIDs();
7856
7857 // Offset here is a global offset across the entire chain.
7858 RecordLocation Loc = getLocalBitOffset(Offset);
JF Bastien0e828952019-06-26 19:50:12 +00007859 if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
7860 Error(std::move(Err));
7861 return nullptr;
7862 }
David Blaikie9fd16f82017-03-08 23:57:08 +00007863 assert(NumCurrentElementsDeserializing == 0 &&
7864 "should not be called while already deserializing");
7865 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007866 return ReadStmtFromStream(*Loc.F);
7867}
7868
Richard Smith3cb15722015-08-05 22:41:45 +00007869void ASTReader::FindExternalLexicalDecls(
7870 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7871 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007872 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7873
Richard Smith9ccdd932015-08-06 22:14:12 +00007874 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007875 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7876 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7877 auto K = (Decl::Kind)+LexicalDecls[I];
7878 if (!IsKindWeWant(K))
7879 continue;
7880
7881 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7882
7883 // Don't add predefined declarations to the lexical context more
7884 // than once.
7885 if (ID < NUM_PREDEF_DECL_IDS) {
7886 if (PredefsVisited[ID])
7887 continue;
7888
7889 PredefsVisited[ID] = true;
7890 }
7891
7892 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007893 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007894 if (!DC->isDeclInLexicalTraversal(D))
7895 Decls.push_back(D);
7896 }
7897 }
7898 };
7899
7900 if (isa<TranslationUnitDecl>(DC)) {
7901 for (auto Lexical : TULexicalDecls)
7902 Visit(Lexical.first, Lexical.second);
7903 } else {
7904 auto I = LexicalDecls.find(DC);
7905 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007906 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007907 }
7908
Guy Benyei11169dd2012-12-18 14:30:41 +00007909 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007910}
7911
7912namespace {
7913
7914class DeclIDComp {
7915 ASTReader &Reader;
7916 ModuleFile &Mod;
7917
7918public:
7919 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7920
7921 bool operator()(LocalDeclID L, LocalDeclID R) const {
7922 SourceLocation LHS = getLocation(L);
7923 SourceLocation RHS = getLocation(R);
7924 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7925 }
7926
7927 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7928 SourceLocation RHS = getLocation(R);
7929 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7930 }
7931
7932 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7933 SourceLocation LHS = getLocation(L);
7934 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7935 }
7936
7937 SourceLocation getLocation(LocalDeclID ID) const {
7938 return Reader.getSourceManager().getFileLoc(
7939 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7940 }
7941};
7942
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007943} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007944
7945void ASTReader::FindFileRegionDecls(FileID File,
7946 unsigned Offset, unsigned Length,
7947 SmallVectorImpl<Decl *> &Decls) {
7948 SourceManager &SM = getSourceManager();
7949
7950 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7951 if (I == FileDeclIDs.end())
7952 return;
7953
7954 FileDeclsInfo &DInfo = I->second;
7955 if (DInfo.Decls.empty())
7956 return;
7957
7958 SourceLocation
7959 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7960 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7961
7962 DeclIDComp DIDComp(*this, *DInfo.Mod);
Fangrui Song7264a472019-07-03 08:13:17 +00007963 ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
7964 llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 if (BeginIt != DInfo.Decls.begin())
7966 --BeginIt;
7967
7968 // If we are pointing at a top-level decl inside an objc container, we need
7969 // to backtrack until we find it otherwise we will fail to report that the
7970 // region overlaps with an objc container.
7971 while (BeginIt != DInfo.Decls.begin() &&
7972 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7973 ->isTopLevelDeclInObjCContainer())
7974 --BeginIt;
7975
Fangrui Song7264a472019-07-03 08:13:17 +00007976 ArrayRef<serialization::LocalDeclID>::iterator EndIt =
7977 llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 if (EndIt != DInfo.Decls.end())
7979 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007980
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 for (ArrayRef<serialization::LocalDeclID>::iterator
7982 DIt = BeginIt; DIt != EndIt; ++DIt)
7983 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7984}
7985
Richard Smith9ce12e32013-02-07 03:30:24 +00007986bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007987ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7988 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007989 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007990 "DeclContext has no visible decls in storage");
7991 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007992 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007993
Richard Smithd88a7f12015-09-01 20:35:42 +00007994 auto It = Lookups.find(DC);
7995 if (It == Lookups.end())
7996 return false;
7997
Richard Smith8c913ec2014-08-14 02:21:01 +00007998 Deserializing LookupResults(this);
7999
Richard Smithd88a7f12015-09-01 20:35:42 +00008000 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008002 for (DeclID ID : It->second.Table.find(Name)) {
8003 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008004 if (ND->getDeclName() == Name)
8005 Decls.push_back(ND);
8006 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008007
Guy Benyei11169dd2012-12-18 14:30:41 +00008008 ++NumVisibleDeclContextsRead;
8009 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00008010 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00008011}
8012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
8014 if (!DC->hasExternalVisibleStorage())
8015 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00008016
8017 auto It = Lookups.find(DC);
8018 assert(It != Lookups.end() &&
8019 "have external visible storage but no lookup tables");
8020
Craig Topper79be4cd2013-07-05 04:33:53 +00008021 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00008022
Vedant Kumar48b4f762018-04-14 01:40:48 +00008023 for (DeclID ID : It->second.Table.findAll()) {
8024 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00008025 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 }
8027
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 ++NumVisibleDeclContextsRead;
8029
Vedant Kumar48b4f762018-04-14 01:40:48 +00008030 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
8031 SetExternalVisibleDeclsForName(DC, I->first, I->second);
8032 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008033 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
8034}
8035
Richard Smithd88a7f12015-09-01 20:35:42 +00008036const serialization::reader::DeclContextLookupTable *
8037ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
8038 auto I = Lookups.find(Primary);
8039 return I == Lookups.end() ? nullptr : &I->second;
8040}
8041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008042/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00008043/// before receiving the implementation, and codegen depends on this.
8044/// We simulate this by deserializing and passing to consumer the methods of the
8045/// implementation before passing the deserialized implementation decl.
8046static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
8047 ASTConsumer *Consumer) {
8048 assert(ImplD && Consumer);
8049
Aaron Ballmanaff18c02014-03-13 19:03:34 +00008050 for (auto *I : ImplD->methods())
8051 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00008052
8053 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
8054}
8055
Guy Benyei11169dd2012-12-18 14:30:41 +00008056void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008057 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00008058 PassObjCImplDeclToConsumer(ImplD, Consumer);
8059 else
8060 Consumer->HandleInterestingDecl(DeclGroupRef(D));
8061}
8062
8063void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
8064 this->Consumer = Consumer;
8065
Richard Smith9e2341d2015-03-23 03:25:59 +00008066 if (Consumer)
8067 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00008068
8069 if (DeserializationListener)
8070 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00008071}
8072
8073void ASTReader::PrintStats() {
8074 std::fprintf(stderr, "*** AST File Statistics:\n");
8075
8076 unsigned NumTypesLoaded
8077 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
8078 QualType());
8079 unsigned NumDeclsLoaded
8080 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008081 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 unsigned NumIdentifiersLoaded
8083 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
8084 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008085 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 unsigned NumMacrosLoaded
8087 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
8088 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00008089 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 unsigned NumSelectorsLoaded
8091 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
8092 SelectorsLoaded.end(),
8093 Selector());
8094
8095 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
8096 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
8097 NumSLocEntriesRead, TotalNumSLocEntries,
8098 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
8099 if (!TypesLoaded.empty())
8100 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
8101 NumTypesLoaded, (unsigned)TypesLoaded.size(),
8102 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
8103 if (!DeclsLoaded.empty())
8104 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
8105 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
8106 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
8107 if (!IdentifiersLoaded.empty())
8108 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
8109 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
8110 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
8111 if (!MacrosLoaded.empty())
8112 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8113 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
8114 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
8115 if (!SelectorsLoaded.empty())
8116 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
8117 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
8118 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
8119 if (TotalNumStatements)
8120 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
8121 NumStatementsRead, TotalNumStatements,
8122 ((float)NumStatementsRead/TotalNumStatements * 100));
8123 if (TotalNumMacros)
8124 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
8125 NumMacrosRead, TotalNumMacros,
8126 ((float)NumMacrosRead/TotalNumMacros * 100));
8127 if (TotalLexicalDeclContexts)
8128 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
8129 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
8130 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
8131 * 100));
8132 if (TotalVisibleDeclContexts)
8133 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
8134 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
8135 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
8136 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008137 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00008138 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
8139 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
8140 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
8141 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008142 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008143 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
8144 NumMethodPoolHits, NumMethodPoolLookups,
8145 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008146 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008147 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
8148 NumMethodPoolTableHits, NumMethodPoolTableLookups,
8149 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
8150 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008151 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00008152 std::fprintf(stderr,
8153 " %u / %u identifier table lookups succeeded (%f%%)\n",
8154 NumIdentifierLookupHits, NumIdentifierLookups,
8155 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00008156
Douglas Gregore060e572013-01-25 01:03:03 +00008157 if (GlobalIndex) {
8158 std::fprintf(stderr, "\n");
8159 GlobalIndex->printStats();
8160 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008161
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 std::fprintf(stderr, "\n");
8163 dump();
8164 std::fprintf(stderr, "\n");
8165}
8166
8167template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00008168LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00008169dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008170 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00008171 InitialCapacity> &Map) {
8172 if (Map.begin() == Map.end())
8173 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008174
Vedant Kumar48b4f762018-04-14 01:40:48 +00008175 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
8176
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008178 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
8179 I != IEnd; ++I) {
8180 llvm::errs() << " " << I->first << " -> " << I->second->FileName
8181 << "\n";
8182 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008183}
8184
Yaron Kerencdae9412016-01-29 19:38:18 +00008185LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00008186 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
8187 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
8188 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
8189 dumpModuleIDMap("Global type map", GlobalTypeMap);
8190 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
8191 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
8192 dumpModuleIDMap("Global macro map", GlobalMacroMap);
8193 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
8194 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008195 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00008196 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008197
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00008199 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00008200 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00008201}
8202
8203/// Return the amount of memory used by memory buffers, breaking down
8204/// by heap-backed versus mmap'ed memory.
8205void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008206 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00008207 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008208 size_t bytes = buf->getBufferSize();
8209 switch (buf->getBufferKind()) {
8210 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
8211 sizes.malloc_bytes += bytes;
8212 break;
8213 case llvm::MemoryBuffer::MemoryBuffer_MMap:
8214 sizes.mmap_bytes += bytes;
8215 break;
8216 }
8217 }
8218 }
8219}
8220
8221void ASTReader::InitializeSema(Sema &S) {
8222 SemaObj = &S;
8223 S.addExternalSource(this);
8224
8225 // Makes sure any declarations that were deserialized "too early"
8226 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008227 for (uint64_t ID : PreloadedDeclIDs) {
8228 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00008229 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00008230 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008231 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00008232
Richard Smith3d8e97e2013-10-18 06:54:39 +00008233 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 if (!FPPragmaOptions.empty()) {
8235 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00008236 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008237 }
8238
Yaxun Liu5b746652016-12-18 05:18:55 +00008239 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
8240 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
8241 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00008242
8243 UpdateSema();
8244}
8245
8246void ASTReader::UpdateSema() {
8247 assert(SemaObj && "no Sema to update");
8248
8249 // Load the offsets of the declarations that Sema references.
8250 // They will be lazily deserialized when needed.
8251 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00008252 assert(SemaDeclRefs.size() % 3 == 0);
8253 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00008254 if (!SemaObj->StdNamespace)
8255 SemaObj->StdNamespace = SemaDeclRefs[I];
8256 if (!SemaObj->StdBadAlloc)
8257 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00008258 if (!SemaObj->StdAlignValT)
8259 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00008260 }
8261 SemaDeclRefs.clear();
8262 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00008263
Nico Weber779355f2016-03-02 23:22:00 +00008264 // Update the state of pragmas. Use the same API as if we had encountered the
8265 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00008266 if(OptimizeOffPragmaLocation.isValid())
Rui Ueyama49a3ad22019-07-16 04:46:31 +00008267 SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00008268 if (PragmaMSStructState != -1)
8269 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00008270 if (PointersToMembersPragmaLocation.isValid()) {
8271 SemaObj->ActOnPragmaMSPointersToMembers(
8272 (LangOptions::PragmaMSPointersToMembersKind)
8273 PragmaMSPointersToMembersState,
8274 PointersToMembersPragmaLocation);
8275 }
Justin Lebar67a78a62016-10-08 22:15:58 +00008276 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008277
8278 if (PragmaPackCurrentValue) {
8279 // The bottom of the stack might have a default value. It must be adjusted
8280 // to the current value to ensure that the packing state is preserved after
8281 // popping entries that were included/imported from a PCH/module.
8282 bool DropFirst = false;
8283 if (!PragmaPackStack.empty() &&
8284 PragmaPackStack.front().Location.isInvalid()) {
8285 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
8286 "Expected a default alignment value");
8287 SemaObj->PackStack.Stack.emplace_back(
8288 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00008289 SemaObj->PackStack.CurrentPragmaLocation,
8290 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008291 DropFirst = true;
8292 }
8293 for (const auto &Entry :
8294 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
8295 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00008296 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00008297 if (PragmaPackCurrentLocation.isInvalid()) {
8298 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
8299 "Expected a default alignment value");
8300 // Keep the current values.
8301 } else {
8302 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
8303 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
8304 }
8305 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008306}
8307
Richard Smitha8d5b6a2015-07-17 19:51:03 +00008308IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008309 // Note that we are loading an identifier.
8310 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00008311
Douglas Gregor7211ac12013-01-25 23:32:03 +00008312 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00008313 NumIdentifierLookups,
8314 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008315
8316 // We don't need to do identifier table lookups in C++ modules (we preload
8317 // all interesting declarations, and don't need to use the scope for name
8318 // lookups). Perform the lookup in PCH files, though, since we don't build
8319 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00008320 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00008321 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008322 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00008323 break;
8324 } else {
8325 // If there is a global index, look there first to determine which modules
8326 // provably do not have any results for this identifier.
8327 GlobalModuleIndex::HitSet Hits;
8328 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
8329 if (!loadGlobalIndex()) {
8330 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
8331 HitsPtr = &Hits;
8332 }
8333 }
8334
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008335 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00008336 }
8337
Guy Benyei11169dd2012-12-18 14:30:41 +00008338 IdentifierInfo *II = Visitor.getIdentifierInfo();
8339 markIdentifierUpToDate(II);
8340 return II;
8341}
8342
8343namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008344
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008345 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00008346 /// identifiers stored within a set of AST files.
8347 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008348 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 const ASTReader &Reader;
8350
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008351 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00008352 /// the AST reader.
8353 unsigned Index;
8354
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008355 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 /// of the current AST file.
8357 ASTIdentifierLookupTable::key_iterator Current;
8358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008359 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00008360 /// the current AST file.
8361 ASTIdentifierLookupTable::key_iterator End;
8362
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008363 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00008364 bool SkipModules;
8365
Guy Benyei11169dd2012-12-18 14:30:41 +00008366 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00008367 explicit ASTIdentifierIterator(const ASTReader &Reader,
8368 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00008369
Craig Topper3e89dfe2014-03-13 02:13:41 +00008370 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00008371 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008372
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008373} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008374
Ben Langmuir537c5b52016-05-04 00:53:13 +00008375ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
8376 bool SkipModules)
8377 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008378}
8379
8380StringRef ASTIdentifierIterator::Next() {
8381 while (Current == End) {
8382 // If we have exhausted all of our AST files, we're done.
8383 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008384 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00008385
8386 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00008387 ModuleFile &F = Reader.ModuleMgr[Index];
8388 if (SkipModules && F.isModule())
8389 continue;
8390
Vedant Kumar48b4f762018-04-14 01:40:48 +00008391 ASTIdentifierLookupTable *IdTable =
8392 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00008393 Current = IdTable->key_begin();
8394 End = IdTable->key_end();
8395 }
8396
8397 // We have any identifiers remaining in the current AST file; return
8398 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008399 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00008400 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00008401 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00008402}
8403
Ben Langmuir537c5b52016-05-04 00:53:13 +00008404namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008405
Ben Langmuir537c5b52016-05-04 00:53:13 +00008406/// A utility for appending two IdentifierIterators.
8407class ChainedIdentifierIterator : public IdentifierIterator {
8408 std::unique_ptr<IdentifierIterator> Current;
8409 std::unique_ptr<IdentifierIterator> Queued;
8410
8411public:
8412 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
8413 std::unique_ptr<IdentifierIterator> Second)
8414 : Current(std::move(First)), Queued(std::move(Second)) {}
8415
8416 StringRef Next() override {
8417 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008418 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008419
8420 StringRef result = Current->Next();
8421 if (!result.empty())
8422 return result;
8423
8424 // Try the queued iterator, which may itself be empty.
8425 Current.reset();
8426 std::swap(Current, Queued);
8427 return Next();
8428 }
8429};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008430
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008431} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008432
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008433IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008434 if (!loadGlobalIndex()) {
8435 std::unique_ptr<IdentifierIterator> ReaderIter(
8436 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8437 std::unique_ptr<IdentifierIterator> ModulesIter(
8438 GlobalIndex->createIdentifierIterator());
8439 return new ChainedIdentifierIterator(std::move(ReaderIter),
8440 std::move(ModulesIter));
8441 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008442
Guy Benyei11169dd2012-12-18 14:30:41 +00008443 return new ASTIdentifierIterator(*this);
8444}
8445
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008446namespace clang {
8447namespace serialization {
8448
Guy Benyei11169dd2012-12-18 14:30:41 +00008449 class ReadMethodPoolVisitor {
8450 ASTReader &Reader;
8451 Selector Sel;
8452 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008453 unsigned InstanceBits = 0;
8454 unsigned FactoryBits = 0;
8455 bool InstanceHasMoreThanOneDecl = false;
8456 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008457 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8458 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008459
8460 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008461 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008462 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008463 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008464
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008465 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008466 if (!M.SelectorLookupTable)
8467 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008468
Guy Benyei11169dd2012-12-18 14:30:41 +00008469 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008470 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008471 return true;
8472
Richard Smithbdf2d932015-07-30 03:37:16 +00008473 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008474 ASTSelectorLookupTable *PoolTable
8475 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008476 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008477 if (Pos == PoolTable->end())
8478 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008479
Richard Smithbdf2d932015-07-30 03:37:16 +00008480 ++Reader.NumMethodPoolTableHits;
8481 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008482 // FIXME: Not quite happy with the statistics here. We probably should
8483 // disable this tracking when called via LoadSelector.
8484 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008485 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008486 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008487 if (Reader.DeserializationListener)
8488 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008489
Richard Smithbdf2d932015-07-30 03:37:16 +00008490 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8491 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8492 InstanceBits = Data.InstanceBits;
8493 FactoryBits = Data.FactoryBits;
8494 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8495 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008496 return true;
8497 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008498
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008499 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008500 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8501 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008502 }
8503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008504 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008505 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 return FactoryMethods;
8507 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008508
8509 unsigned getInstanceBits() const { return InstanceBits; }
8510 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008511
Nico Weberff4b35e2014-12-27 22:14:15 +00008512 bool instanceHasMoreThanOneDecl() const {
8513 return InstanceHasMoreThanOneDecl;
8514 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008515
Nico Weberff4b35e2014-12-27 22:14:15 +00008516 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008517 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008518
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008519} // namespace serialization
8520} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008521
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008522/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008523static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8524 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008525 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8526 S.addMethodToGlobalList(&List, Methods[I]);
8527 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008528}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008529
Guy Benyei11169dd2012-12-18 14:30:41 +00008530void ASTReader::ReadMethodPool(Selector Sel) {
8531 // Get the selector generation and update it to the current generation.
8532 unsigned &Generation = SelectorGeneration[Sel];
8533 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008534 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008535 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008536
Guy Benyei11169dd2012-12-18 14:30:41 +00008537 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008538 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008539 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008540 ModuleMgr.visit(Visitor);
8541
Guy Benyei11169dd2012-12-18 14:30:41 +00008542 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008543 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008544 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008545
8546 ++NumMethodPoolHits;
8547
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 if (!getSema())
8549 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008550
Guy Benyei11169dd2012-12-18 14:30:41 +00008551 Sema &S = *getSema();
8552 Sema::GlobalMethodPool::iterator Pos
8553 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008554
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008555 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008556 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008557 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008558 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008559
8560 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8561 // when building a module we keep every method individually and may need to
8562 // update hasMoreThanOneDecl as we add the methods.
8563 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8564 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008565}
8566
Manman Rena0f31a02016-04-29 19:04:05 +00008567void ASTReader::updateOutOfDateSelector(Selector Sel) {
8568 if (SelectorOutOfDate[Sel])
8569 ReadMethodPool(Sel);
8570}
8571
Guy Benyei11169dd2012-12-18 14:30:41 +00008572void ASTReader::ReadKnownNamespaces(
8573 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8574 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008575
Vedant Kumar48b4f762018-04-14 01:40:48 +00008576 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8577 if (NamespaceDecl *Namespace
8578 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008579 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008580 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008581}
8582
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008583void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008584 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008585 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008586 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008587 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008588 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008589 Undefined.insert(std::make_pair(D, Loc));
8590 }
8591}
Nick Lewycky8334af82013-01-26 00:35:08 +00008592
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008593void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8594 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8595 Exprs) {
8596 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008597 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008598 uint64_t Count = DelayedDeleteExprs[Idx++];
8599 for (uint64_t C = 0; C < Count; ++C) {
8600 SourceLocation DeleteLoc =
8601 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8602 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8603 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8604 }
8605 }
8606}
8607
Guy Benyei11169dd2012-12-18 14:30:41 +00008608void ASTReader::ReadTentativeDefinitions(
8609 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008610 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8611 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008612 if (Var)
8613 TentativeDefs.push_back(Var);
8614 }
8615 TentativeDefinitions.clear();
8616}
8617
8618void ASTReader::ReadUnusedFileScopedDecls(
8619 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008620 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8621 DeclaratorDecl *D
8622 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 if (D)
8624 Decls.push_back(D);
8625 }
8626 UnusedFileScopedDecls.clear();
8627}
8628
8629void ASTReader::ReadDelegatingConstructors(
8630 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008631 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8632 CXXConstructorDecl *D
8633 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008634 if (D)
8635 Decls.push_back(D);
8636 }
8637 DelegatingCtorDecls.clear();
8638}
8639
8640void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008641 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8642 TypedefNameDecl *D
8643 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008644 if (D)
8645 Decls.push_back(D);
8646 }
8647 ExtVectorDecls.clear();
8648}
8649
Nico Weber72889432014-09-06 01:25:55 +00008650void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8651 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008652 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8653 ++I) {
8654 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8655 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008656 if (D)
8657 Decls.insert(D);
8658 }
8659 UnusedLocalTypedefNameCandidates.clear();
8660}
8661
Guy Benyei11169dd2012-12-18 14:30:41 +00008662void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008663 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 if (ReferencedSelectorsData.empty())
8665 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008666
Guy Benyei11169dd2012-12-18 14:30:41 +00008667 // If there are @selector references added them to its pool. This is for
8668 // implementation of -Wselector.
8669 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8670 unsigned I = 0;
8671 while (I < DataSize) {
8672 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8673 SourceLocation SelLoc
8674 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8675 Sels.push_back(std::make_pair(Sel, SelLoc));
8676 }
8677 ReferencedSelectorsData.clear();
8678}
8679
8680void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008681 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008682 if (WeakUndeclaredIdentifiers.empty())
8683 return;
8684
8685 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008686 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008688 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008689 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8690 SourceLocation Loc
8691 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8692 bool Used = WeakUndeclaredIdentifiers[I++];
8693 WeakInfo WI(AliasId, Loc);
8694 WI.setUsed(Used);
8695 WeakIDs.push_back(std::make_pair(WeakId, WI));
8696 }
8697 WeakUndeclaredIdentifiers.clear();
8698}
8699
8700void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8701 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8702 ExternalVTableUse VT;
8703 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8704 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8705 VT.DefinitionRequired = VTableUses[Idx++];
8706 VTables.push_back(VT);
8707 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008708
Guy Benyei11169dd2012-12-18 14:30:41 +00008709 VTableUses.clear();
8710}
8711
8712void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008713 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008714 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008715 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008716 SourceLocation Loc
8717 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8718
8719 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008720 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008721 PendingInstantiations.clear();
8722}
8723
Richard Smithe40f2ba2013-08-07 21:41:30 +00008724void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008725 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8726 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008727 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8728 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008729 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008730
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00008731 auto LT = std::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008732 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8733
8734 ModuleFile *F = getOwningModuleFile(LT->D);
8735 assert(F && "No module");
8736
8737 unsigned TokN = LateParsedTemplates[Idx++];
8738 LT->Toks.reserve(TokN);
8739 for (unsigned T = 0; T < TokN; ++T)
8740 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8741
Justin Lebar28f09c52016-10-10 16:26:08 +00008742 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008743 }
8744
8745 LateParsedTemplates.clear();
8746}
8747
Guy Benyei11169dd2012-12-18 14:30:41 +00008748void ASTReader::LoadSelector(Selector Sel) {
8749 // It would be complicated to avoid reading the methods anyway. So don't.
8750 ReadMethodPool(Sel);
8751}
8752
8753void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8754 assert(ID && "Non-zero identifier ID required");
8755 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8756 IdentifiersLoaded[ID - 1] = II;
8757 if (DeserializationListener)
8758 DeserializationListener->IdentifierRead(ID, II);
8759}
8760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008761/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008762/// identifier.
8763///
8764/// If the AST reader is currently in a state where the given declaration IDs
8765/// cannot safely be resolved, they are queued until it is safe to resolve
8766/// them.
8767///
8768/// \param II an IdentifierInfo that refers to one or more globally-visible
8769/// declarations.
8770///
8771/// \param DeclIDs the set of declaration IDs with the name @p II that are
8772/// visible at global scope.
8773///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008774/// \param Decls if non-null, this vector will be populated with the set of
8775/// deserialized declarations. These declarations will not be pushed into
8776/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008777void
8778ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8779 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008780 SmallVectorImpl<Decl *> *Decls) {
8781 if (NumCurrentElementsDeserializing && !Decls) {
8782 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 return;
8784 }
8785
Vedant Kumar48b4f762018-04-14 01:40:48 +00008786 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008787 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008788 // Queue this declaration so that it will be added to the
8789 // translation unit scope and identifier's declaration chain
8790 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008791 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008792 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008794
Vedant Kumar48b4f762018-04-14 01:40:48 +00008795 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008796
8797 // If we're simply supposed to record the declarations, do so now.
8798 if (Decls) {
8799 Decls->push_back(D);
8800 continue;
8801 }
8802
8803 // Introduce this declaration into the translation-unit scope
8804 // and add it to the declaration chain for this identifier, so
8805 // that (unqualified) name lookup will find it.
8806 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008807 }
8808}
8809
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008810IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008811 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008812 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008813
8814 if (IdentifiersLoaded.empty()) {
8815 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008816 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008817 }
8818
8819 ID -= 1;
8820 if (!IdentifiersLoaded[ID]) {
8821 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8822 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8823 ModuleFile *M = I->second;
8824 unsigned Index = ID - M->BaseIdentifierID;
8825 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8826
8827 // All of the strings in the AST file are preceded by a 16-bit length.
8828 // Extract that 16-bit length to avoid having to execute strlen().
8829 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8830 // unsigned integers. This is important to avoid integer overflow when
8831 // we cast them to 'unsigned'.
8832 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8833 unsigned StrLen = (((unsigned) StrLenPtr[0])
8834 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008835 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8836 IdentifiersLoaded[ID] = &II;
8837 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008838 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008839 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008840 }
8841
8842 return IdentifiersLoaded[ID];
8843}
8844
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008845IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8846 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008847}
8848
8849IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8850 if (LocalID < NUM_PREDEF_IDENT_IDS)
8851 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008852
Richard Smith37a93df2017-02-18 00:32:02 +00008853 if (!M.ModuleOffsetMap.empty())
8854 ReadModuleOffsetMap(M);
8855
Guy Benyei11169dd2012-12-18 14:30:41 +00008856 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8857 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008858 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008859 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008860
Guy Benyei11169dd2012-12-18 14:30:41 +00008861 return LocalID + I->second;
8862}
8863
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008864MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008865 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008866 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008867
8868 if (MacrosLoaded.empty()) {
8869 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008870 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008871 }
8872
8873 ID -= NUM_PREDEF_MACRO_IDS;
8874 if (!MacrosLoaded[ID]) {
8875 GlobalMacroMapType::iterator I
8876 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8877 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8878 ModuleFile *M = I->second;
8879 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008880 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008881
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008882 if (DeserializationListener)
8883 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8884 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008885 }
8886
8887 return MacrosLoaded[ID];
8888}
8889
8890MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8891 if (LocalID < NUM_PREDEF_MACRO_IDS)
8892 return LocalID;
8893
Richard Smith37a93df2017-02-18 00:32:02 +00008894 if (!M.ModuleOffsetMap.empty())
8895 ReadModuleOffsetMap(M);
8896
Guy Benyei11169dd2012-12-18 14:30:41 +00008897 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8898 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8899 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8900
8901 return LocalID + I->second;
8902}
8903
8904serialization::SubmoduleID
8905ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8906 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8907 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008908
Richard Smith37a93df2017-02-18 00:32:02 +00008909 if (!M.ModuleOffsetMap.empty())
8910 ReadModuleOffsetMap(M);
8911
Guy Benyei11169dd2012-12-18 14:30:41 +00008912 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8913 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008914 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008915 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008916
Guy Benyei11169dd2012-12-18 14:30:41 +00008917 return LocalID + I->second;
8918}
8919
8920Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8921 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8922 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008923 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008925
Guy Benyei11169dd2012-12-18 14:30:41 +00008926 if (GlobalID > SubmodulesLoaded.size()) {
8927 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008928 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008929 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008930
Guy Benyei11169dd2012-12-18 14:30:41 +00008931 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8932}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008933
8934Module *ASTReader::getModule(unsigned ID) {
8935 return getSubmodule(ID);
8936}
8937
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008938bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8939 ModuleFile *MF = getOwningModuleFile(D);
8940 return MF && MF->PCHHasObjectFile;
8941}
8942
Richard Smithd88a7f12015-09-01 20:35:42 +00008943ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8944 if (ID & 1) {
8945 // It's a module, look it up by submodule ID.
8946 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8947 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8948 } else {
8949 // It's a prefix (preamble, PCH, ...). Look it up by index.
8950 unsigned IndexFromEnd = ID >> 1;
8951 assert(IndexFromEnd && "got reference to unknown module file");
8952 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8953 }
8954}
8955
8956unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8957 if (!F)
8958 return 1;
8959
8960 // For a file representing a module, use the submodule ID of the top-level
8961 // module as the file ID. For any other kind of file, the number of such
8962 // files loaded beforehand will be the same on reload.
8963 // FIXME: Is this true even if we have an explicit module file and a PCH?
8964 if (F->isModule())
8965 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8966
8967 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008968 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008969 assert(I != PCHModules.end() && "emitting reference to unknown file");
8970 return (I - PCHModules.end()) << 1;
8971}
8972
Adrian Prantl15bcf702015-06-30 17:39:43 +00008973llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8974ASTReader::getSourceDescriptor(unsigned ID) {
8975 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008976 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008977
8978 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008979 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008980 const auto &PCHChain = ModuleMgr.pch_modules();
8981 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008982 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008983 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008984 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8985 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8986 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008987 }
8988 return None;
8989}
8990
David Blaikie1ac9c982017-04-11 21:13:37 +00008991ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008992 auto I = DefinitionSource.find(FD);
8993 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008994 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008995 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008996}
8997
Guy Benyei11169dd2012-12-18 14:30:41 +00008998Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8999 return DecodeSelector(getGlobalSelectorID(M, LocalID));
9000}
9001
9002Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
9003 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009004 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009005
9006 if (ID > SelectorsLoaded.size()) {
9007 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009008 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00009009 }
9010
Craig Toppera13603a2014-05-22 05:54:18 +00009011 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009012 // Load this selector from the selector table.
9013 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
9014 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
9015 ModuleFile &M = *I->second;
9016 ASTSelectorLookupTrait Trait(*this, M);
9017 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
9018 SelectorsLoaded[ID - 1] =
9019 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
9020 if (DeserializationListener)
9021 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
9022 }
9023
9024 return SelectorsLoaded[ID - 1];
9025}
9026
9027Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
9028 return DecodeSelector(ID);
9029}
9030
9031uint32_t ASTReader::GetNumExternalSelectors() {
9032 // ID 0 (the null selector) is considered an external selector.
9033 return getTotalNumSelectors() + 1;
9034}
9035
9036serialization::SelectorID
9037ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
9038 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
9039 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009040
Richard Smith37a93df2017-02-18 00:32:02 +00009041 if (!M.ModuleOffsetMap.empty())
9042 ReadModuleOffsetMap(M);
9043
Guy Benyei11169dd2012-12-18 14:30:41 +00009044 ContinuousRangeMap<uint32_t, int, 2>::iterator I
9045 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009046 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00009047 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009048
Guy Benyei11169dd2012-12-18 14:30:41 +00009049 return LocalID + I->second;
9050}
9051
9052DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009053ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009054 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009055 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009056 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009057 switch (Kind) {
9058 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00009059 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009060
9061 case DeclarationName::ObjCZeroArgSelector:
9062 case DeclarationName::ObjCOneArgSelector:
9063 case DeclarationName::ObjCMultiArgSelector:
9064 return DeclarationName(ReadSelector(F, Record, Idx));
9065
9066 case DeclarationName::CXXConstructorName:
9067 return Context.DeclarationNames.getCXXConstructorName(
9068 Context.getCanonicalType(readType(F, Record, Idx)));
9069
9070 case DeclarationName::CXXDestructorName:
9071 return Context.DeclarationNames.getCXXDestructorName(
9072 Context.getCanonicalType(readType(F, Record, Idx)));
9073
Richard Smith35845152017-02-07 01:37:30 +00009074 case DeclarationName::CXXDeductionGuideName:
9075 return Context.DeclarationNames.getCXXDeductionGuideName(
9076 ReadDeclAs<TemplateDecl>(F, Record, Idx));
9077
Guy Benyei11169dd2012-12-18 14:30:41 +00009078 case DeclarationName::CXXConversionFunctionName:
9079 return Context.DeclarationNames.getCXXConversionFunctionName(
9080 Context.getCanonicalType(readType(F, Record, Idx)));
9081
9082 case DeclarationName::CXXOperatorName:
9083 return Context.DeclarationNames.getCXXOperatorName(
9084 (OverloadedOperatorKind)Record[Idx++]);
9085
9086 case DeclarationName::CXXLiteralOperatorName:
9087 return Context.DeclarationNames.getCXXLiteralOperatorName(
9088 GetIdentifierInfo(F, Record, Idx));
9089
9090 case DeclarationName::CXXUsingDirective:
9091 return DeclarationName::getUsingDirectiveName();
9092 }
9093
9094 llvm_unreachable("Invalid NameKind!");
9095}
9096
9097void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
9098 DeclarationNameLoc &DNLoc,
9099 DeclarationName Name,
9100 const RecordData &Record, unsigned &Idx) {
9101 switch (Name.getNameKind()) {
9102 case DeclarationName::CXXConstructorName:
9103 case DeclarationName::CXXDestructorName:
9104 case DeclarationName::CXXConversionFunctionName:
9105 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
9106 break;
9107
9108 case DeclarationName::CXXOperatorName:
9109 DNLoc.CXXOperatorName.BeginOpNameLoc
9110 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9111 DNLoc.CXXOperatorName.EndOpNameLoc
9112 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9113 break;
9114
9115 case DeclarationName::CXXLiteralOperatorName:
9116 DNLoc.CXXLiteralOperatorName.OpNameLoc
9117 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
9118 break;
9119
9120 case DeclarationName::Identifier:
9121 case DeclarationName::ObjCZeroArgSelector:
9122 case DeclarationName::ObjCOneArgSelector:
9123 case DeclarationName::ObjCMultiArgSelector:
9124 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00009125 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00009126 break;
9127 }
9128}
9129
9130void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
9131 DeclarationNameInfo &NameInfo,
9132 const RecordData &Record, unsigned &Idx) {
9133 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
9134 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
9135 DeclarationNameLoc DNLoc;
9136 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
9137 NameInfo.setInfo(DNLoc);
9138}
9139
9140void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
9141 const RecordData &Record, unsigned &Idx) {
9142 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
9143 unsigned NumTPLists = Record[Idx++];
9144 Info.NumTemplParamLists = NumTPLists;
9145 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009146 Info.TemplParamLists =
9147 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00009148 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00009149 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
9150 }
9151}
9152
9153TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009154ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009155 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009156 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009157 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009158 switch (Kind) {
9159 case TemplateName::Template:
9160 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
9161
9162 case TemplateName::OverloadedTemplate: {
9163 unsigned size = Record[Idx++];
9164 UnresolvedSet<8> Decls;
9165 while (size--)
9166 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
9167
9168 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
9169 }
9170
Richard Smithb23c5e82019-05-09 03:31:27 +00009171 case TemplateName::AssumedTemplate: {
9172 DeclarationName Name = ReadDeclarationName(F, Record, Idx);
9173 return Context.getAssumedTemplateName(Name);
9174 }
9175
Guy Benyei11169dd2012-12-18 14:30:41 +00009176 case TemplateName::QualifiedTemplate: {
9177 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9178 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009179 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009180 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
9181 }
9182
9183 case TemplateName::DependentTemplate: {
9184 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
9185 if (Record[Idx++]) // isIdentifier
9186 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009187 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009188 Idx));
9189 return Context.getDependentTemplateName(NNS,
9190 (OverloadedOperatorKind)Record[Idx++]);
9191 }
9192
9193 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009194 TemplateTemplateParmDecl *param
9195 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
9196 if (!param) return TemplateName();
9197 TemplateName replacement = ReadTemplateName(F, Record, Idx);
9198 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00009199 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009200
Guy Benyei11169dd2012-12-18 14:30:41 +00009201 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009202 TemplateTemplateParmDecl *Param
9203 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009204 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009205 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009206
Guy Benyei11169dd2012-12-18 14:30:41 +00009207 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
9208 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009209 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009210
Guy Benyei11169dd2012-12-18 14:30:41 +00009211 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
9212 }
9213 }
9214
9215 llvm_unreachable("Unhandled template name kind!");
9216}
9217
Richard Smith2bb3c342015-08-09 01:05:31 +00009218TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
9219 const RecordData &Record,
9220 unsigned &Idx,
9221 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009222 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00009223 if (Canonicalize) {
9224 // The caller wants a canonical template argument. Sometimes the AST only
9225 // wants template arguments in canonical form (particularly as the template
9226 // argument lists of template specializations) so ensure we preserve that
9227 // canonical form across serialization.
9228 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
9229 return Context.getCanonicalTemplateArgument(Arg);
9230 }
9231
Vedant Kumar48b4f762018-04-14 01:40:48 +00009232 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009233 switch (Kind) {
9234 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00009235 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00009236 case TemplateArgument::Type:
9237 return TemplateArgument(readType(F, Record, Idx));
9238 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009239 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00009240 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009241 }
9242 case TemplateArgument::NullPtr:
9243 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
9244 case TemplateArgument::Integral: {
9245 llvm::APSInt Value = ReadAPSInt(Record, Idx);
9246 QualType T = readType(F, Record, Idx);
9247 return TemplateArgument(Context, Value, T);
9248 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009249 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00009250 return TemplateArgument(ReadTemplateName(F, Record, Idx));
9251 case TemplateArgument::TemplateExpansion: {
9252 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00009253 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00009254 if (unsigned NumExpansions = Record[Idx++])
9255 NumTemplateExpansions = NumExpansions - 1;
9256 return TemplateArgument(Name, NumTemplateExpansions);
9257 }
9258 case TemplateArgument::Expression:
9259 return TemplateArgument(ReadExpr(F));
9260 case TemplateArgument::Pack: {
9261 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00009262 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00009263 for (unsigned I = 0; I != NumArgs; ++I)
9264 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00009265 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00009266 }
9267 }
9268
9269 llvm_unreachable("Unhandled template argument kind!");
9270}
9271
9272TemplateParameterList *
9273ASTReader::ReadTemplateParameterList(ModuleFile &F,
9274 const RecordData &Record, unsigned &Idx) {
9275 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
9276 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
9277 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
9278
9279 unsigned NumParams = Record[Idx++];
9280 SmallVector<NamedDecl *, 16> Params;
9281 Params.reserve(NumParams);
9282 while (NumParams--)
9283 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
9284
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00009285 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00009286 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
9287 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00009288 return TemplateParams;
9289}
9290
9291void
9292ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00009293ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00009294 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00009295 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009296 unsigned NumTemplateArgs = Record[Idx++];
9297 TemplArgs.reserve(NumTemplateArgs);
9298 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00009299 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00009300}
9301
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009302/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00009303void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00009304 const RecordData &Record, unsigned &Idx) {
9305 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009306 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00009307 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00009308 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009309 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00009310 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00009311 }
9312}
9313
9314CXXBaseSpecifier
9315ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
9316 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009317 bool isVirtual = static_cast<bool>(Record[Idx++]);
9318 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
9319 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
9320 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009321 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
9322 SourceRange Range = ReadSourceRange(F, Record, Idx);
9323 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009324 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00009325 EllipsisLoc);
9326 Result.setInheritConstructors(inheritConstructors);
9327 return Result;
9328}
9329
Richard Smithc2bb8182015-03-24 06:36:48 +00009330CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00009331ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
9332 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009333 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009334 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009335 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00009336 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00009337 for (unsigned i = 0; i != NumInitializers; ++i) {
9338 TypeSourceInfo *TInfo = nullptr;
9339 bool IsBaseVirtual = false;
9340 FieldDecl *Member = nullptr;
9341 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009342
Vedant Kumar48b4f762018-04-14 01:40:48 +00009343 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00009344 switch (Type) {
9345 case CTOR_INITIALIZER_BASE:
9346 TInfo = GetTypeSourceInfo(F, Record, Idx);
9347 IsBaseVirtual = Record[Idx++];
9348 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009349
Richard Smithc2bb8182015-03-24 06:36:48 +00009350 case CTOR_INITIALIZER_DELEGATING:
9351 TInfo = GetTypeSourceInfo(F, Record, Idx);
9352 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009353
Richard Smithc2bb8182015-03-24 06:36:48 +00009354 case CTOR_INITIALIZER_MEMBER:
9355 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
9356 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009357
Richard Smithc2bb8182015-03-24 06:36:48 +00009358 case CTOR_INITIALIZER_INDIRECT_MEMBER:
9359 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
9360 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009361 }
Richard Smithc2bb8182015-03-24 06:36:48 +00009362
9363 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
9364 Expr *Init = ReadExpr(F);
9365 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
9366 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00009367
9368 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00009369 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00009370 BOMInit = new (Context)
9371 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
9372 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009373 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00009374 BOMInit = new (Context)
9375 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00009376 else if (Member)
9377 BOMInit = new (Context)
9378 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
9379 Init, RParenLoc);
9380 else
9381 BOMInit = new (Context)
9382 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
9383 LParenLoc, Init, RParenLoc);
9384
Richard Smith418ed822016-12-14 19:45:03 +00009385 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00009386 unsigned SourceOrder = Record[Idx++];
9387 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00009388 }
9389
Richard Smithc2bb8182015-03-24 06:36:48 +00009390 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00009391 }
9392
Richard Smithc2bb8182015-03-24 06:36:48 +00009393 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00009394}
9395
9396NestedNameSpecifier *
9397ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
9398 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009399 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009400 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00009401 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00009402 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009403 NestedNameSpecifier::SpecifierKind Kind
9404 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009405 switch (Kind) {
9406 case NestedNameSpecifier::Identifier: {
9407 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
9408 NNS = NestedNameSpecifier::Create(Context, Prev, II);
9409 break;
9410 }
9411
9412 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009413 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009414 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
9415 break;
9416 }
9417
9418 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009419 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009420 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
9421 break;
9422 }
9423
9424 case NestedNameSpecifier::TypeSpec:
9425 case NestedNameSpecifier::TypeSpecWithTemplate: {
9426 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
9427 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00009428 return nullptr;
9429
Guy Benyei11169dd2012-12-18 14:30:41 +00009430 bool Template = Record[Idx++];
9431 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
9432 break;
9433 }
9434
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009435 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00009436 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
9437 // No associated value, and there can't be a prefix.
9438 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00009439
9440 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009441 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009442 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
9443 break;
9444 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009445 }
9446 Prev = NNS;
9447 }
9448 return NNS;
9449}
9450
9451NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009452ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009453 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009454 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009455 unsigned N = Record[Idx++];
9456 NestedNameSpecifierLocBuilder Builder;
9457 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009458 NestedNameSpecifier::SpecifierKind Kind
9459 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009460 switch (Kind) {
9461 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009462 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009463 SourceRange Range = ReadSourceRange(F, Record, Idx);
9464 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9465 break;
9466 }
9467
9468 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009469 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009470 SourceRange Range = ReadSourceRange(F, Record, Idx);
9471 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9472 break;
9473 }
9474
9475 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009476 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009477 SourceRange Range = ReadSourceRange(F, Record, Idx);
9478 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9479 break;
9480 }
9481
9482 case NestedNameSpecifier::TypeSpec:
9483 case NestedNameSpecifier::TypeSpecWithTemplate: {
9484 bool Template = Record[Idx++];
9485 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9486 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009487 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009488 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9489
9490 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009491 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009492 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9493 T->getTypeLoc(), ColonColonLoc);
9494 break;
9495 }
9496
9497 case NestedNameSpecifier::Global: {
9498 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9499 Builder.MakeGlobal(Context, ColonColonLoc);
9500 break;
9501 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009502
9503 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009504 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009505 SourceRange Range = ReadSourceRange(F, Record, Idx);
9506 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9507 break;
9508 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009509 }
9510 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009511
Guy Benyei11169dd2012-12-18 14:30:41 +00009512 return Builder.getWithLocInContext(Context);
9513}
9514
9515SourceRange
9516ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9517 unsigned &Idx) {
9518 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9519 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9520 return SourceRange(beg, end);
9521}
9522
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00009523static FixedPointSemantics
9524ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
9525 unsigned &Idx) {
9526 unsigned Width = Record[Idx++];
9527 unsigned Scale = Record[Idx++];
9528 uint64_t Tmp = Record[Idx++];
9529 bool IsSigned = Tmp & 0x1;
9530 bool IsSaturated = Tmp & 0x2;
9531 bool HasUnsignedPadding = Tmp & 0x4;
9532 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
9533 HasUnsignedPadding);
9534}
9535
9536APValue ASTReader::ReadAPValue(const RecordData &Record, unsigned &Idx) {
9537 unsigned Kind = Record[Idx++];
9538 switch (Kind) {
9539 case APValue::None:
9540 return APValue();
9541 case APValue::Indeterminate:
9542 return APValue::IndeterminateValue();
9543 case APValue::Int:
9544 return APValue(ReadAPSInt(Record, Idx));
9545 case APValue::Float: {
9546 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics(
9547 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9548 return APValue(ReadAPFloat(Record, FloatSema, Idx));
9549 }
9550 case APValue::FixedPoint: {
9551 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
9552 return APValue(APFixedPoint(ReadAPInt(Record, Idx), FPSema));
9553 }
9554 case APValue::ComplexInt: {
9555 llvm::APSInt First = ReadAPSInt(Record, Idx);
9556 return APValue(std::move(First), ReadAPSInt(Record, Idx));
9557 }
9558 case APValue::ComplexFloat: {
9559 const llvm::fltSemantics &FloatSema1 = llvm::APFloatBase::EnumToSemantics(
9560 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9561 llvm::APFloat First = ReadAPFloat(Record, FloatSema1, Idx);
9562 const llvm::fltSemantics &FloatSema2 = llvm::APFloatBase::EnumToSemantics(
9563 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9564 return APValue(std::move(First), ReadAPFloat(Record, FloatSema2, Idx));
9565 }
9566 case APValue::LValue:
9567 case APValue::Vector:
9568 case APValue::Array:
9569 case APValue::Struct:
9570 case APValue::Union:
9571 case APValue::MemberPointer:
9572 case APValue::AddrLabelDiff:
9573 // TODO : Handle all these APValue::ValueKind.
9574 return APValue();
9575 }
9576 llvm_unreachable("Invalid APValue::ValueKind");
9577}
9578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009579/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009580llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9581 unsigned BitWidth = Record[Idx++];
9582 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9583 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9584 Idx += NumWords;
9585 return Result;
9586}
9587
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009588/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009589llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9590 bool isUnsigned = Record[Idx++];
9591 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9592}
9593
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009594/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009595llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9596 const llvm::fltSemantics &Sem,
9597 unsigned &Idx) {
9598 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009599}
9600
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009601// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009602std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9603 unsigned Len = Record[Idx++];
9604 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9605 Idx += Len;
9606 return Result;
9607}
9608
Richard Smith7ed1bc92014-12-05 22:42:13 +00009609std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9610 unsigned &Idx) {
9611 std::string Filename = ReadString(Record, Idx);
9612 ResolveImportedPath(F, Filename);
9613 return Filename;
9614}
9615
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009616std::string ASTReader::ReadPath(StringRef BaseDirectory,
9617 const RecordData &Record, unsigned &Idx) {
9618 std::string Filename = ReadString(Record, Idx);
9619 if (!BaseDirectory.empty())
9620 ResolveImportedPath(Filename, BaseDirectory);
9621 return Filename;
9622}
9623
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009624VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009625 unsigned &Idx) {
9626 unsigned Major = Record[Idx++];
9627 unsigned Minor = Record[Idx++];
9628 unsigned Subminor = Record[Idx++];
9629 if (Minor == 0)
9630 return VersionTuple(Major);
9631 if (Subminor == 0)
9632 return VersionTuple(Major, Minor - 1);
9633 return VersionTuple(Major, Minor - 1, Subminor - 1);
9634}
9635
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009636CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009637 const RecordData &Record,
9638 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009639 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009640 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009641}
9642
Richard Smith37a93df2017-02-18 00:32:02 +00009643DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009644 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009645}
9646
Richard Smith37a93df2017-02-18 00:32:02 +00009647DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009648 return Diags.Report(Loc, DiagID);
9649}
9650
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009651/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009652/// preprocessor.
9653IdentifierTable &ASTReader::getIdentifierTable() {
9654 return PP.getIdentifierTable();
9655}
9656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009657/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009658/// statement.
9659void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009660 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009661 "Already have a SwitchCase with this ID");
9662 (*CurrSwitchCaseStmts)[ID] = SC;
9663}
9664
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009665/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009666SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009667 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009668 return (*CurrSwitchCaseStmts)[ID];
9669}
9670
9671void ASTReader::ClearSwitchCaseIDs() {
9672 CurrSwitchCaseStmts->clear();
9673}
9674
9675void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009676 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009677 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009678 for (SmallVectorImpl<std::pair<BitstreamCursor,
9679 serialization::ModuleFile *>>::iterator
9680 I = CommentsCursors.begin(),
9681 E = CommentsCursors.end();
9682 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009683 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009684 BitstreamCursor &Cursor = I->first;
9685 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009686 SavedStreamPosition SavedPosition(Cursor);
9687
9688 RecordData Record;
9689 while (true) {
JF Bastien0e828952019-06-26 19:50:12 +00009690 Expected<llvm::BitstreamEntry> MaybeEntry =
9691 Cursor.advanceSkippingSubblocks(
9692 BitstreamCursor::AF_DontPopBlockAtEnd);
9693 if (!MaybeEntry) {
9694 Error(MaybeEntry.takeError());
9695 return;
9696 }
9697 llvm::BitstreamEntry Entry = MaybeEntry.get();
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009698
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009699 switch (Entry.Kind) {
9700 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9701 case llvm::BitstreamEntry::Error:
9702 Error("malformed block record in AST file");
9703 return;
9704 case llvm::BitstreamEntry::EndBlock:
9705 goto NextCursor;
9706 case llvm::BitstreamEntry::Record:
9707 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009708 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009709 }
9710
9711 // Read a record.
9712 Record.clear();
JF Bastien0e828952019-06-26 19:50:12 +00009713 Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
9714 if (!MaybeComment) {
9715 Error(MaybeComment.takeError());
9716 return;
9717 }
9718 switch ((CommentRecordTypes)MaybeComment.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009719 case COMMENTS_RAW_COMMENT: {
9720 unsigned Idx = 0;
9721 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009722 RawComment::CommentKind Kind =
9723 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009724 bool IsTrailingComment = Record[Idx++];
9725 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009726 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009727 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009728 break;
9729 }
9730 }
9731 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009732 NextCursor:
Jan Korousf31d8df2019-08-13 18:11:44 +00009733 llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
9734 FileToOffsetToComment;
9735 for (RawComment *C : Comments) {
9736 SourceLocation CommentLoc = C->getBeginLoc();
9737 if (CommentLoc.isValid()) {
9738 std::pair<FileID, unsigned> Loc =
9739 SourceMgr.getDecomposedLoc(CommentLoc);
9740 if (Loc.first.isValid())
9741 Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
9742 }
9743 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009744 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009745}
9746
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009747void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9748 bool IncludeSystem, bool Complain,
9749 llvm::function_ref<void(const serialization::InputFile &IF,
9750 bool isSystem)> Visitor) {
9751 unsigned NumUserInputs = MF.NumUserInputFiles;
9752 unsigned NumInputs = MF.InputFilesLoaded.size();
9753 assert(NumUserInputs <= NumInputs);
9754 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9755 for (unsigned I = 0; I < N; ++I) {
9756 bool IsSystem = I >= NumUserInputs;
9757 InputFile IF = getInputFile(MF, I+1, Complain);
9758 Visitor(IF, IsSystem);
9759 }
9760}
9761
Richard Smithf3f84612017-06-29 02:19:42 +00009762void ASTReader::visitTopLevelModuleMaps(
9763 serialization::ModuleFile &MF,
9764 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9765 unsigned NumInputs = MF.InputFilesLoaded.size();
9766 for (unsigned I = 0; I < NumInputs; ++I) {
9767 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9768 if (IFI.TopLevelModuleMap)
9769 // FIXME: This unnecessarily re-reads the InputFileInfo.
9770 if (auto *FE = getInputFile(MF, I + 1).getFile())
9771 Visitor(FE);
9772 }
9773}
9774
Richard Smithcd45dbc2014-04-19 03:48:30 +00009775std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9776 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009777 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009778 return M->getFullModuleName();
9779
9780 // Otherwise, use the name of the top-level module the decl is within.
9781 if (ModuleFile *M = getOwningModuleFile(D))
9782 return M->ModuleName;
9783
9784 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009785 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009786}
9787
Guy Benyei11169dd2012-12-18 14:30:41 +00009788void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009789 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009790 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009791 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009792 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009793 // If any identifiers with corresponding top-level declarations have
9794 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009795 using TopLevelDeclsMap =
9796 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009797 TopLevelDeclsMap TopLevelDecls;
9798
Guy Benyei11169dd2012-12-18 14:30:41 +00009799 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009800 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009801 SmallVector<uint32_t, 4> DeclIDs =
9802 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009803 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009804
9805 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009806 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009807
Richard Smitha62d1982018-08-03 01:00:01 +00009808 // Load each function type that we deferred loading because it was a
9809 // deduced type that might refer to a local type declared within itself.
9810 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9811 auto *FD = PendingFunctionTypes[I].first;
9812 FD->setType(GetType(PendingFunctionTypes[I].second));
9813
9814 // If we gave a function a deduced return type, remember that we need to
9815 // propagate that along the redeclaration chain.
9816 auto *DT = FD->getReturnType()->getContainedDeducedType();
9817 if (DT && DT->isDeduced())
9818 PendingDeducedTypeUpdates.insert(
9819 {FD->getCanonicalDecl(), FD->getReturnType()});
9820 }
9821 PendingFunctionTypes.clear();
9822
Richard Smith851072e2014-05-19 20:59:20 +00009823 // For each decl chain that we wanted to complete while deserializing, mark
9824 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009825 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9826 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9827 }
Richard Smith851072e2014-05-19 20:59:20 +00009828 PendingIncompleteDeclChains.clear();
9829
Guy Benyei11169dd2012-12-18 14:30:41 +00009830 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009831 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009832 loadPendingDeclChain(PendingDeclChains[I].first,
9833 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009834 PendingDeclChains.clear();
9835
Douglas Gregor6168bd22013-02-18 15:53:43 +00009836 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009837 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9838 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9839 IdentifierInfo *II = TLD->first;
9840 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9841 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009842 }
9843 }
9844
Guy Benyei11169dd2012-12-18 14:30:41 +00009845 // Load any pending macro definitions.
9846 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009847 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9848 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9849 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9850 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009851 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009852 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009853 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009854 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009855 resolvePendingMacro(II, Info);
9856 }
9857 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009858 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009859 ++IDIdx) {
9860 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009861 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009862 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009863 }
9864 }
9865 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009866
9867 // Wire up the DeclContexts for Decls that we delayed setting until
9868 // recursive loading is completed.
9869 while (!PendingDeclContextInfos.empty()) {
9870 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9871 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009872 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9873 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009874 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9875 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009876
Richard Smithd1c46742014-04-30 02:24:17 +00009877 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009878 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009879 auto Update = PendingUpdateRecords.pop_back_val();
9880 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009881 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009882 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009883 }
Richard Smith8a639892015-01-24 01:07:20 +00009884
9885 // At this point, all update records for loaded decls are in place, so any
9886 // fake class definitions should have become real.
9887 assert(PendingFakeDefinitionData.empty() &&
9888 "faked up a class definition but never saw the real one");
9889
Guy Benyei11169dd2012-12-18 14:30:41 +00009890 // If we deserialized any C++ or Objective-C class definitions, any
9891 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009892 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009893 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009894 for (Decl *D : PendingDefinitions) {
9895 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9896 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009897 // Make sure that the TagType points at the definition.
9898 const_cast<TagType*>(TagT)->decl = TD;
9899 }
Richard Smith8ce51082015-03-11 01:44:51 +00009900
Vedant Kumar48b4f762018-04-14 01:40:48 +00009901 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009902 for (auto *R = getMostRecentExistingDecl(RD); R;
9903 R = R->getPreviousDecl()) {
9904 assert((R == D) ==
9905 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009906 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009907 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009908 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009909 }
9910
9911 continue;
9912 }
Richard Smith8ce51082015-03-11 01:44:51 +00009913
Vedant Kumar48b4f762018-04-14 01:40:48 +00009914 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009915 // Make sure that the ObjCInterfaceType points at the definition.
9916 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9917 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009918
9919 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9920 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9921
Guy Benyei11169dd2012-12-18 14:30:41 +00009922 continue;
9923 }
Richard Smith8ce51082015-03-11 01:44:51 +00009924
Vedant Kumar48b4f762018-04-14 01:40:48 +00009925 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009926 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9927 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9928
Guy Benyei11169dd2012-12-18 14:30:41 +00009929 continue;
9930 }
Richard Smith8ce51082015-03-11 01:44:51 +00009931
Vedant Kumar48b4f762018-04-14 01:40:48 +00009932 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009933 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9934 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009935 }
9936 PendingDefinitions.clear();
9937
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009938 // Load the bodies of any functions or methods we've encountered. We do
9939 // this now (delayed) so that we can be sure that the declaration chains
9940 // have been fully wired up (hasBody relies on this).
9941 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009942 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9943 PBEnd = PendingBodies.end();
9944 PB != PBEnd; ++PB) {
9945 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009946 // For a function defined inline within a class template, force the
9947 // canonical definition to be the one inside the canonical definition of
9948 // the template. This ensures that we instantiate from a correct view
9949 // of the template.
9950 //
9951 // Sadly we can't do this more generally: we can't be sure that all
9952 // copies of an arbitrary class definition will have the same members
9953 // defined (eg, some member functions may not be instantiated, and some
9954 // special members may or may not have been implicitly defined).
9955 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9956 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9957 continue;
9958
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009959 // FIXME: Check for =delete/=default?
9960 // FIXME: Complain about ODR violations here?
9961 const FunctionDecl *Defn = nullptr;
9962 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009963 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009964 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009965 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009966 mergeDefinitionVisibility(NonConstDefn, FD);
9967
9968 if (!FD->isLateTemplateParsed() &&
9969 !NonConstDefn->isLateTemplateParsed() &&
9970 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009971 if (!isa<CXXMethodDecl>(FD)) {
9972 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9973 } else if (FD->getLexicalParent()->isFileContext() &&
9974 NonConstDefn->getLexicalParent()->isFileContext()) {
9975 // Only diagnose out-of-line method definitions. If they are
9976 // in class definitions, then an error will be generated when
9977 // processing the class bodies.
9978 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9979 }
Richard Trieue6caa262017-12-23 00:41:01 +00009980 }
9981 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009982 continue;
9983 }
9984
Vedant Kumar48b4f762018-04-14 01:40:48 +00009985 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009986 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009987 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009988 }
9989 PendingBodies.clear();
9990
Richard Smith42413142015-05-15 20:05:43 +00009991 // Do some cleanup.
9992 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9993 getContext().deduplicateMergedDefinitonsFor(ND);
9994 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009995}
9996
9997void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009998 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009999 PendingFunctionOdrMergeFailures.empty() &&
10000 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +000010001 return;
10002
Richard Smitha0ce9c42014-07-29 23:23:27 +000010003 // Trigger the import of the full definition of each class that had any
10004 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +000010005 // These updates may in turn find and diagnose some ODR failures, so take
10006 // ownership of the set first.
10007 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
10008 PendingOdrMergeFailures.clear();
10009 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010010 Merge.first->buildLookup();
10011 Merge.first->decls_begin();
10012 Merge.first->bases_begin();
10013 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +000010014 for (auto &RecordPair : Merge.second) {
10015 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010016 RD->decls_begin();
10017 RD->bases_begin();
10018 RD->vbases_begin();
10019 }
10020 }
10021
Richard Trieue6caa262017-12-23 00:41:01 +000010022 // Trigger the import of functions.
10023 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
10024 PendingFunctionOdrMergeFailures.clear();
10025 for (auto &Merge : FunctionOdrMergeFailures) {
10026 Merge.first->buildLookup();
10027 Merge.first->decls_begin();
10028 Merge.first->getBody();
10029 for (auto &FD : Merge.second) {
10030 FD->buildLookup();
10031 FD->decls_begin();
10032 FD->getBody();
10033 }
10034 }
10035
Richard Trieuab4d7302018-07-25 22:52:05 +000010036 // Trigger the import of enums.
10037 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
10038 PendingEnumOdrMergeFailures.clear();
10039 for (auto &Merge : EnumOdrMergeFailures) {
10040 Merge.first->decls_begin();
10041 for (auto &Enum : Merge.second) {
10042 Enum->decls_begin();
10043 }
10044 }
10045
Richard Smitha0ce9c42014-07-29 23:23:27 +000010046 // For each declaration from a merged context, check that the canonical
10047 // definition of that context also contains a declaration of the same
10048 // entity.
10049 //
10050 // Caution: this loop does things that might invalidate iterators into
10051 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
10052 while (!PendingOdrMergeChecks.empty()) {
10053 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
10054
10055 // FIXME: Skip over implicit declarations for now. This matters for things
10056 // like implicitly-declared special member functions. This isn't entirely
10057 // correct; we can end up with multiple unmerged declarations of the same
10058 // implicit entity.
10059 if (D->isImplicit())
10060 continue;
10061
10062 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +000010063
10064 bool Found = false;
10065 const Decl *DCanon = D->getCanonicalDecl();
10066
Richard Smith01bdb7a2014-08-28 05:44:07 +000010067 for (auto RI : D->redecls()) {
10068 if (RI->getLexicalDeclContext() == CanonDef) {
10069 Found = true;
10070 break;
10071 }
10072 }
10073 if (Found)
10074 continue;
10075
Richard Smith0f4e2c42015-08-06 04:23:48 +000010076 // Quick check failed, time to do the slow thing. Note, we can't just
10077 // look up the name of D in CanonDef here, because the member that is
10078 // in CanonDef might not be found by name lookup (it might have been
10079 // replaced by a more recent declaration in the lookup table), and we
10080 // can't necessarily find it in the redeclaration chain because it might
10081 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010082 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +000010083 for (auto *CanonMember : CanonDef->decls()) {
10084 if (CanonMember->getCanonicalDecl() == DCanon) {
10085 // This can happen if the declaration is merely mergeable and not
10086 // actually redeclarable (we looked for redeclarations earlier).
10087 //
10088 // FIXME: We should be able to detect this more efficiently, without
10089 // pulling in all of the members of CanonDef.
10090 Found = true;
10091 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +000010092 }
Richard Smith0f4e2c42015-08-06 04:23:48 +000010093 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
10094 if (ND->getDeclName() == D->getDeclName())
10095 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010096 }
10097
10098 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +000010099 // The AST doesn't like TagDecls becoming invalid after they've been
10100 // completed. We only really need to mark FieldDecls as invalid here.
10101 if (!isa<TagDecl>(D))
10102 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010103
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010104 // Ensure we don't accidentally recursively enter deserialization while
10105 // we're producing our diagnostic.
10106 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +000010107
10108 std::string CanonDefModule =
10109 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
10110 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
10111 << D << getOwningModuleNameForDiagnostic(D)
10112 << CanonDef << CanonDefModule.empty() << CanonDefModule;
10113
10114 if (Candidates.empty())
10115 Diag(cast<Decl>(CanonDef)->getLocation(),
10116 diag::note_module_odr_violation_no_possible_decls) << D;
10117 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010118 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
10119 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +000010120 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +000010121 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +000010122 }
10123
10124 DiagnosedOdrMergeFailures.insert(CanonDef);
10125 }
10126 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010127
Richard Trieuab4d7302018-07-25 22:52:05 +000010128 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
10129 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +000010130 return;
10131
10132 // Ensure we don't accidentally recursively enter deserialization while
10133 // we're producing our diagnostics.
10134 Deserializing RecursionGuard(this);
10135
Richard Trieue6caa262017-12-23 00:41:01 +000010136 // Common code for hashing helpers.
10137 ODRHash Hash;
10138 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
10139 Hash.clear();
10140 Hash.AddQualType(Ty);
10141 return Hash.CalculateHash();
10142 };
10143
10144 auto ComputeODRHash = [&Hash](const Stmt *S) {
10145 assert(S);
10146 Hash.clear();
10147 Hash.AddStmt(S);
10148 return Hash.CalculateHash();
10149 };
10150
10151 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
10152 assert(D);
10153 Hash.clear();
10154 Hash.AddSubDecl(D);
10155 return Hash.CalculateHash();
10156 };
10157
Richard Trieu7282d322018-04-25 00:31:15 +000010158 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
10159 Hash.clear();
10160 Hash.AddTemplateArgument(TA);
10161 return Hash.CalculateHash();
10162 };
10163
Richard Trieu9359e8f2018-05-30 01:12:26 +000010164 auto ComputeTemplateParameterListODRHash =
10165 [&Hash](const TemplateParameterList *TPL) {
10166 assert(TPL);
10167 Hash.clear();
10168 Hash.AddTemplateParameterList(TPL);
10169 return Hash.CalculateHash();
10170 };
10171
Richard Smithcd45dbc2014-04-19 03:48:30 +000010172 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +000010173 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +000010174 // If we've already pointed out a specific problem with this class, don't
10175 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +000010176 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +000010177 continue;
10178
10179 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010180 CXXRecordDecl *FirstRecord = Merge.first;
10181 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010182 for (auto &RecordPair : Merge.second) {
10183 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010184 // Multiple different declarations got merged together; tell the user
10185 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +000010186 if (FirstRecord == SecondRecord)
10187 continue;
10188
10189 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +000010190
10191 auto *FirstDD = FirstRecord->DefinitionData;
10192 auto *SecondDD = RecordPair.second;
10193
10194 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
10195
10196 // Diagnostics from DefinitionData are emitted here.
10197 if (FirstDD != SecondDD) {
10198 enum ODRDefinitionDataDifference {
10199 NumBases,
10200 NumVBases,
10201 BaseType,
10202 BaseVirtual,
10203 BaseAccess,
10204 };
10205 auto ODRDiagError = [FirstRecord, &FirstModule,
10206 this](SourceLocation Loc, SourceRange Range,
10207 ODRDefinitionDataDifference DiffType) {
10208 return Diag(Loc, diag::err_module_odr_violation_definition_data)
10209 << FirstRecord << FirstModule.empty() << FirstModule << Range
10210 << DiffType;
10211 };
10212 auto ODRDiagNote = [&SecondModule,
10213 this](SourceLocation Loc, SourceRange Range,
10214 ODRDefinitionDataDifference DiffType) {
10215 return Diag(Loc, diag::note_module_odr_violation_definition_data)
10216 << SecondModule << Range << DiffType;
10217 };
10218
Richard Trieue13eabe2017-09-30 02:19:17 +000010219 unsigned FirstNumBases = FirstDD->NumBases;
10220 unsigned FirstNumVBases = FirstDD->NumVBases;
10221 unsigned SecondNumBases = SecondDD->NumBases;
10222 unsigned SecondNumVBases = SecondDD->NumVBases;
10223
10224 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
10225 unsigned NumBases = DD->NumBases;
10226 if (NumBases == 0) return SourceRange();
10227 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010228 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +000010229 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +000010230 };
10231
10232 if (FirstNumBases != SecondNumBases) {
10233 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10234 NumBases)
10235 << FirstNumBases;
10236 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10237 NumBases)
10238 << SecondNumBases;
10239 Diagnosed = true;
10240 break;
10241 }
10242
10243 if (FirstNumVBases != SecondNumVBases) {
10244 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
10245 NumVBases)
10246 << FirstNumVBases;
10247 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
10248 NumVBases)
10249 << SecondNumVBases;
10250 Diagnosed = true;
10251 break;
10252 }
10253
10254 auto FirstBases = FirstDD->bases();
10255 auto SecondBases = SecondDD->bases();
10256 unsigned i = 0;
10257 for (i = 0; i < FirstNumBases; ++i) {
10258 auto FirstBase = FirstBases[i];
10259 auto SecondBase = SecondBases[i];
10260 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
10261 ComputeQualTypeODRHash(SecondBase.getType())) {
10262 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10263 BaseType)
10264 << (i + 1) << FirstBase.getType();
10265 ODRDiagNote(SecondRecord->getLocation(),
10266 SecondBase.getSourceRange(), BaseType)
10267 << (i + 1) << SecondBase.getType();
10268 break;
10269 }
10270
10271 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
10272 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10273 BaseVirtual)
10274 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
10275 ODRDiagNote(SecondRecord->getLocation(),
10276 SecondBase.getSourceRange(), BaseVirtual)
10277 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
10278 break;
10279 }
10280
10281 if (FirstBase.getAccessSpecifierAsWritten() !=
10282 SecondBase.getAccessSpecifierAsWritten()) {
10283 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
10284 BaseAccess)
10285 << (i + 1) << FirstBase.getType()
10286 << (int)FirstBase.getAccessSpecifierAsWritten();
10287 ODRDiagNote(SecondRecord->getLocation(),
10288 SecondBase.getSourceRange(), BaseAccess)
10289 << (i + 1) << SecondBase.getType()
10290 << (int)SecondBase.getAccessSpecifierAsWritten();
10291 break;
10292 }
10293 }
10294
10295 if (i != FirstNumBases) {
10296 Diagnosed = true;
10297 break;
10298 }
10299 }
10300
Richard Trieue7f7ed22017-02-22 01:11:25 +000010301 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +000010302
10303 const ClassTemplateDecl *FirstTemplate =
10304 FirstRecord->getDescribedClassTemplate();
10305 const ClassTemplateDecl *SecondTemplate =
10306 SecondRecord->getDescribedClassTemplate();
10307
10308 assert(!FirstTemplate == !SecondTemplate &&
10309 "Both pointers should be null or non-null");
10310
10311 enum ODRTemplateDifference {
10312 ParamEmptyName,
10313 ParamName,
10314 ParamSingleDefaultArgument,
10315 ParamDifferentDefaultArgument,
10316 };
10317
10318 if (FirstTemplate && SecondTemplate) {
10319 DeclHashes FirstTemplateHashes;
10320 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +000010321
10322 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +000010323 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
10324 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +000010325 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +000010326 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +000010327 }
10328 };
10329
10330 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
10331 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
10332
10333 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
10334 "Number of template parameters should be equal.");
10335
10336 auto FirstIt = FirstTemplateHashes.begin();
10337 auto FirstEnd = FirstTemplateHashes.end();
10338 auto SecondIt = SecondTemplateHashes.begin();
10339 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
10340 if (FirstIt->second == SecondIt->second)
10341 continue;
10342
10343 auto ODRDiagError = [FirstRecord, &FirstModule,
10344 this](SourceLocation Loc, SourceRange Range,
10345 ODRTemplateDifference DiffType) {
10346 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
10347 << FirstRecord << FirstModule.empty() << FirstModule << Range
10348 << DiffType;
10349 };
10350 auto ODRDiagNote = [&SecondModule,
10351 this](SourceLocation Loc, SourceRange Range,
10352 ODRTemplateDifference DiffType) {
10353 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
10354 << SecondModule << Range << DiffType;
10355 };
10356
Vedant Kumar48b4f762018-04-14 01:40:48 +000010357 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
10358 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +000010359
10360 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
10361 "Parameter Decl's should be the same kind.");
10362
10363 DeclarationName FirstName = FirstDecl->getDeclName();
10364 DeclarationName SecondName = SecondDecl->getDeclName();
10365
10366 if (FirstName != SecondName) {
10367 const bool FirstNameEmpty =
10368 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
10369 const bool SecondNameEmpty =
10370 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
10371 assert((!FirstNameEmpty || !SecondNameEmpty) &&
10372 "Both template parameters cannot be unnamed.");
10373 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10374 FirstNameEmpty ? ParamEmptyName : ParamName)
10375 << FirstName;
10376 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10377 SecondNameEmpty ? ParamEmptyName : ParamName)
10378 << SecondName;
10379 break;
10380 }
10381
10382 switch (FirstDecl->getKind()) {
10383 default:
10384 llvm_unreachable("Invalid template parameter type.");
10385 case Decl::TemplateTypeParm: {
10386 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
10387 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
10388 const bool HasFirstDefaultArgument =
10389 FirstParam->hasDefaultArgument() &&
10390 !FirstParam->defaultArgumentWasInherited();
10391 const bool HasSecondDefaultArgument =
10392 SecondParam->hasDefaultArgument() &&
10393 !SecondParam->defaultArgumentWasInherited();
10394
10395 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10396 ODRDiagError(FirstDecl->getLocation(),
10397 FirstDecl->getSourceRange(),
10398 ParamSingleDefaultArgument)
10399 << HasFirstDefaultArgument;
10400 ODRDiagNote(SecondDecl->getLocation(),
10401 SecondDecl->getSourceRange(),
10402 ParamSingleDefaultArgument)
10403 << HasSecondDefaultArgument;
10404 break;
10405 }
10406
10407 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10408 "Expecting default arguments.");
10409
10410 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10411 ParamDifferentDefaultArgument);
10412 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10413 ParamDifferentDefaultArgument);
10414
10415 break;
10416 }
10417 case Decl::NonTypeTemplateParm: {
10418 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
10419 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
10420 const bool HasFirstDefaultArgument =
10421 FirstParam->hasDefaultArgument() &&
10422 !FirstParam->defaultArgumentWasInherited();
10423 const bool HasSecondDefaultArgument =
10424 SecondParam->hasDefaultArgument() &&
10425 !SecondParam->defaultArgumentWasInherited();
10426
10427 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10428 ODRDiagError(FirstDecl->getLocation(),
10429 FirstDecl->getSourceRange(),
10430 ParamSingleDefaultArgument)
10431 << HasFirstDefaultArgument;
10432 ODRDiagNote(SecondDecl->getLocation(),
10433 SecondDecl->getSourceRange(),
10434 ParamSingleDefaultArgument)
10435 << HasSecondDefaultArgument;
10436 break;
10437 }
10438
10439 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10440 "Expecting default arguments.");
10441
10442 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10443 ParamDifferentDefaultArgument);
10444 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10445 ParamDifferentDefaultArgument);
10446
10447 break;
10448 }
10449 case Decl::TemplateTemplateParm: {
10450 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10451 const auto *SecondParam =
10452 cast<TemplateTemplateParmDecl>(SecondDecl);
10453 const bool HasFirstDefaultArgument =
10454 FirstParam->hasDefaultArgument() &&
10455 !FirstParam->defaultArgumentWasInherited();
10456 const bool HasSecondDefaultArgument =
10457 SecondParam->hasDefaultArgument() &&
10458 !SecondParam->defaultArgumentWasInherited();
10459
10460 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10461 ODRDiagError(FirstDecl->getLocation(),
10462 FirstDecl->getSourceRange(),
10463 ParamSingleDefaultArgument)
10464 << HasFirstDefaultArgument;
10465 ODRDiagNote(SecondDecl->getLocation(),
10466 SecondDecl->getSourceRange(),
10467 ParamSingleDefaultArgument)
10468 << HasSecondDefaultArgument;
10469 break;
10470 }
10471
10472 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10473 "Expecting default arguments.");
10474
10475 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10476 ParamDifferentDefaultArgument);
10477 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10478 ParamDifferentDefaultArgument);
10479
10480 break;
10481 }
10482 }
10483
10484 break;
10485 }
10486
10487 if (FirstIt != FirstEnd) {
10488 Diagnosed = true;
10489 break;
10490 }
10491 }
10492
Richard Trieue7f7ed22017-02-22 01:11:25 +000010493 DeclHashes FirstHashes;
10494 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010495
Richard Trieue6caa262017-12-23 00:41:01 +000010496 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
10497 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010498 for (auto *D : Record->decls()) {
10499 // Due to decl merging, the first CXXRecordDecl is the parent of
10500 // Decls in both records.
10501 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
10502 continue;
Richard Trieue6caa262017-12-23 00:41:01 +000010503 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +000010504 }
10505 };
10506 PopulateHashes(FirstHashes, FirstRecord);
10507 PopulateHashes(SecondHashes, SecondRecord);
10508
10509 // Used with err_module_odr_violation_mismatch_decl and
10510 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +000010511 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +000010512 enum {
10513 EndOfClass,
10514 PublicSpecifer,
10515 PrivateSpecifer,
10516 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +000010517 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +000010518 Field,
Richard Trieu48143742017-02-28 21:24:38 +000010519 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +000010520 TypeAlias,
10521 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010522 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010523 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010524 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +000010525 Other
10526 } FirstDiffType = Other,
10527 SecondDiffType = Other;
10528
10529 auto DifferenceSelector = [](Decl *D) {
10530 assert(D && "valid Decl required");
10531 switch (D->getKind()) {
10532 default:
10533 return Other;
10534 case Decl::AccessSpec:
10535 switch (D->getAccess()) {
10536 case AS_public:
10537 return PublicSpecifer;
10538 case AS_private:
10539 return PrivateSpecifer;
10540 case AS_protected:
10541 return ProtectedSpecifer;
10542 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010543 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010544 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010545 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010546 case Decl::StaticAssert:
10547 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010548 case Decl::Field:
10549 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010550 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010551 case Decl::CXXConstructor:
10552 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010553 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010554 case Decl::TypeAlias:
10555 return TypeAlias;
10556 case Decl::Typedef:
10557 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010558 case Decl::Var:
10559 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010560 case Decl::Friend:
10561 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010562 case Decl::FunctionTemplate:
10563 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010564 }
10565 };
10566
10567 Decl *FirstDecl = nullptr;
10568 Decl *SecondDecl = nullptr;
10569 auto FirstIt = FirstHashes.begin();
10570 auto SecondIt = SecondHashes.begin();
10571
10572 // If there is a diagnoseable difference, FirstDiffType and
10573 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10574 // filled in if not EndOfClass.
10575 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010576 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10577 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010578 ++FirstIt;
10579 ++SecondIt;
10580 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010581 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010582
Richard Trieue7f7ed22017-02-22 01:11:25 +000010583 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10584 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10585
10586 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10587 SecondDiffType =
10588 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10589
10590 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010591 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010592
10593 if (FirstDiffType == Other || SecondDiffType == Other) {
10594 // Reaching this point means an unexpected Decl was encountered
10595 // or no difference was detected. This causes a generic error
10596 // message to be emitted.
10597 Diag(FirstRecord->getLocation(),
10598 diag::err_module_odr_violation_different_definitions)
10599 << FirstRecord << FirstModule.empty() << FirstModule;
10600
Richard Trieuca48d362017-06-21 01:43:13 +000010601 if (FirstDecl) {
10602 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10603 << FirstRecord << FirstDecl->getSourceRange();
10604 }
10605
Richard Trieue7f7ed22017-02-22 01:11:25 +000010606 Diag(SecondRecord->getLocation(),
10607 diag::note_module_odr_violation_different_definitions)
10608 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010609
10610 if (SecondDecl) {
10611 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10612 << SecondDecl->getSourceRange();
10613 }
10614
Richard Trieue7f7ed22017-02-22 01:11:25 +000010615 Diagnosed = true;
10616 break;
10617 }
10618
10619 if (FirstDiffType != SecondDiffType) {
10620 SourceLocation FirstLoc;
10621 SourceRange FirstRange;
10622 if (FirstDiffType == EndOfClass) {
10623 FirstLoc = FirstRecord->getBraceRange().getEnd();
10624 } else {
10625 FirstLoc = FirstIt->first->getLocation();
10626 FirstRange = FirstIt->first->getSourceRange();
10627 }
10628 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10629 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10630 << FirstDiffType;
10631
10632 SourceLocation SecondLoc;
10633 SourceRange SecondRange;
10634 if (SecondDiffType == EndOfClass) {
10635 SecondLoc = SecondRecord->getBraceRange().getEnd();
10636 } else {
10637 SecondLoc = SecondDecl->getLocation();
10638 SecondRange = SecondDecl->getSourceRange();
10639 }
10640 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10641 << SecondModule << SecondRange << SecondDiffType;
10642 Diagnosed = true;
10643 break;
10644 }
10645
Richard Trieu639d7b62017-02-22 22:22:42 +000010646 assert(FirstDiffType == SecondDiffType);
10647
10648 // Used with err_module_odr_violation_mismatch_decl_diff and
10649 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010650 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010651 StaticAssertCondition,
10652 StaticAssertMessage,
10653 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010654 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010655 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010656 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010657 FieldDifferentWidthBitField,
10658 FieldSingleMutable,
10659 FieldSingleInitializer,
10660 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010661 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010662 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010663 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010664 MethodVirtual,
10665 MethodStatic,
10666 MethodVolatile,
10667 MethodConst,
10668 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010669 MethodNumberParameters,
10670 MethodParameterType,
10671 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010672 MethodParameterSingleDefaultArgument,
10673 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010674 MethodNoTemplateArguments,
10675 MethodDifferentNumberTemplateArguments,
10676 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010677 MethodSingleBody,
10678 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010679 TypedefName,
10680 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010681 VarName,
10682 VarType,
10683 VarSingleInitializer,
10684 VarDifferentInitializer,
10685 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010686 FriendTypeFunction,
10687 FriendType,
10688 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010689 FunctionTemplateDifferentNumberParameters,
10690 FunctionTemplateParameterDifferentKind,
10691 FunctionTemplateParameterName,
10692 FunctionTemplateParameterSingleDefaultArgument,
10693 FunctionTemplateParameterDifferentDefaultArgument,
10694 FunctionTemplateParameterDifferentType,
10695 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010696 };
10697
10698 // These lambdas have the common portions of the ODR diagnostics. This
10699 // has the same return as Diag(), so addition parameters can be passed
10700 // in with operator<<
10701 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10702 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10703 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10704 << FirstRecord << FirstModule.empty() << FirstModule << Range
10705 << DiffType;
10706 };
10707 auto ODRDiagNote = [&SecondModule, this](
10708 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10709 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10710 << SecondModule << Range << DiffType;
10711 };
10712
Richard Trieu639d7b62017-02-22 22:22:42 +000010713 switch (FirstDiffType) {
10714 case Other:
10715 case EndOfClass:
10716 case PublicSpecifer:
10717 case PrivateSpecifer:
10718 case ProtectedSpecifer:
10719 llvm_unreachable("Invalid diff type");
10720
10721 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010722 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10723 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010724
10725 Expr *FirstExpr = FirstSA->getAssertExpr();
10726 Expr *SecondExpr = SecondSA->getAssertExpr();
10727 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10728 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10729 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010730 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010731 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010732 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10733 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010734 Diagnosed = true;
10735 break;
10736 }
10737
10738 StringLiteral *FirstStr = FirstSA->getMessage();
10739 StringLiteral *SecondStr = SecondSA->getMessage();
10740 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10741 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10742 SourceLocation FirstLoc, SecondLoc;
10743 SourceRange FirstRange, SecondRange;
10744 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010745 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010746 FirstRange = FirstStr->getSourceRange();
10747 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010748 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010749 FirstRange = FirstSA->getSourceRange();
10750 }
10751 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010752 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010753 SecondRange = SecondStr->getSourceRange();
10754 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010755 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010756 SecondRange = SecondSA->getSourceRange();
10757 }
10758 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10759 << (FirstStr == nullptr);
10760 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10761 << (SecondStr == nullptr);
10762 Diagnosed = true;
10763 break;
10764 }
10765
10766 if (FirstStr && SecondStr &&
10767 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010768 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010769 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010770 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010771 StaticAssertMessage);
10772 Diagnosed = true;
10773 break;
10774 }
10775 break;
10776 }
Richard Trieud0786092017-02-23 00:23:01 +000010777 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010778 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10779 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010780 IdentifierInfo *FirstII = FirstField->getIdentifier();
10781 IdentifierInfo *SecondII = SecondField->getIdentifier();
10782 if (FirstII->getName() != SecondII->getName()) {
10783 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10784 FieldName)
10785 << FirstII;
10786 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10787 FieldName)
10788 << SecondII;
10789
10790 Diagnosed = true;
10791 break;
10792 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010793
Richard Smithdbafb6c2017-06-29 23:23:46 +000010794 assert(getContext().hasSameType(FirstField->getType(),
10795 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010796
10797 QualType FirstType = FirstField->getType();
10798 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010799 if (ComputeQualTypeODRHash(FirstType) !=
10800 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010801 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10802 FieldTypeName)
10803 << FirstII << FirstType;
10804 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10805 FieldTypeName)
10806 << SecondII << SecondType;
10807
10808 Diagnosed = true;
10809 break;
10810 }
10811
Richard Trieu93772fc2017-02-24 20:59:28 +000010812 const bool IsFirstBitField = FirstField->isBitField();
10813 const bool IsSecondBitField = SecondField->isBitField();
10814 if (IsFirstBitField != IsSecondBitField) {
10815 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10816 FieldSingleBitField)
10817 << FirstII << IsFirstBitField;
10818 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10819 FieldSingleBitField)
10820 << SecondII << IsSecondBitField;
10821 Diagnosed = true;
10822 break;
10823 }
10824
10825 if (IsFirstBitField && IsSecondBitField) {
10826 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10827 FieldDifferentWidthBitField)
10828 << FirstII << FirstField->getBitWidth()->getSourceRange();
10829 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10830 FieldDifferentWidthBitField)
10831 << SecondII << SecondField->getBitWidth()->getSourceRange();
10832 Diagnosed = true;
10833 break;
10834 }
10835
Richard Trieu8d543e22017-02-24 23:35:37 +000010836 const bool IsFirstMutable = FirstField->isMutable();
10837 const bool IsSecondMutable = SecondField->isMutable();
10838 if (IsFirstMutable != IsSecondMutable) {
10839 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10840 FieldSingleMutable)
10841 << FirstII << IsFirstMutable;
10842 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10843 FieldSingleMutable)
10844 << SecondII << IsSecondMutable;
10845 Diagnosed = true;
10846 break;
10847 }
10848
10849 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10850 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10851 if ((!FirstInitializer && SecondInitializer) ||
10852 (FirstInitializer && !SecondInitializer)) {
10853 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10854 FieldSingleInitializer)
10855 << FirstII << (FirstInitializer != nullptr);
10856 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10857 FieldSingleInitializer)
10858 << SecondII << (SecondInitializer != nullptr);
10859 Diagnosed = true;
10860 break;
10861 }
10862
10863 if (FirstInitializer && SecondInitializer) {
10864 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10865 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10866 if (FirstInitHash != SecondInitHash) {
10867 ODRDiagError(FirstField->getLocation(),
10868 FirstField->getSourceRange(),
10869 FieldDifferentInitializers)
10870 << FirstII << FirstInitializer->getSourceRange();
10871 ODRDiagNote(SecondField->getLocation(),
10872 SecondField->getSourceRange(),
10873 FieldDifferentInitializers)
10874 << SecondII << SecondInitializer->getSourceRange();
10875 Diagnosed = true;
10876 break;
10877 }
10878 }
10879
Richard Trieud0786092017-02-23 00:23:01 +000010880 break;
10881 }
Richard Trieu48143742017-02-28 21:24:38 +000010882 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010883 enum {
10884 DiagMethod,
10885 DiagConstructor,
10886 DiagDestructor,
10887 } FirstMethodType,
10888 SecondMethodType;
10889 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10890 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10891 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10892 return DiagMethod;
10893 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010894 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10895 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010896 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10897 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010898 auto FirstName = FirstMethod->getDeclName();
10899 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010900 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010901 ODRDiagError(FirstMethod->getLocation(),
10902 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010903 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010904 ODRDiagNote(SecondMethod->getLocation(),
10905 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010906 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010907
10908 Diagnosed = true;
10909 break;
10910 }
10911
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010912 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10913 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010914 if (FirstDeleted != SecondDeleted) {
10915 ODRDiagError(FirstMethod->getLocation(),
10916 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010917 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010918
10919 ODRDiagNote(SecondMethod->getLocation(),
10920 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010921 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010922 Diagnosed = true;
10923 break;
10924 }
10925
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010926 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10927 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10928 if (FirstDefaulted != SecondDefaulted) {
10929 ODRDiagError(FirstMethod->getLocation(),
10930 FirstMethod->getSourceRange(), MethodDefaulted)
10931 << FirstMethodType << FirstName << FirstDefaulted;
10932
10933 ODRDiagNote(SecondMethod->getLocation(),
10934 SecondMethod->getSourceRange(), MethodDefaulted)
10935 << SecondMethodType << SecondName << SecondDefaulted;
10936 Diagnosed = true;
10937 break;
10938 }
10939
Richard Trieu583e2c12017-03-04 00:08:58 +000010940 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10941 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10942 const bool FirstPure = FirstMethod->isPure();
10943 const bool SecondPure = SecondMethod->isPure();
10944 if ((FirstVirtual || SecondVirtual) &&
10945 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10946 ODRDiagError(FirstMethod->getLocation(),
10947 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010948 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010949 ODRDiagNote(SecondMethod->getLocation(),
10950 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010951 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010952 Diagnosed = true;
10953 break;
10954 }
10955
10956 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10957 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10958 // class needs to be checked instead.
10959 const auto FirstStorage = FirstMethod->getStorageClass();
10960 const auto SecondStorage = SecondMethod->getStorageClass();
10961 const bool FirstStatic = FirstStorage == SC_Static;
10962 const bool SecondStatic = SecondStorage == SC_Static;
10963 if (FirstStatic != SecondStatic) {
10964 ODRDiagError(FirstMethod->getLocation(),
10965 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010966 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010967 ODRDiagNote(SecondMethod->getLocation(),
10968 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010969 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010970 Diagnosed = true;
10971 break;
10972 }
10973
10974 const bool FirstVolatile = FirstMethod->isVolatile();
10975 const bool SecondVolatile = SecondMethod->isVolatile();
10976 if (FirstVolatile != SecondVolatile) {
10977 ODRDiagError(FirstMethod->getLocation(),
10978 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010979 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010980 ODRDiagNote(SecondMethod->getLocation(),
10981 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010982 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010983 Diagnosed = true;
10984 break;
10985 }
10986
10987 const bool FirstConst = FirstMethod->isConst();
10988 const bool SecondConst = SecondMethod->isConst();
10989 if (FirstConst != SecondConst) {
10990 ODRDiagError(FirstMethod->getLocation(),
10991 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010992 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010993 ODRDiagNote(SecondMethod->getLocation(),
10994 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010995 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010996 Diagnosed = true;
10997 break;
10998 }
10999
11000 const bool FirstInline = FirstMethod->isInlineSpecified();
11001 const bool SecondInline = SecondMethod->isInlineSpecified();
11002 if (FirstInline != SecondInline) {
11003 ODRDiagError(FirstMethod->getLocation(),
11004 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011005 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011006 ODRDiagNote(SecondMethod->getLocation(),
11007 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000011008 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000011009 Diagnosed = true;
11010 break;
11011 }
11012
Richard Trieu02552272017-05-02 23:58:52 +000011013 const unsigned FirstNumParameters = FirstMethod->param_size();
11014 const unsigned SecondNumParameters = SecondMethod->param_size();
11015 if (FirstNumParameters != SecondNumParameters) {
11016 ODRDiagError(FirstMethod->getLocation(),
11017 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011018 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011019 ODRDiagNote(SecondMethod->getLocation(),
11020 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000011021 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000011022 Diagnosed = true;
11023 break;
11024 }
11025
11026 // Need this status boolean to know when break out of the switch.
11027 bool ParameterMismatch = false;
11028 for (unsigned I = 0; I < FirstNumParameters; ++I) {
11029 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
11030 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
11031
11032 QualType FirstParamType = FirstParam->getType();
11033 QualType SecondParamType = SecondParam->getType();
11034 if (FirstParamType != SecondParamType &&
11035 ComputeQualTypeODRHash(FirstParamType) !=
11036 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011037 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011038 FirstParamType->getAs<DecayedType>()) {
11039 ODRDiagError(FirstMethod->getLocation(),
11040 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011041 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11042 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000011043 } else {
11044 ODRDiagError(FirstMethod->getLocation(),
11045 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011046 << FirstMethodType << FirstName << (I + 1) << FirstParamType
11047 << false;
Richard Trieu02552272017-05-02 23:58:52 +000011048 }
11049
Vedant Kumar48b4f762018-04-14 01:40:48 +000011050 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000011051 SecondParamType->getAs<DecayedType>()) {
11052 ODRDiagNote(SecondMethod->getLocation(),
11053 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011054 << SecondMethodType << SecondName << (I + 1)
11055 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000011056 << ParamDecayedType->getOriginalType();
11057 } else {
11058 ODRDiagNote(SecondMethod->getLocation(),
11059 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000011060 << SecondMethodType << SecondName << (I + 1)
11061 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000011062 }
11063 ParameterMismatch = true;
11064 break;
11065 }
11066
11067 DeclarationName FirstParamName = FirstParam->getDeclName();
11068 DeclarationName SecondParamName = SecondParam->getDeclName();
11069 if (FirstParamName != SecondParamName) {
11070 ODRDiagError(FirstMethod->getLocation(),
11071 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011072 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011073 ODRDiagNote(SecondMethod->getLocation(),
11074 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000011075 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000011076 ParameterMismatch = true;
11077 break;
11078 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011079
11080 const Expr *FirstInit = FirstParam->getInit();
11081 const Expr *SecondInit = SecondParam->getInit();
11082 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11083 ODRDiagError(FirstMethod->getLocation(),
11084 FirstMethod->getSourceRange(),
11085 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011086 << FirstMethodType << FirstName << (I + 1)
11087 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011088 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11089 ODRDiagNote(SecondMethod->getLocation(),
11090 SecondMethod->getSourceRange(),
11091 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011092 << SecondMethodType << SecondName << (I + 1)
11093 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000011094 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11095 ParameterMismatch = true;
11096 break;
11097 }
11098
11099 if (FirstInit && SecondInit &&
11100 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11101 ODRDiagError(FirstMethod->getLocation(),
11102 FirstMethod->getSourceRange(),
11103 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011104 << FirstMethodType << FirstName << (I + 1)
11105 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011106 ODRDiagNote(SecondMethod->getLocation(),
11107 SecondMethod->getSourceRange(),
11108 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000011109 << SecondMethodType << SecondName << (I + 1)
11110 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000011111 ParameterMismatch = true;
11112 break;
11113
11114 }
Richard Trieu02552272017-05-02 23:58:52 +000011115 }
11116
11117 if (ParameterMismatch) {
11118 Diagnosed = true;
11119 break;
11120 }
11121
Richard Trieu7282d322018-04-25 00:31:15 +000011122 const auto *FirstTemplateArgs =
11123 FirstMethod->getTemplateSpecializationArgs();
11124 const auto *SecondTemplateArgs =
11125 SecondMethod->getTemplateSpecializationArgs();
11126
11127 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
11128 (!FirstTemplateArgs && SecondTemplateArgs)) {
11129 ODRDiagError(FirstMethod->getLocation(),
11130 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
11131 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
11132 ODRDiagNote(SecondMethod->getLocation(),
11133 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
11134 << SecondMethodType << SecondName
11135 << (SecondTemplateArgs != nullptr);
11136
11137 Diagnosed = true;
11138 break;
11139 }
11140
11141 if (FirstTemplateArgs && SecondTemplateArgs) {
11142 // Remove pack expansions from argument list.
11143 auto ExpandTemplateArgumentList =
11144 [](const TemplateArgumentList *TAL) {
11145 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
11146 for (const TemplateArgument &TA : TAL->asArray()) {
11147 if (TA.getKind() != TemplateArgument::Pack) {
11148 ExpandedList.push_back(&TA);
11149 continue;
11150 }
11151 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
11152 ExpandedList.push_back(&PackTA);
11153 }
11154 }
11155 return ExpandedList;
11156 };
11157 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
11158 ExpandTemplateArgumentList(FirstTemplateArgs);
11159 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
11160 ExpandTemplateArgumentList(SecondTemplateArgs);
11161
11162 if (FirstExpandedList.size() != SecondExpandedList.size()) {
11163 ODRDiagError(FirstMethod->getLocation(),
11164 FirstMethod->getSourceRange(),
11165 MethodDifferentNumberTemplateArguments)
11166 << FirstMethodType << FirstName
11167 << (unsigned)FirstExpandedList.size();
11168 ODRDiagNote(SecondMethod->getLocation(),
11169 SecondMethod->getSourceRange(),
11170 MethodDifferentNumberTemplateArguments)
11171 << SecondMethodType << SecondName
11172 << (unsigned)SecondExpandedList.size();
11173
11174 Diagnosed = true;
11175 break;
11176 }
11177
11178 bool TemplateArgumentMismatch = false;
11179 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
11180 const TemplateArgument &FirstTA = *FirstExpandedList[i],
11181 &SecondTA = *SecondExpandedList[i];
11182 if (ComputeTemplateArgumentODRHash(FirstTA) ==
11183 ComputeTemplateArgumentODRHash(SecondTA)) {
11184 continue;
11185 }
11186
11187 ODRDiagError(FirstMethod->getLocation(),
11188 FirstMethod->getSourceRange(),
11189 MethodDifferentTemplateArgument)
11190 << FirstMethodType << FirstName << FirstTA << i + 1;
11191 ODRDiagNote(SecondMethod->getLocation(),
11192 SecondMethod->getSourceRange(),
11193 MethodDifferentTemplateArgument)
11194 << SecondMethodType << SecondName << SecondTA << i + 1;
11195
11196 TemplateArgumentMismatch = true;
11197 break;
11198 }
11199
11200 if (TemplateArgumentMismatch) {
11201 Diagnosed = true;
11202 break;
11203 }
11204 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000011205
11206 // Compute the hash of the method as if it has no body.
11207 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
11208 Hash.clear();
11209 Hash.AddFunctionDecl(D, true /*SkipBody*/);
11210 return Hash.CalculateHash();
11211 };
11212
11213 // Compare the hash generated to the hash stored. A difference means
11214 // that a body was present in the original source. Due to merging,
11215 // the stardard way of detecting a body will not work.
11216 const bool HasFirstBody =
11217 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
11218 const bool HasSecondBody =
11219 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
11220
11221 if (HasFirstBody != HasSecondBody) {
11222 ODRDiagError(FirstMethod->getLocation(),
11223 FirstMethod->getSourceRange(), MethodSingleBody)
11224 << FirstMethodType << FirstName << HasFirstBody;
11225 ODRDiagNote(SecondMethod->getLocation(),
11226 SecondMethod->getSourceRange(), MethodSingleBody)
11227 << SecondMethodType << SecondName << HasSecondBody;
11228 Diagnosed = true;
11229 break;
11230 }
11231
11232 if (HasFirstBody && HasSecondBody) {
11233 ODRDiagError(FirstMethod->getLocation(),
11234 FirstMethod->getSourceRange(), MethodDifferentBody)
11235 << FirstMethodType << FirstName;
11236 ODRDiagNote(SecondMethod->getLocation(),
11237 SecondMethod->getSourceRange(), MethodDifferentBody)
11238 << SecondMethodType << SecondName;
11239 Diagnosed = true;
11240 break;
11241 }
11242
Richard Trieu48143742017-02-28 21:24:38 +000011243 break;
11244 }
Richard Trieu11d566a2017-06-12 21:58:22 +000011245 case TypeAlias:
11246 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011247 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
11248 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000011249 auto FirstName = FirstTD->getDeclName();
11250 auto SecondName = SecondTD->getDeclName();
11251 if (FirstName != SecondName) {
11252 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11253 TypedefName)
11254 << (FirstDiffType == TypeAlias) << FirstName;
11255 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11256 TypedefName)
11257 << (FirstDiffType == TypeAlias) << SecondName;
11258 Diagnosed = true;
11259 break;
11260 }
11261
11262 QualType FirstType = FirstTD->getUnderlyingType();
11263 QualType SecondType = SecondTD->getUnderlyingType();
11264 if (ComputeQualTypeODRHash(FirstType) !=
11265 ComputeQualTypeODRHash(SecondType)) {
11266 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
11267 TypedefType)
11268 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
11269 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
11270 TypedefType)
11271 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
11272 Diagnosed = true;
11273 break;
11274 }
11275 break;
11276 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000011277 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011278 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
11279 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000011280 auto FirstName = FirstVD->getDeclName();
11281 auto SecondName = SecondVD->getDeclName();
11282 if (FirstName != SecondName) {
11283 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11284 VarName)
11285 << FirstName;
11286 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11287 VarName)
11288 << SecondName;
11289 Diagnosed = true;
11290 break;
11291 }
11292
11293 QualType FirstType = FirstVD->getType();
11294 QualType SecondType = SecondVD->getType();
11295 if (ComputeQualTypeODRHash(FirstType) !=
11296 ComputeQualTypeODRHash(SecondType)) {
11297 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11298 VarType)
11299 << FirstName << FirstType;
11300 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11301 VarType)
11302 << SecondName << SecondType;
11303 Diagnosed = true;
11304 break;
11305 }
11306
11307 const Expr *FirstInit = FirstVD->getInit();
11308 const Expr *SecondInit = SecondVD->getInit();
11309 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11310 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11311 VarSingleInitializer)
11312 << FirstName << (FirstInit == nullptr)
11313 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
11314 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11315 VarSingleInitializer)
11316 << SecondName << (SecondInit == nullptr)
11317 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11318 Diagnosed = true;
11319 break;
11320 }
11321
11322 if (FirstInit && SecondInit &&
11323 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11324 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11325 VarDifferentInitializer)
11326 << FirstName << FirstInit->getSourceRange();
11327 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11328 VarDifferentInitializer)
11329 << SecondName << SecondInit->getSourceRange();
11330 Diagnosed = true;
11331 break;
11332 }
11333
11334 const bool FirstIsConstexpr = FirstVD->isConstexpr();
11335 const bool SecondIsConstexpr = SecondVD->isConstexpr();
11336 if (FirstIsConstexpr != SecondIsConstexpr) {
11337 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
11338 VarConstexpr)
11339 << FirstName << FirstIsConstexpr;
11340 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
11341 VarConstexpr)
11342 << SecondName << SecondIsConstexpr;
11343 Diagnosed = true;
11344 break;
11345 }
11346 break;
11347 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000011348 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011349 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
11350 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000011351
11352 NamedDecl *FirstND = FirstFriend->getFriendDecl();
11353 NamedDecl *SecondND = SecondFriend->getFriendDecl();
11354
11355 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
11356 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
11357
11358 if (FirstND && SecondND) {
11359 ODRDiagError(FirstFriend->getFriendLoc(),
11360 FirstFriend->getSourceRange(), FriendFunction)
11361 << FirstND;
11362 ODRDiagNote(SecondFriend->getFriendLoc(),
11363 SecondFriend->getSourceRange(), FriendFunction)
11364 << SecondND;
11365
11366 Diagnosed = true;
11367 break;
11368 }
11369
11370 if (FirstTSI && SecondTSI) {
11371 QualType FirstFriendType = FirstTSI->getType();
11372 QualType SecondFriendType = SecondTSI->getType();
11373 assert(ComputeQualTypeODRHash(FirstFriendType) !=
11374 ComputeQualTypeODRHash(SecondFriendType));
11375 ODRDiagError(FirstFriend->getFriendLoc(),
11376 FirstFriend->getSourceRange(), FriendType)
11377 << FirstFriendType;
11378 ODRDiagNote(SecondFriend->getFriendLoc(),
11379 SecondFriend->getSourceRange(), FriendType)
11380 << SecondFriendType;
11381 Diagnosed = true;
11382 break;
11383 }
11384
11385 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
11386 FriendTypeFunction)
11387 << (FirstTSI == nullptr);
11388 ODRDiagNote(SecondFriend->getFriendLoc(),
11389 SecondFriend->getSourceRange(), FriendTypeFunction)
11390 << (SecondTSI == nullptr);
11391
11392 Diagnosed = true;
11393 break;
11394 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000011395 case FunctionTemplate: {
11396 FunctionTemplateDecl *FirstTemplate =
11397 cast<FunctionTemplateDecl>(FirstDecl);
11398 FunctionTemplateDecl *SecondTemplate =
11399 cast<FunctionTemplateDecl>(SecondDecl);
11400
11401 TemplateParameterList *FirstTPL =
11402 FirstTemplate->getTemplateParameters();
11403 TemplateParameterList *SecondTPL =
11404 SecondTemplate->getTemplateParameters();
11405
11406 if (FirstTPL->size() != SecondTPL->size()) {
11407 ODRDiagError(FirstTemplate->getLocation(),
11408 FirstTemplate->getSourceRange(),
11409 FunctionTemplateDifferentNumberParameters)
11410 << FirstTemplate << FirstTPL->size();
11411 ODRDiagNote(SecondTemplate->getLocation(),
11412 SecondTemplate->getSourceRange(),
11413 FunctionTemplateDifferentNumberParameters)
11414 << SecondTemplate << SecondTPL->size();
11415
11416 Diagnosed = true;
11417 break;
11418 }
11419
11420 bool ParameterMismatch = false;
11421 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
11422 NamedDecl *FirstParam = FirstTPL->getParam(i);
11423 NamedDecl *SecondParam = SecondTPL->getParam(i);
11424
11425 if (FirstParam->getKind() != SecondParam->getKind()) {
11426 enum {
11427 TemplateTypeParameter,
11428 NonTypeTemplateParameter,
11429 TemplateTemplateParameter,
11430 };
11431 auto GetParamType = [](NamedDecl *D) {
11432 switch (D->getKind()) {
11433 default:
11434 llvm_unreachable("Unexpected template parameter type");
11435 case Decl::TemplateTypeParm:
11436 return TemplateTypeParameter;
11437 case Decl::NonTypeTemplateParm:
11438 return NonTypeTemplateParameter;
11439 case Decl::TemplateTemplateParm:
11440 return TemplateTemplateParameter;
11441 }
11442 };
11443
11444 ODRDiagError(FirstTemplate->getLocation(),
11445 FirstTemplate->getSourceRange(),
11446 FunctionTemplateParameterDifferentKind)
11447 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
11448 ODRDiagNote(SecondTemplate->getLocation(),
11449 SecondTemplate->getSourceRange(),
11450 FunctionTemplateParameterDifferentKind)
11451 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
11452
11453 ParameterMismatch = true;
11454 break;
11455 }
11456
11457 if (FirstParam->getName() != SecondParam->getName()) {
11458 ODRDiagError(FirstTemplate->getLocation(),
11459 FirstTemplate->getSourceRange(),
11460 FunctionTemplateParameterName)
11461 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
11462 << FirstParam;
11463 ODRDiagNote(SecondTemplate->getLocation(),
11464 SecondTemplate->getSourceRange(),
11465 FunctionTemplateParameterName)
11466 << SecondTemplate << (i + 1)
11467 << (bool)SecondParam->getIdentifier() << SecondParam;
11468 ParameterMismatch = true;
11469 break;
11470 }
11471
11472 if (isa<TemplateTypeParmDecl>(FirstParam) &&
11473 isa<TemplateTypeParmDecl>(SecondParam)) {
11474 TemplateTypeParmDecl *FirstTTPD =
11475 cast<TemplateTypeParmDecl>(FirstParam);
11476 TemplateTypeParmDecl *SecondTTPD =
11477 cast<TemplateTypeParmDecl>(SecondParam);
11478 bool HasFirstDefaultArgument =
11479 FirstTTPD->hasDefaultArgument() &&
11480 !FirstTTPD->defaultArgumentWasInherited();
11481 bool HasSecondDefaultArgument =
11482 SecondTTPD->hasDefaultArgument() &&
11483 !SecondTTPD->defaultArgumentWasInherited();
11484 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11485 ODRDiagError(FirstTemplate->getLocation(),
11486 FirstTemplate->getSourceRange(),
11487 FunctionTemplateParameterSingleDefaultArgument)
11488 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11489 ODRDiagNote(SecondTemplate->getLocation(),
11490 SecondTemplate->getSourceRange(),
11491 FunctionTemplateParameterSingleDefaultArgument)
11492 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11493 ParameterMismatch = true;
11494 break;
11495 }
11496
11497 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11498 QualType FirstType = FirstTTPD->getDefaultArgument();
11499 QualType SecondType = SecondTTPD->getDefaultArgument();
11500 if (ComputeQualTypeODRHash(FirstType) !=
11501 ComputeQualTypeODRHash(SecondType)) {
11502 ODRDiagError(FirstTemplate->getLocation(),
11503 FirstTemplate->getSourceRange(),
11504 FunctionTemplateParameterDifferentDefaultArgument)
11505 << FirstTemplate << (i + 1) << FirstType;
11506 ODRDiagNote(SecondTemplate->getLocation(),
11507 SecondTemplate->getSourceRange(),
11508 FunctionTemplateParameterDifferentDefaultArgument)
11509 << SecondTemplate << (i + 1) << SecondType;
11510 ParameterMismatch = true;
11511 break;
11512 }
11513 }
11514
11515 if (FirstTTPD->isParameterPack() !=
11516 SecondTTPD->isParameterPack()) {
11517 ODRDiagError(FirstTemplate->getLocation(),
11518 FirstTemplate->getSourceRange(),
11519 FunctionTemplatePackParameter)
11520 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11521 ODRDiagNote(SecondTemplate->getLocation(),
11522 SecondTemplate->getSourceRange(),
11523 FunctionTemplatePackParameter)
11524 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11525 ParameterMismatch = true;
11526 break;
11527 }
11528 }
11529
11530 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11531 isa<TemplateTemplateParmDecl>(SecondParam)) {
11532 TemplateTemplateParmDecl *FirstTTPD =
11533 cast<TemplateTemplateParmDecl>(FirstParam);
11534 TemplateTemplateParmDecl *SecondTTPD =
11535 cast<TemplateTemplateParmDecl>(SecondParam);
11536
11537 TemplateParameterList *FirstTPL =
11538 FirstTTPD->getTemplateParameters();
11539 TemplateParameterList *SecondTPL =
11540 SecondTTPD->getTemplateParameters();
11541
11542 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11543 ComputeTemplateParameterListODRHash(SecondTPL)) {
11544 ODRDiagError(FirstTemplate->getLocation(),
11545 FirstTemplate->getSourceRange(),
11546 FunctionTemplateParameterDifferentType)
11547 << FirstTemplate << (i + 1);
11548 ODRDiagNote(SecondTemplate->getLocation(),
11549 SecondTemplate->getSourceRange(),
11550 FunctionTemplateParameterDifferentType)
11551 << SecondTemplate << (i + 1);
11552 ParameterMismatch = true;
11553 break;
11554 }
11555
11556 bool HasFirstDefaultArgument =
11557 FirstTTPD->hasDefaultArgument() &&
11558 !FirstTTPD->defaultArgumentWasInherited();
11559 bool HasSecondDefaultArgument =
11560 SecondTTPD->hasDefaultArgument() &&
11561 !SecondTTPD->defaultArgumentWasInherited();
11562 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11563 ODRDiagError(FirstTemplate->getLocation(),
11564 FirstTemplate->getSourceRange(),
11565 FunctionTemplateParameterSingleDefaultArgument)
11566 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11567 ODRDiagNote(SecondTemplate->getLocation(),
11568 SecondTemplate->getSourceRange(),
11569 FunctionTemplateParameterSingleDefaultArgument)
11570 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11571 ParameterMismatch = true;
11572 break;
11573 }
11574
11575 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11576 TemplateArgument FirstTA =
11577 FirstTTPD->getDefaultArgument().getArgument();
11578 TemplateArgument SecondTA =
11579 SecondTTPD->getDefaultArgument().getArgument();
11580 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11581 ComputeTemplateArgumentODRHash(SecondTA)) {
11582 ODRDiagError(FirstTemplate->getLocation(),
11583 FirstTemplate->getSourceRange(),
11584 FunctionTemplateParameterDifferentDefaultArgument)
11585 << FirstTemplate << (i + 1) << FirstTA;
11586 ODRDiagNote(SecondTemplate->getLocation(),
11587 SecondTemplate->getSourceRange(),
11588 FunctionTemplateParameterDifferentDefaultArgument)
11589 << SecondTemplate << (i + 1) << SecondTA;
11590 ParameterMismatch = true;
11591 break;
11592 }
11593 }
11594
11595 if (FirstTTPD->isParameterPack() !=
11596 SecondTTPD->isParameterPack()) {
11597 ODRDiagError(FirstTemplate->getLocation(),
11598 FirstTemplate->getSourceRange(),
11599 FunctionTemplatePackParameter)
11600 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11601 ODRDiagNote(SecondTemplate->getLocation(),
11602 SecondTemplate->getSourceRange(),
11603 FunctionTemplatePackParameter)
11604 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11605 ParameterMismatch = true;
11606 break;
11607 }
11608 }
11609
11610 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11611 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11612 NonTypeTemplateParmDecl *FirstNTTPD =
11613 cast<NonTypeTemplateParmDecl>(FirstParam);
11614 NonTypeTemplateParmDecl *SecondNTTPD =
11615 cast<NonTypeTemplateParmDecl>(SecondParam);
11616
11617 QualType FirstType = FirstNTTPD->getType();
11618 QualType SecondType = SecondNTTPD->getType();
11619 if (ComputeQualTypeODRHash(FirstType) !=
11620 ComputeQualTypeODRHash(SecondType)) {
11621 ODRDiagError(FirstTemplate->getLocation(),
11622 FirstTemplate->getSourceRange(),
11623 FunctionTemplateParameterDifferentType)
11624 << FirstTemplate << (i + 1);
11625 ODRDiagNote(SecondTemplate->getLocation(),
11626 SecondTemplate->getSourceRange(),
11627 FunctionTemplateParameterDifferentType)
11628 << SecondTemplate << (i + 1);
11629 ParameterMismatch = true;
11630 break;
11631 }
11632
11633 bool HasFirstDefaultArgument =
11634 FirstNTTPD->hasDefaultArgument() &&
11635 !FirstNTTPD->defaultArgumentWasInherited();
11636 bool HasSecondDefaultArgument =
11637 SecondNTTPD->hasDefaultArgument() &&
11638 !SecondNTTPD->defaultArgumentWasInherited();
11639 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11640 ODRDiagError(FirstTemplate->getLocation(),
11641 FirstTemplate->getSourceRange(),
11642 FunctionTemplateParameterSingleDefaultArgument)
11643 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11644 ODRDiagNote(SecondTemplate->getLocation(),
11645 SecondTemplate->getSourceRange(),
11646 FunctionTemplateParameterSingleDefaultArgument)
11647 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11648 ParameterMismatch = true;
11649 break;
11650 }
11651
11652 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11653 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11654 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11655 if (ComputeODRHash(FirstDefaultArgument) !=
11656 ComputeODRHash(SecondDefaultArgument)) {
11657 ODRDiagError(FirstTemplate->getLocation(),
11658 FirstTemplate->getSourceRange(),
11659 FunctionTemplateParameterDifferentDefaultArgument)
11660 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11661 ODRDiagNote(SecondTemplate->getLocation(),
11662 SecondTemplate->getSourceRange(),
11663 FunctionTemplateParameterDifferentDefaultArgument)
11664 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11665 ParameterMismatch = true;
11666 break;
11667 }
11668 }
11669
11670 if (FirstNTTPD->isParameterPack() !=
11671 SecondNTTPD->isParameterPack()) {
11672 ODRDiagError(FirstTemplate->getLocation(),
11673 FirstTemplate->getSourceRange(),
11674 FunctionTemplatePackParameter)
11675 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11676 ODRDiagNote(SecondTemplate->getLocation(),
11677 SecondTemplate->getSourceRange(),
11678 FunctionTemplatePackParameter)
11679 << SecondTemplate << (i + 1)
11680 << SecondNTTPD->isParameterPack();
11681 ParameterMismatch = true;
11682 break;
11683 }
11684 }
11685 }
11686
11687 if (ParameterMismatch) {
11688 Diagnosed = true;
11689 break;
11690 }
11691
11692 break;
11693 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011694 }
11695
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011696 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011697 continue;
11698
Richard Trieu708859a2017-06-08 00:56:21 +000011699 Diag(FirstDecl->getLocation(),
11700 diag::err_module_odr_violation_mismatch_decl_unknown)
11701 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11702 << FirstDecl->getSourceRange();
11703 Diag(SecondDecl->getLocation(),
11704 diag::note_module_odr_violation_mismatch_decl_unknown)
11705 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011706 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011707 }
11708
11709 if (!Diagnosed) {
11710 // All definitions are updates to the same declaration. This happens if a
11711 // module instantiates the declaration of a class template specialization
11712 // and two or more other modules instantiate its definition.
11713 //
11714 // FIXME: Indicate which modules had instantiations of this definition.
11715 // FIXME: How can this even happen?
11716 Diag(Merge.first->getLocation(),
11717 diag::err_module_odr_violation_different_instantiations)
11718 << Merge.first;
11719 }
11720 }
Richard Trieue6caa262017-12-23 00:41:01 +000011721
11722 // Issue ODR failures diagnostics for functions.
11723 for (auto &Merge : FunctionOdrMergeFailures) {
11724 enum ODRFunctionDifference {
11725 ReturnType,
11726 ParameterName,
11727 ParameterType,
11728 ParameterSingleDefaultArgument,
11729 ParameterDifferentDefaultArgument,
11730 FunctionBody,
11731 };
11732
11733 FunctionDecl *FirstFunction = Merge.first;
11734 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11735
11736 bool Diagnosed = false;
11737 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011738
Richard Trieue6caa262017-12-23 00:41:01 +000011739 if (FirstFunction == SecondFunction)
11740 continue;
11741
11742 std::string SecondModule =
11743 getOwningModuleNameForDiagnostic(SecondFunction);
11744
11745 auto ODRDiagError = [FirstFunction, &FirstModule,
11746 this](SourceLocation Loc, SourceRange Range,
11747 ODRFunctionDifference DiffType) {
11748 return Diag(Loc, diag::err_module_odr_violation_function)
11749 << FirstFunction << FirstModule.empty() << FirstModule << Range
11750 << DiffType;
11751 };
11752 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11753 SourceRange Range,
11754 ODRFunctionDifference DiffType) {
11755 return Diag(Loc, diag::note_module_odr_violation_function)
11756 << SecondModule << Range << DiffType;
11757 };
11758
11759 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11760 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11761 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11762 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11763 << FirstFunction->getReturnType();
11764 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11765 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11766 << SecondFunction->getReturnType();
11767 Diagnosed = true;
11768 break;
11769 }
11770
11771 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11772 "Merged functions with different number of parameters");
11773
11774 auto ParamSize = FirstFunction->param_size();
11775 bool ParameterMismatch = false;
11776 for (unsigned I = 0; I < ParamSize; ++I) {
11777 auto *FirstParam = FirstFunction->getParamDecl(I);
11778 auto *SecondParam = SecondFunction->getParamDecl(I);
11779
11780 assert(getContext().hasSameType(FirstParam->getType(),
11781 SecondParam->getType()) &&
11782 "Merged function has different parameter types.");
11783
11784 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11785 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11786 ParameterName)
11787 << I + 1 << FirstParam->getDeclName();
11788 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11789 ParameterName)
11790 << I + 1 << SecondParam->getDeclName();
11791 ParameterMismatch = true;
11792 break;
11793 };
11794
11795 QualType FirstParamType = FirstParam->getType();
11796 QualType SecondParamType = SecondParam->getType();
11797 if (FirstParamType != SecondParamType &&
11798 ComputeQualTypeODRHash(FirstParamType) !=
11799 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011800 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011801 FirstParamType->getAs<DecayedType>()) {
11802 ODRDiagError(FirstParam->getLocation(),
11803 FirstParam->getSourceRange(), ParameterType)
11804 << (I + 1) << FirstParamType << true
11805 << ParamDecayedType->getOriginalType();
11806 } else {
11807 ODRDiagError(FirstParam->getLocation(),
11808 FirstParam->getSourceRange(), ParameterType)
11809 << (I + 1) << FirstParamType << false;
11810 }
11811
Vedant Kumar48b4f762018-04-14 01:40:48 +000011812 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011813 SecondParamType->getAs<DecayedType>()) {
11814 ODRDiagNote(SecondParam->getLocation(),
11815 SecondParam->getSourceRange(), ParameterType)
11816 << (I + 1) << SecondParamType << true
11817 << ParamDecayedType->getOriginalType();
11818 } else {
11819 ODRDiagNote(SecondParam->getLocation(),
11820 SecondParam->getSourceRange(), ParameterType)
11821 << (I + 1) << SecondParamType << false;
11822 }
11823 ParameterMismatch = true;
11824 break;
11825 }
11826
11827 const Expr *FirstInit = FirstParam->getInit();
11828 const Expr *SecondInit = SecondParam->getInit();
11829 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11830 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11831 ParameterSingleDefaultArgument)
11832 << (I + 1) << (FirstInit == nullptr)
11833 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11834 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11835 ParameterSingleDefaultArgument)
11836 << (I + 1) << (SecondInit == nullptr)
11837 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11838 ParameterMismatch = true;
11839 break;
11840 }
11841
11842 if (FirstInit && SecondInit &&
11843 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11844 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11845 ParameterDifferentDefaultArgument)
11846 << (I + 1) << FirstInit->getSourceRange();
11847 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11848 ParameterDifferentDefaultArgument)
11849 << (I + 1) << SecondInit->getSourceRange();
11850 ParameterMismatch = true;
11851 break;
11852 }
11853
11854 assert(ComputeSubDeclODRHash(FirstParam) ==
11855 ComputeSubDeclODRHash(SecondParam) &&
11856 "Undiagnosed parameter difference.");
11857 }
11858
11859 if (ParameterMismatch) {
11860 Diagnosed = true;
11861 break;
11862 }
11863
11864 // If no error has been generated before now, assume the problem is in
11865 // the body and generate a message.
11866 ODRDiagError(FirstFunction->getLocation(),
11867 FirstFunction->getSourceRange(), FunctionBody);
11868 ODRDiagNote(SecondFunction->getLocation(),
11869 SecondFunction->getSourceRange(), FunctionBody);
11870 Diagnosed = true;
11871 break;
11872 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011873 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011874 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11875 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011876
11877 // Issue ODR failures diagnostics for enums.
11878 for (auto &Merge : EnumOdrMergeFailures) {
11879 enum ODREnumDifference {
11880 SingleScopedEnum,
11881 EnumTagKeywordMismatch,
11882 SingleSpecifiedType,
11883 DifferentSpecifiedTypes,
11884 DifferentNumberEnumConstants,
11885 EnumConstantName,
11886 EnumConstantSingleInitilizer,
11887 EnumConstantDifferentInitilizer,
11888 };
11889
11890 // If we've already pointed out a specific problem with this enum, don't
11891 // bother issuing a general "something's different" diagnostic.
11892 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11893 continue;
11894
11895 EnumDecl *FirstEnum = Merge.first;
11896 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11897
11898 using DeclHashes =
11899 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11900 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11901 DeclHashes &Hashes, EnumDecl *Enum) {
11902 for (auto *D : Enum->decls()) {
11903 // Due to decl merging, the first EnumDecl is the parent of
11904 // Decls in both records.
11905 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11906 continue;
11907 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11908 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11909 ComputeSubDeclODRHash(D));
11910 }
11911 };
11912 DeclHashes FirstHashes;
11913 PopulateHashes(FirstHashes, FirstEnum);
11914 bool Diagnosed = false;
11915 for (auto &SecondEnum : Merge.second) {
11916
11917 if (FirstEnum == SecondEnum)
11918 continue;
11919
11920 std::string SecondModule =
11921 getOwningModuleNameForDiagnostic(SecondEnum);
11922
11923 auto ODRDiagError = [FirstEnum, &FirstModule,
11924 this](SourceLocation Loc, SourceRange Range,
11925 ODREnumDifference DiffType) {
11926 return Diag(Loc, diag::err_module_odr_violation_enum)
11927 << FirstEnum << FirstModule.empty() << FirstModule << Range
11928 << DiffType;
11929 };
11930 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11931 SourceRange Range,
11932 ODREnumDifference DiffType) {
11933 return Diag(Loc, diag::note_module_odr_violation_enum)
11934 << SecondModule << Range << DiffType;
11935 };
11936
11937 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11938 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11939 SingleScopedEnum)
11940 << FirstEnum->isScoped();
11941 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11942 SingleScopedEnum)
11943 << SecondEnum->isScoped();
11944 Diagnosed = true;
11945 continue;
11946 }
11947
11948 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11949 if (FirstEnum->isScopedUsingClassTag() !=
11950 SecondEnum->isScopedUsingClassTag()) {
11951 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11952 EnumTagKeywordMismatch)
11953 << FirstEnum->isScopedUsingClassTag();
11954 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11955 EnumTagKeywordMismatch)
11956 << SecondEnum->isScopedUsingClassTag();
11957 Diagnosed = true;
11958 continue;
11959 }
11960 }
11961
11962 QualType FirstUnderlyingType =
11963 FirstEnum->getIntegerTypeSourceInfo()
11964 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11965 : QualType();
11966 QualType SecondUnderlyingType =
11967 SecondEnum->getIntegerTypeSourceInfo()
11968 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11969 : QualType();
11970 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11971 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11972 SingleSpecifiedType)
11973 << !FirstUnderlyingType.isNull();
11974 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11975 SingleSpecifiedType)
11976 << !SecondUnderlyingType.isNull();
11977 Diagnosed = true;
11978 continue;
11979 }
11980
11981 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11982 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11983 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11984 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11985 DifferentSpecifiedTypes)
11986 << FirstUnderlyingType;
11987 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11988 DifferentSpecifiedTypes)
11989 << SecondUnderlyingType;
11990 Diagnosed = true;
11991 continue;
11992 }
11993 }
11994
11995 DeclHashes SecondHashes;
11996 PopulateHashes(SecondHashes, SecondEnum);
11997
11998 if (FirstHashes.size() != SecondHashes.size()) {
11999 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
12000 DifferentNumberEnumConstants)
12001 << (int)FirstHashes.size();
12002 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
12003 DifferentNumberEnumConstants)
12004 << (int)SecondHashes.size();
12005 Diagnosed = true;
12006 continue;
12007 }
12008
12009 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
12010 if (FirstHashes[I].second == SecondHashes[I].second)
12011 continue;
12012 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
12013 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
12014
12015 if (FirstEnumConstant->getDeclName() !=
12016 SecondEnumConstant->getDeclName()) {
12017
12018 ODRDiagError(FirstEnumConstant->getLocation(),
12019 FirstEnumConstant->getSourceRange(), EnumConstantName)
12020 << I + 1 << FirstEnumConstant;
12021 ODRDiagNote(SecondEnumConstant->getLocation(),
12022 SecondEnumConstant->getSourceRange(), EnumConstantName)
12023 << I + 1 << SecondEnumConstant;
12024 Diagnosed = true;
12025 break;
12026 }
12027
12028 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
12029 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
12030 if (!FirstInit && !SecondInit)
12031 continue;
12032
12033 if (!FirstInit || !SecondInit) {
12034 ODRDiagError(FirstEnumConstant->getLocation(),
12035 FirstEnumConstant->getSourceRange(),
12036 EnumConstantSingleInitilizer)
12037 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
12038 ODRDiagNote(SecondEnumConstant->getLocation(),
12039 SecondEnumConstant->getSourceRange(),
12040 EnumConstantSingleInitilizer)
12041 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
12042 Diagnosed = true;
12043 break;
12044 }
12045
12046 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
12047 ODRDiagError(FirstEnumConstant->getLocation(),
12048 FirstEnumConstant->getSourceRange(),
12049 EnumConstantDifferentInitilizer)
12050 << I + 1 << FirstEnumConstant;
12051 ODRDiagNote(SecondEnumConstant->getLocation(),
12052 SecondEnumConstant->getSourceRange(),
12053 EnumConstantDifferentInitilizer)
12054 << I + 1 << SecondEnumConstant;
12055 Diagnosed = true;
12056 break;
12057 }
12058 }
12059 }
12060
12061 (void)Diagnosed;
12062 assert(Diagnosed && "Unable to emit ODR diagnostic.");
12063 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012064}
12065
Richard Smithce18a182015-07-14 00:26:00 +000012066void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000012067 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000012068 ReadTimer->startTimer();
12069}
12070
Guy Benyei11169dd2012-12-18 14:30:41 +000012071void ASTReader::FinishedDeserializing() {
12072 assert(NumCurrentElementsDeserializing &&
12073 "FinishedDeserializing not paired with StartedDeserializing");
12074 if (NumCurrentElementsDeserializing == 1) {
12075 // We decrease NumCurrentElementsDeserializing only after pending actions
12076 // are finished, to avoid recursively re-calling finishPendingActions().
12077 finishPendingActions();
12078 }
12079 --NumCurrentElementsDeserializing;
12080
Richard Smitha0ce9c42014-07-29 23:23:27 +000012081 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000012082 // Propagate exception specification and deduced type updates along
12083 // redeclaration chains.
12084 //
12085 // We do this now rather than in finishPendingActions because we want to
12086 // be able to walk the complete redeclaration chains of the updated decls.
12087 while (!PendingExceptionSpecUpdates.empty() ||
12088 !PendingDeducedTypeUpdates.empty()) {
12089 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000012090 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000012091 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000012092 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000012093 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000012094 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000012095 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000012096 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000012097 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000012098 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000012099 }
Richard Smitha62d1982018-08-03 01:00:01 +000012100
12101 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
12102 PendingDeducedTypeUpdates.clear();
12103 for (auto Update : DTUpdates) {
12104 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
12105 // FIXME: If the return type is already deduced, check that it matches.
12106 getContext().adjustDeducedFunctionResultType(Update.first,
12107 Update.second);
12108 }
Richard Smith9e2341d2015-03-23 03:25:59 +000012109 }
12110
Richard Smithce18a182015-07-14 00:26:00 +000012111 if (ReadTimer)
12112 ReadTimer->stopTimer();
12113
Richard Smith0f4e2c42015-08-06 04:23:48 +000012114 diagnoseOdrViolations();
12115
Richard Smith04d05b52014-03-23 00:27:18 +000012116 // We are not in recursive loading, so it's safe to pass the "interesting"
12117 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000012118 if (Consumer)
12119 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000012120 }
12121}
12122
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012123void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000012124 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
12125 // Remove any fake results before adding any real ones.
12126 auto It = PendingFakeLookupResults.find(II);
12127 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000012128 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000012129 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000012130 // FIXME: this works around module+PCH performance issue.
12131 // Rather than erase the result from the map, which is O(n), just clear
12132 // the vector of NamedDecls.
12133 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000012134 }
12135 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000012136
12137 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
12138 SemaObj->TUScope->AddDecl(D);
12139 } else if (SemaObj->TUScope) {
12140 // Adding the decl to IdResolver may have failed because it was already in
12141 // (even though it was not added in scope). If it is already in, make sure
12142 // it gets in the scope as well.
12143 if (std::find(SemaObj->IdResolver.begin(Name),
12144 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
12145 SemaObj->TUScope->AddDecl(D);
12146 }
12147}
12148
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012149ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
12150 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000012151 const PCHContainerReader &PCHContainerRdr,
12152 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
12153 StringRef isysroot, bool DisableValidation,
12154 bool AllowASTWithCompilerErrors,
12155 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
12156 bool UseGlobalIndex,
12157 std::unique_ptr<llvm::Timer> ReadTimer)
12158 : Listener(DisableValidation
12159 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
12160 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000012161 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012162 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000012163 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
12164 PCHContainerRdr, PP.getHeaderSearchInfo()),
12165 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000012166 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000012167 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
12168 AllowConfigurationMismatch(AllowConfigurationMismatch),
12169 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000012170 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000012171 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000012172
12173 for (const auto &Ext : Extensions) {
12174 auto BlockName = Ext->getExtensionMetadata().BlockName;
12175 auto Known = ModuleFileExtensions.find(BlockName);
12176 if (Known != ModuleFileExtensions.end()) {
12177 Diags.Report(diag::warn_duplicate_module_file_extension)
12178 << BlockName;
12179 continue;
12180 }
12181
12182 ModuleFileExtensions.insert({BlockName, Ext});
12183 }
Guy Benyei11169dd2012-12-18 14:30:41 +000012184}
12185
12186ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000012187 if (OwnsDeserializationListener)
12188 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000012189}
Richard Smith10379092016-05-06 23:14:07 +000012190
12191IdentifierResolver &ASTReader::getIdResolver() {
12192 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
12193}
David L. Jonesbe1557a2016-12-21 00:17:49 +000012194
JF Bastien0e828952019-06-26 19:50:12 +000012195Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
12196 unsigned AbbrevID) {
David L. Jonesbe1557a2016-12-21 00:17:49 +000012197 Idx = 0;
12198 Record.clear();
12199 return Cursor.readRecord(AbbrevID, Record);
12200}
Kelvin Libe286f52018-09-15 13:54:15 +000012201//===----------------------------------------------------------------------===//
12202//// OMPClauseReader implementation
12203////===----------------------------------------------------------------------===//
12204
12205OMPClause *OMPClauseReader::readClause() {
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000012206 OMPClause *C = nullptr;
Kelvin Libe286f52018-09-15 13:54:15 +000012207 switch (Record.readInt()) {
12208 case OMPC_if:
12209 C = new (Context) OMPIfClause();
12210 break;
12211 case OMPC_final:
12212 C = new (Context) OMPFinalClause();
12213 break;
12214 case OMPC_num_threads:
12215 C = new (Context) OMPNumThreadsClause();
12216 break;
12217 case OMPC_safelen:
12218 C = new (Context) OMPSafelenClause();
12219 break;
12220 case OMPC_simdlen:
12221 C = new (Context) OMPSimdlenClause();
12222 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012223 case OMPC_allocator:
12224 C = new (Context) OMPAllocatorClause();
12225 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012226 case OMPC_collapse:
12227 C = new (Context) OMPCollapseClause();
12228 break;
12229 case OMPC_default:
12230 C = new (Context) OMPDefaultClause();
12231 break;
12232 case OMPC_proc_bind:
12233 C = new (Context) OMPProcBindClause();
12234 break;
12235 case OMPC_schedule:
12236 C = new (Context) OMPScheduleClause();
12237 break;
12238 case OMPC_ordered:
12239 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
12240 break;
12241 case OMPC_nowait:
12242 C = new (Context) OMPNowaitClause();
12243 break;
12244 case OMPC_untied:
12245 C = new (Context) OMPUntiedClause();
12246 break;
12247 case OMPC_mergeable:
12248 C = new (Context) OMPMergeableClause();
12249 break;
12250 case OMPC_read:
12251 C = new (Context) OMPReadClause();
12252 break;
12253 case OMPC_write:
12254 C = new (Context) OMPWriteClause();
12255 break;
12256 case OMPC_update:
12257 C = new (Context) OMPUpdateClause();
12258 break;
12259 case OMPC_capture:
12260 C = new (Context) OMPCaptureClause();
12261 break;
12262 case OMPC_seq_cst:
12263 C = new (Context) OMPSeqCstClause();
12264 break;
12265 case OMPC_threads:
12266 C = new (Context) OMPThreadsClause();
12267 break;
12268 case OMPC_simd:
12269 C = new (Context) OMPSIMDClause();
12270 break;
12271 case OMPC_nogroup:
12272 C = new (Context) OMPNogroupClause();
12273 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012274 case OMPC_unified_address:
12275 C = new (Context) OMPUnifiedAddressClause();
12276 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012277 case OMPC_unified_shared_memory:
12278 C = new (Context) OMPUnifiedSharedMemoryClause();
12279 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012280 case OMPC_reverse_offload:
12281 C = new (Context) OMPReverseOffloadClause();
12282 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012283 case OMPC_dynamic_allocators:
12284 C = new (Context) OMPDynamicAllocatorsClause();
12285 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012286 case OMPC_atomic_default_mem_order:
12287 C = new (Context) OMPAtomicDefaultMemOrderClause();
12288 break;
12289 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000012290 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
12291 break;
12292 case OMPC_firstprivate:
12293 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
12294 break;
12295 case OMPC_lastprivate:
12296 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
12297 break;
12298 case OMPC_shared:
12299 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
12300 break;
12301 case OMPC_reduction:
12302 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
12303 break;
12304 case OMPC_task_reduction:
12305 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
12306 break;
12307 case OMPC_in_reduction:
12308 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
12309 break;
12310 case OMPC_linear:
12311 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
12312 break;
12313 case OMPC_aligned:
12314 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
12315 break;
12316 case OMPC_copyin:
12317 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
12318 break;
12319 case OMPC_copyprivate:
12320 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
12321 break;
12322 case OMPC_flush:
12323 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
12324 break;
12325 case OMPC_depend: {
12326 unsigned NumVars = Record.readInt();
12327 unsigned NumLoops = Record.readInt();
12328 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
12329 break;
12330 }
12331 case OMPC_device:
12332 C = new (Context) OMPDeviceClause();
12333 break;
12334 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012335 OMPMappableExprListSizeTy Sizes;
12336 Sizes.NumVars = Record.readInt();
12337 Sizes.NumUniqueDeclarations = Record.readInt();
12338 Sizes.NumComponentLists = Record.readInt();
12339 Sizes.NumComponents = Record.readInt();
12340 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012341 break;
12342 }
12343 case OMPC_num_teams:
12344 C = new (Context) OMPNumTeamsClause();
12345 break;
12346 case OMPC_thread_limit:
12347 C = new (Context) OMPThreadLimitClause();
12348 break;
12349 case OMPC_priority:
12350 C = new (Context) OMPPriorityClause();
12351 break;
12352 case OMPC_grainsize:
12353 C = new (Context) OMPGrainsizeClause();
12354 break;
12355 case OMPC_num_tasks:
12356 C = new (Context) OMPNumTasksClause();
12357 break;
12358 case OMPC_hint:
12359 C = new (Context) OMPHintClause();
12360 break;
12361 case OMPC_dist_schedule:
12362 C = new (Context) OMPDistScheduleClause();
12363 break;
12364 case OMPC_defaultmap:
12365 C = new (Context) OMPDefaultmapClause();
12366 break;
12367 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012368 OMPMappableExprListSizeTy Sizes;
12369 Sizes.NumVars = Record.readInt();
12370 Sizes.NumUniqueDeclarations = Record.readInt();
12371 Sizes.NumComponentLists = Record.readInt();
12372 Sizes.NumComponents = Record.readInt();
12373 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012374 break;
12375 }
12376 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012377 OMPMappableExprListSizeTy Sizes;
12378 Sizes.NumVars = Record.readInt();
12379 Sizes.NumUniqueDeclarations = Record.readInt();
12380 Sizes.NumComponentLists = Record.readInt();
12381 Sizes.NumComponents = Record.readInt();
12382 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012383 break;
12384 }
12385 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012386 OMPMappableExprListSizeTy Sizes;
12387 Sizes.NumVars = Record.readInt();
12388 Sizes.NumUniqueDeclarations = Record.readInt();
12389 Sizes.NumComponentLists = Record.readInt();
12390 Sizes.NumComponents = Record.readInt();
12391 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012392 break;
12393 }
12394 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012395 OMPMappableExprListSizeTy Sizes;
12396 Sizes.NumVars = Record.readInt();
12397 Sizes.NumUniqueDeclarations = Record.readInt();
12398 Sizes.NumComponentLists = Record.readInt();
12399 Sizes.NumComponents = Record.readInt();
12400 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000012401 break;
12402 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000012403 case OMPC_allocate:
12404 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
12405 break;
Kelvin Libe286f52018-09-15 13:54:15 +000012406 }
Simon Pilgrim556fbfe2019-09-15 16:05:20 +000012407 assert(C && "Unknown OMPClause type");
12408
Kelvin Libe286f52018-09-15 13:54:15 +000012409 Visit(C);
12410 C->setLocStart(Record.readSourceLocation());
12411 C->setLocEnd(Record.readSourceLocation());
12412
12413 return C;
12414}
12415
12416void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
12417 C->setPreInitStmt(Record.readSubStmt(),
12418 static_cast<OpenMPDirectiveKind>(Record.readInt()));
12419}
12420
12421void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
12422 VisitOMPClauseWithPreInit(C);
12423 C->setPostUpdateExpr(Record.readSubExpr());
12424}
12425
12426void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
12427 VisitOMPClauseWithPreInit(C);
12428 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
12429 C->setNameModifierLoc(Record.readSourceLocation());
12430 C->setColonLoc(Record.readSourceLocation());
12431 C->setCondition(Record.readSubExpr());
12432 C->setLParenLoc(Record.readSourceLocation());
12433}
12434
12435void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
12436 C->setCondition(Record.readSubExpr());
12437 C->setLParenLoc(Record.readSourceLocation());
12438}
12439
12440void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12441 VisitOMPClauseWithPreInit(C);
12442 C->setNumThreads(Record.readSubExpr());
12443 C->setLParenLoc(Record.readSourceLocation());
12444}
12445
12446void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12447 C->setSafelen(Record.readSubExpr());
12448 C->setLParenLoc(Record.readSourceLocation());
12449}
12450
12451void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12452 C->setSimdlen(Record.readSubExpr());
12453 C->setLParenLoc(Record.readSourceLocation());
12454}
12455
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012456void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12457 C->setAllocator(Record.readExpr());
12458 C->setLParenLoc(Record.readSourceLocation());
12459}
12460
Kelvin Libe286f52018-09-15 13:54:15 +000012461void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12462 C->setNumForLoops(Record.readSubExpr());
12463 C->setLParenLoc(Record.readSourceLocation());
12464}
12465
12466void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12467 C->setDefaultKind(
12468 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
12469 C->setLParenLoc(Record.readSourceLocation());
12470 C->setDefaultKindKwLoc(Record.readSourceLocation());
12471}
12472
12473void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12474 C->setProcBindKind(
12475 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
12476 C->setLParenLoc(Record.readSourceLocation());
12477 C->setProcBindKindKwLoc(Record.readSourceLocation());
12478}
12479
12480void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12481 VisitOMPClauseWithPreInit(C);
12482 C->setScheduleKind(
12483 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12484 C->setFirstScheduleModifier(
12485 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12486 C->setSecondScheduleModifier(
12487 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12488 C->setChunkSize(Record.readSubExpr());
12489 C->setLParenLoc(Record.readSourceLocation());
12490 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12491 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12492 C->setScheduleKindLoc(Record.readSourceLocation());
12493 C->setCommaLoc(Record.readSourceLocation());
12494}
12495
12496void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12497 C->setNumForLoops(Record.readSubExpr());
12498 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12499 C->setLoopNumIterations(I, Record.readSubExpr());
12500 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12501 C->setLoopCounter(I, Record.readSubExpr());
12502 C->setLParenLoc(Record.readSourceLocation());
12503}
12504
12505void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12506
12507void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12508
12509void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12510
12511void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12512
12513void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12514
12515void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12516
12517void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12518
12519void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12520
12521void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12522
12523void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12524
12525void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12526
Kelvin Li1408f912018-09-26 04:28:39 +000012527void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12528
Patrick Lyster4a370b92018-10-01 13:47:43 +000012529void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12530 OMPUnifiedSharedMemoryClause *) {}
12531
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012532void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12533
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012534void
12535OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12536}
12537
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012538void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12539 OMPAtomicDefaultMemOrderClause *C) {
12540 C->setAtomicDefaultMemOrderKind(
12541 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12542 C->setLParenLoc(Record.readSourceLocation());
12543 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12544}
12545
Kelvin Libe286f52018-09-15 13:54:15 +000012546void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12547 C->setLParenLoc(Record.readSourceLocation());
12548 unsigned NumVars = C->varlist_size();
12549 SmallVector<Expr *, 16> Vars;
12550 Vars.reserve(NumVars);
12551 for (unsigned i = 0; i != NumVars; ++i)
12552 Vars.push_back(Record.readSubExpr());
12553 C->setVarRefs(Vars);
12554 Vars.clear();
12555 for (unsigned i = 0; i != NumVars; ++i)
12556 Vars.push_back(Record.readSubExpr());
12557 C->setPrivateCopies(Vars);
12558}
12559
12560void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12561 VisitOMPClauseWithPreInit(C);
12562 C->setLParenLoc(Record.readSourceLocation());
12563 unsigned NumVars = C->varlist_size();
12564 SmallVector<Expr *, 16> Vars;
12565 Vars.reserve(NumVars);
12566 for (unsigned i = 0; i != NumVars; ++i)
12567 Vars.push_back(Record.readSubExpr());
12568 C->setVarRefs(Vars);
12569 Vars.clear();
12570 for (unsigned i = 0; i != NumVars; ++i)
12571 Vars.push_back(Record.readSubExpr());
12572 C->setPrivateCopies(Vars);
12573 Vars.clear();
12574 for (unsigned i = 0; i != NumVars; ++i)
12575 Vars.push_back(Record.readSubExpr());
12576 C->setInits(Vars);
12577}
12578
12579void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12580 VisitOMPClauseWithPostUpdate(C);
12581 C->setLParenLoc(Record.readSourceLocation());
12582 unsigned NumVars = C->varlist_size();
12583 SmallVector<Expr *, 16> Vars;
12584 Vars.reserve(NumVars);
12585 for (unsigned i = 0; i != NumVars; ++i)
12586 Vars.push_back(Record.readSubExpr());
12587 C->setVarRefs(Vars);
12588 Vars.clear();
12589 for (unsigned i = 0; i != NumVars; ++i)
12590 Vars.push_back(Record.readSubExpr());
12591 C->setPrivateCopies(Vars);
12592 Vars.clear();
12593 for (unsigned i = 0; i != NumVars; ++i)
12594 Vars.push_back(Record.readSubExpr());
12595 C->setSourceExprs(Vars);
12596 Vars.clear();
12597 for (unsigned i = 0; i != NumVars; ++i)
12598 Vars.push_back(Record.readSubExpr());
12599 C->setDestinationExprs(Vars);
12600 Vars.clear();
12601 for (unsigned i = 0; i != NumVars; ++i)
12602 Vars.push_back(Record.readSubExpr());
12603 C->setAssignmentOps(Vars);
12604}
12605
12606void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12607 C->setLParenLoc(Record.readSourceLocation());
12608 unsigned NumVars = C->varlist_size();
12609 SmallVector<Expr *, 16> Vars;
12610 Vars.reserve(NumVars);
12611 for (unsigned i = 0; i != NumVars; ++i)
12612 Vars.push_back(Record.readSubExpr());
12613 C->setVarRefs(Vars);
12614}
12615
12616void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12617 VisitOMPClauseWithPostUpdate(C);
12618 C->setLParenLoc(Record.readSourceLocation());
12619 C->setColonLoc(Record.readSourceLocation());
12620 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12621 DeclarationNameInfo DNI;
12622 Record.readDeclarationNameInfo(DNI);
12623 C->setQualifierLoc(NNSL);
12624 C->setNameInfo(DNI);
12625
12626 unsigned NumVars = C->varlist_size();
12627 SmallVector<Expr *, 16> Vars;
12628 Vars.reserve(NumVars);
12629 for (unsigned i = 0; i != NumVars; ++i)
12630 Vars.push_back(Record.readSubExpr());
12631 C->setVarRefs(Vars);
12632 Vars.clear();
12633 for (unsigned i = 0; i != NumVars; ++i)
12634 Vars.push_back(Record.readSubExpr());
12635 C->setPrivates(Vars);
12636 Vars.clear();
12637 for (unsigned i = 0; i != NumVars; ++i)
12638 Vars.push_back(Record.readSubExpr());
12639 C->setLHSExprs(Vars);
12640 Vars.clear();
12641 for (unsigned i = 0; i != NumVars; ++i)
12642 Vars.push_back(Record.readSubExpr());
12643 C->setRHSExprs(Vars);
12644 Vars.clear();
12645 for (unsigned i = 0; i != NumVars; ++i)
12646 Vars.push_back(Record.readSubExpr());
12647 C->setReductionOps(Vars);
12648}
12649
12650void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12651 VisitOMPClauseWithPostUpdate(C);
12652 C->setLParenLoc(Record.readSourceLocation());
12653 C->setColonLoc(Record.readSourceLocation());
12654 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12655 DeclarationNameInfo DNI;
12656 Record.readDeclarationNameInfo(DNI);
12657 C->setQualifierLoc(NNSL);
12658 C->setNameInfo(DNI);
12659
12660 unsigned NumVars = C->varlist_size();
12661 SmallVector<Expr *, 16> Vars;
12662 Vars.reserve(NumVars);
12663 for (unsigned I = 0; I != NumVars; ++I)
12664 Vars.push_back(Record.readSubExpr());
12665 C->setVarRefs(Vars);
12666 Vars.clear();
12667 for (unsigned I = 0; I != NumVars; ++I)
12668 Vars.push_back(Record.readSubExpr());
12669 C->setPrivates(Vars);
12670 Vars.clear();
12671 for (unsigned I = 0; I != NumVars; ++I)
12672 Vars.push_back(Record.readSubExpr());
12673 C->setLHSExprs(Vars);
12674 Vars.clear();
12675 for (unsigned I = 0; I != NumVars; ++I)
12676 Vars.push_back(Record.readSubExpr());
12677 C->setRHSExprs(Vars);
12678 Vars.clear();
12679 for (unsigned I = 0; I != NumVars; ++I)
12680 Vars.push_back(Record.readSubExpr());
12681 C->setReductionOps(Vars);
12682}
12683
12684void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12685 VisitOMPClauseWithPostUpdate(C);
12686 C->setLParenLoc(Record.readSourceLocation());
12687 C->setColonLoc(Record.readSourceLocation());
12688 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12689 DeclarationNameInfo DNI;
12690 Record.readDeclarationNameInfo(DNI);
12691 C->setQualifierLoc(NNSL);
12692 C->setNameInfo(DNI);
12693
12694 unsigned NumVars = C->varlist_size();
12695 SmallVector<Expr *, 16> Vars;
12696 Vars.reserve(NumVars);
12697 for (unsigned I = 0; I != NumVars; ++I)
12698 Vars.push_back(Record.readSubExpr());
12699 C->setVarRefs(Vars);
12700 Vars.clear();
12701 for (unsigned I = 0; I != NumVars; ++I)
12702 Vars.push_back(Record.readSubExpr());
12703 C->setPrivates(Vars);
12704 Vars.clear();
12705 for (unsigned I = 0; I != NumVars; ++I)
12706 Vars.push_back(Record.readSubExpr());
12707 C->setLHSExprs(Vars);
12708 Vars.clear();
12709 for (unsigned I = 0; I != NumVars; ++I)
12710 Vars.push_back(Record.readSubExpr());
12711 C->setRHSExprs(Vars);
12712 Vars.clear();
12713 for (unsigned I = 0; I != NumVars; ++I)
12714 Vars.push_back(Record.readSubExpr());
12715 C->setReductionOps(Vars);
12716 Vars.clear();
12717 for (unsigned I = 0; I != NumVars; ++I)
12718 Vars.push_back(Record.readSubExpr());
12719 C->setTaskgroupDescriptors(Vars);
12720}
12721
12722void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12723 VisitOMPClauseWithPostUpdate(C);
12724 C->setLParenLoc(Record.readSourceLocation());
12725 C->setColonLoc(Record.readSourceLocation());
12726 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12727 C->setModifierLoc(Record.readSourceLocation());
12728 unsigned NumVars = C->varlist_size();
12729 SmallVector<Expr *, 16> Vars;
12730 Vars.reserve(NumVars);
12731 for (unsigned i = 0; i != NumVars; ++i)
12732 Vars.push_back(Record.readSubExpr());
12733 C->setVarRefs(Vars);
12734 Vars.clear();
12735 for (unsigned i = 0; i != NumVars; ++i)
12736 Vars.push_back(Record.readSubExpr());
12737 C->setPrivates(Vars);
12738 Vars.clear();
12739 for (unsigned i = 0; i != NumVars; ++i)
12740 Vars.push_back(Record.readSubExpr());
12741 C->setInits(Vars);
12742 Vars.clear();
12743 for (unsigned i = 0; i != NumVars; ++i)
12744 Vars.push_back(Record.readSubExpr());
12745 C->setUpdates(Vars);
12746 Vars.clear();
12747 for (unsigned i = 0; i != NumVars; ++i)
12748 Vars.push_back(Record.readSubExpr());
12749 C->setFinals(Vars);
12750 C->setStep(Record.readSubExpr());
12751 C->setCalcStep(Record.readSubExpr());
Alexey Bataev195ae902019-08-08 13:42:45 +000012752 Vars.clear();
12753 for (unsigned I = 0; I != NumVars + 1; ++I)
12754 Vars.push_back(Record.readSubExpr());
12755 C->setUsedExprs(Vars);
Kelvin Libe286f52018-09-15 13:54:15 +000012756}
12757
12758void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12759 C->setLParenLoc(Record.readSourceLocation());
12760 C->setColonLoc(Record.readSourceLocation());
12761 unsigned NumVars = C->varlist_size();
12762 SmallVector<Expr *, 16> Vars;
12763 Vars.reserve(NumVars);
12764 for (unsigned i = 0; i != NumVars; ++i)
12765 Vars.push_back(Record.readSubExpr());
12766 C->setVarRefs(Vars);
12767 C->setAlignment(Record.readSubExpr());
12768}
12769
12770void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12771 C->setLParenLoc(Record.readSourceLocation());
12772 unsigned NumVars = C->varlist_size();
12773 SmallVector<Expr *, 16> Exprs;
12774 Exprs.reserve(NumVars);
12775 for (unsigned i = 0; i != NumVars; ++i)
12776 Exprs.push_back(Record.readSubExpr());
12777 C->setVarRefs(Exprs);
12778 Exprs.clear();
12779 for (unsigned i = 0; i != NumVars; ++i)
12780 Exprs.push_back(Record.readSubExpr());
12781 C->setSourceExprs(Exprs);
12782 Exprs.clear();
12783 for (unsigned i = 0; i != NumVars; ++i)
12784 Exprs.push_back(Record.readSubExpr());
12785 C->setDestinationExprs(Exprs);
12786 Exprs.clear();
12787 for (unsigned i = 0; i != NumVars; ++i)
12788 Exprs.push_back(Record.readSubExpr());
12789 C->setAssignmentOps(Exprs);
12790}
12791
12792void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12793 C->setLParenLoc(Record.readSourceLocation());
12794 unsigned NumVars = C->varlist_size();
12795 SmallVector<Expr *, 16> Exprs;
12796 Exprs.reserve(NumVars);
12797 for (unsigned i = 0; i != NumVars; ++i)
12798 Exprs.push_back(Record.readSubExpr());
12799 C->setVarRefs(Exprs);
12800 Exprs.clear();
12801 for (unsigned i = 0; i != NumVars; ++i)
12802 Exprs.push_back(Record.readSubExpr());
12803 C->setSourceExprs(Exprs);
12804 Exprs.clear();
12805 for (unsigned i = 0; i != NumVars; ++i)
12806 Exprs.push_back(Record.readSubExpr());
12807 C->setDestinationExprs(Exprs);
12808 Exprs.clear();
12809 for (unsigned i = 0; i != NumVars; ++i)
12810 Exprs.push_back(Record.readSubExpr());
12811 C->setAssignmentOps(Exprs);
12812}
12813
12814void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12815 C->setLParenLoc(Record.readSourceLocation());
12816 unsigned NumVars = C->varlist_size();
12817 SmallVector<Expr *, 16> Vars;
12818 Vars.reserve(NumVars);
12819 for (unsigned i = 0; i != NumVars; ++i)
12820 Vars.push_back(Record.readSubExpr());
12821 C->setVarRefs(Vars);
12822}
12823
12824void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12825 C->setLParenLoc(Record.readSourceLocation());
12826 C->setDependencyKind(
12827 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12828 C->setDependencyLoc(Record.readSourceLocation());
12829 C->setColonLoc(Record.readSourceLocation());
12830 unsigned NumVars = C->varlist_size();
12831 SmallVector<Expr *, 16> Vars;
12832 Vars.reserve(NumVars);
12833 for (unsigned I = 0; I != NumVars; ++I)
12834 Vars.push_back(Record.readSubExpr());
12835 C->setVarRefs(Vars);
12836 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12837 C->setLoopData(I, Record.readSubExpr());
12838}
12839
12840void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12841 VisitOMPClauseWithPreInit(C);
12842 C->setDevice(Record.readSubExpr());
12843 C->setLParenLoc(Record.readSourceLocation());
12844}
12845
12846void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12847 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012848 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12849 C->setMapTypeModifier(
12850 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12851 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12852 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012853 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12854 DeclarationNameInfo DNI;
12855 Record.readDeclarationNameInfo(DNI);
12856 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012857 C->setMapType(
12858 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12859 C->setMapLoc(Record.readSourceLocation());
12860 C->setColonLoc(Record.readSourceLocation());
12861 auto NumVars = C->varlist_size();
12862 auto UniqueDecls = C->getUniqueDeclarationsNum();
12863 auto TotalLists = C->getTotalComponentListNum();
12864 auto TotalComponents = C->getTotalComponentsNum();
12865
12866 SmallVector<Expr *, 16> Vars;
12867 Vars.reserve(NumVars);
12868 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012869 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012870 C->setVarRefs(Vars);
12871
Michael Kruse4304e9d2019-02-19 16:38:20 +000012872 SmallVector<Expr *, 16> UDMappers;
12873 UDMappers.reserve(NumVars);
12874 for (unsigned I = 0; I < NumVars; ++I)
12875 UDMappers.push_back(Record.readExpr());
12876 C->setUDMapperRefs(UDMappers);
12877
Kelvin Libe286f52018-09-15 13:54:15 +000012878 SmallVector<ValueDecl *, 16> Decls;
12879 Decls.reserve(UniqueDecls);
12880 for (unsigned i = 0; i < UniqueDecls; ++i)
12881 Decls.push_back(Record.readDeclAs<ValueDecl>());
12882 C->setUniqueDecls(Decls);
12883
12884 SmallVector<unsigned, 16> ListsPerDecl;
12885 ListsPerDecl.reserve(UniqueDecls);
12886 for (unsigned i = 0; i < UniqueDecls; ++i)
12887 ListsPerDecl.push_back(Record.readInt());
12888 C->setDeclNumLists(ListsPerDecl);
12889
12890 SmallVector<unsigned, 32> ListSizes;
12891 ListSizes.reserve(TotalLists);
12892 for (unsigned i = 0; i < TotalLists; ++i)
12893 ListSizes.push_back(Record.readInt());
12894 C->setComponentListSizes(ListSizes);
12895
12896 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12897 Components.reserve(TotalComponents);
12898 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012899 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012900 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12901 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12902 AssociatedExpr, AssociatedDecl));
12903 }
12904 C->setComponents(Components, ListSizes);
12905}
12906
Alexey Bataeve04483e2019-03-27 14:14:31 +000012907void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12908 C->setLParenLoc(Record.readSourceLocation());
12909 C->setColonLoc(Record.readSourceLocation());
12910 C->setAllocator(Record.readSubExpr());
12911 unsigned NumVars = C->varlist_size();
12912 SmallVector<Expr *, 16> Vars;
12913 Vars.reserve(NumVars);
12914 for (unsigned i = 0; i != NumVars; ++i)
12915 Vars.push_back(Record.readSubExpr());
12916 C->setVarRefs(Vars);
12917}
12918
Kelvin Libe286f52018-09-15 13:54:15 +000012919void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12920 VisitOMPClauseWithPreInit(C);
12921 C->setNumTeams(Record.readSubExpr());
12922 C->setLParenLoc(Record.readSourceLocation());
12923}
12924
12925void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12926 VisitOMPClauseWithPreInit(C);
12927 C->setThreadLimit(Record.readSubExpr());
12928 C->setLParenLoc(Record.readSourceLocation());
12929}
12930
12931void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12932 C->setPriority(Record.readSubExpr());
12933 C->setLParenLoc(Record.readSourceLocation());
12934}
12935
12936void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12937 C->setGrainsize(Record.readSubExpr());
12938 C->setLParenLoc(Record.readSourceLocation());
12939}
12940
12941void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12942 C->setNumTasks(Record.readSubExpr());
12943 C->setLParenLoc(Record.readSourceLocation());
12944}
12945
12946void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12947 C->setHint(Record.readSubExpr());
12948 C->setLParenLoc(Record.readSourceLocation());
12949}
12950
12951void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12952 VisitOMPClauseWithPreInit(C);
12953 C->setDistScheduleKind(
12954 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12955 C->setChunkSize(Record.readSubExpr());
12956 C->setLParenLoc(Record.readSourceLocation());
12957 C->setDistScheduleKindLoc(Record.readSourceLocation());
12958 C->setCommaLoc(Record.readSourceLocation());
12959}
12960
12961void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12962 C->setDefaultmapKind(
12963 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12964 C->setDefaultmapModifier(
12965 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12966 C->setLParenLoc(Record.readSourceLocation());
12967 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12968 C->setDefaultmapKindLoc(Record.readSourceLocation());
12969}
12970
12971void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12972 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012973 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12974 DeclarationNameInfo DNI;
12975 Record.readDeclarationNameInfo(DNI);
12976 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012977 auto NumVars = C->varlist_size();
12978 auto UniqueDecls = C->getUniqueDeclarationsNum();
12979 auto TotalLists = C->getTotalComponentListNum();
12980 auto TotalComponents = C->getTotalComponentsNum();
12981
12982 SmallVector<Expr *, 16> Vars;
12983 Vars.reserve(NumVars);
12984 for (unsigned i = 0; i != NumVars; ++i)
12985 Vars.push_back(Record.readSubExpr());
12986 C->setVarRefs(Vars);
12987
Michael Kruse01f670d2019-02-22 22:29:42 +000012988 SmallVector<Expr *, 16> UDMappers;
12989 UDMappers.reserve(NumVars);
12990 for (unsigned I = 0; I < NumVars; ++I)
12991 UDMappers.push_back(Record.readSubExpr());
12992 C->setUDMapperRefs(UDMappers);
12993
Kelvin Libe286f52018-09-15 13:54:15 +000012994 SmallVector<ValueDecl *, 16> Decls;
12995 Decls.reserve(UniqueDecls);
12996 for (unsigned i = 0; i < UniqueDecls; ++i)
12997 Decls.push_back(Record.readDeclAs<ValueDecl>());
12998 C->setUniqueDecls(Decls);
12999
13000 SmallVector<unsigned, 16> ListsPerDecl;
13001 ListsPerDecl.reserve(UniqueDecls);
13002 for (unsigned i = 0; i < UniqueDecls; ++i)
13003 ListsPerDecl.push_back(Record.readInt());
13004 C->setDeclNumLists(ListsPerDecl);
13005
13006 SmallVector<unsigned, 32> ListSizes;
13007 ListSizes.reserve(TotalLists);
13008 for (unsigned i = 0; i < TotalLists; ++i)
13009 ListSizes.push_back(Record.readInt());
13010 C->setComponentListSizes(ListSizes);
13011
13012 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13013 Components.reserve(TotalComponents);
13014 for (unsigned i = 0; i < TotalComponents; ++i) {
13015 Expr *AssociatedExpr = Record.readSubExpr();
13016 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13017 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13018 AssociatedExpr, AssociatedDecl));
13019 }
13020 C->setComponents(Components, ListSizes);
13021}
13022
13023void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
13024 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000013025 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
13026 DeclarationNameInfo DNI;
13027 Record.readDeclarationNameInfo(DNI);
13028 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000013029 auto NumVars = C->varlist_size();
13030 auto UniqueDecls = C->getUniqueDeclarationsNum();
13031 auto TotalLists = C->getTotalComponentListNum();
13032 auto TotalComponents = C->getTotalComponentsNum();
13033
13034 SmallVector<Expr *, 16> Vars;
13035 Vars.reserve(NumVars);
13036 for (unsigned i = 0; i != NumVars; ++i)
13037 Vars.push_back(Record.readSubExpr());
13038 C->setVarRefs(Vars);
13039
Michael Kruse0336c752019-02-25 20:34:15 +000013040 SmallVector<Expr *, 16> UDMappers;
13041 UDMappers.reserve(NumVars);
13042 for (unsigned I = 0; I < NumVars; ++I)
13043 UDMappers.push_back(Record.readSubExpr());
13044 C->setUDMapperRefs(UDMappers);
13045
Kelvin Libe286f52018-09-15 13:54:15 +000013046 SmallVector<ValueDecl *, 16> Decls;
13047 Decls.reserve(UniqueDecls);
13048 for (unsigned i = 0; i < UniqueDecls; ++i)
13049 Decls.push_back(Record.readDeclAs<ValueDecl>());
13050 C->setUniqueDecls(Decls);
13051
13052 SmallVector<unsigned, 16> ListsPerDecl;
13053 ListsPerDecl.reserve(UniqueDecls);
13054 for (unsigned i = 0; i < UniqueDecls; ++i)
13055 ListsPerDecl.push_back(Record.readInt());
13056 C->setDeclNumLists(ListsPerDecl);
13057
13058 SmallVector<unsigned, 32> ListSizes;
13059 ListSizes.reserve(TotalLists);
13060 for (unsigned i = 0; i < TotalLists; ++i)
13061 ListSizes.push_back(Record.readInt());
13062 C->setComponentListSizes(ListSizes);
13063
13064 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13065 Components.reserve(TotalComponents);
13066 for (unsigned i = 0; i < TotalComponents; ++i) {
13067 Expr *AssociatedExpr = Record.readSubExpr();
13068 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13069 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13070 AssociatedExpr, AssociatedDecl));
13071 }
13072 C->setComponents(Components, ListSizes);
13073}
13074
13075void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
13076 C->setLParenLoc(Record.readSourceLocation());
13077 auto NumVars = C->varlist_size();
13078 auto UniqueDecls = C->getUniqueDeclarationsNum();
13079 auto TotalLists = C->getTotalComponentListNum();
13080 auto TotalComponents = C->getTotalComponentsNum();
13081
13082 SmallVector<Expr *, 16> Vars;
13083 Vars.reserve(NumVars);
13084 for (unsigned i = 0; i != NumVars; ++i)
13085 Vars.push_back(Record.readSubExpr());
13086 C->setVarRefs(Vars);
13087 Vars.clear();
13088 for (unsigned i = 0; i != NumVars; ++i)
13089 Vars.push_back(Record.readSubExpr());
13090 C->setPrivateCopies(Vars);
13091 Vars.clear();
13092 for (unsigned i = 0; i != NumVars; ++i)
13093 Vars.push_back(Record.readSubExpr());
13094 C->setInits(Vars);
13095
13096 SmallVector<ValueDecl *, 16> Decls;
13097 Decls.reserve(UniqueDecls);
13098 for (unsigned i = 0; i < UniqueDecls; ++i)
13099 Decls.push_back(Record.readDeclAs<ValueDecl>());
13100 C->setUniqueDecls(Decls);
13101
13102 SmallVector<unsigned, 16> ListsPerDecl;
13103 ListsPerDecl.reserve(UniqueDecls);
13104 for (unsigned i = 0; i < UniqueDecls; ++i)
13105 ListsPerDecl.push_back(Record.readInt());
13106 C->setDeclNumLists(ListsPerDecl);
13107
13108 SmallVector<unsigned, 32> ListSizes;
13109 ListSizes.reserve(TotalLists);
13110 for (unsigned i = 0; i < TotalLists; ++i)
13111 ListSizes.push_back(Record.readInt());
13112 C->setComponentListSizes(ListSizes);
13113
13114 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13115 Components.reserve(TotalComponents);
13116 for (unsigned i = 0; i < TotalComponents; ++i) {
13117 Expr *AssociatedExpr = Record.readSubExpr();
13118 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13119 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13120 AssociatedExpr, AssociatedDecl));
13121 }
13122 C->setComponents(Components, ListSizes);
13123}
13124
13125void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
13126 C->setLParenLoc(Record.readSourceLocation());
13127 auto NumVars = C->varlist_size();
13128 auto UniqueDecls = C->getUniqueDeclarationsNum();
13129 auto TotalLists = C->getTotalComponentListNum();
13130 auto TotalComponents = C->getTotalComponentsNum();
13131
13132 SmallVector<Expr *, 16> Vars;
13133 Vars.reserve(NumVars);
13134 for (unsigned i = 0; i != NumVars; ++i)
13135 Vars.push_back(Record.readSubExpr());
13136 C->setVarRefs(Vars);
13137 Vars.clear();
13138
13139 SmallVector<ValueDecl *, 16> Decls;
13140 Decls.reserve(UniqueDecls);
13141 for (unsigned i = 0; i < UniqueDecls; ++i)
13142 Decls.push_back(Record.readDeclAs<ValueDecl>());
13143 C->setUniqueDecls(Decls);
13144
13145 SmallVector<unsigned, 16> ListsPerDecl;
13146 ListsPerDecl.reserve(UniqueDecls);
13147 for (unsigned i = 0; i < UniqueDecls; ++i)
13148 ListsPerDecl.push_back(Record.readInt());
13149 C->setDeclNumLists(ListsPerDecl);
13150
13151 SmallVector<unsigned, 32> ListSizes;
13152 ListSizes.reserve(TotalLists);
13153 for (unsigned i = 0; i < TotalLists; ++i)
13154 ListSizes.push_back(Record.readInt());
13155 C->setComponentListSizes(ListSizes);
13156
13157 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
13158 Components.reserve(TotalComponents);
13159 for (unsigned i = 0; i < TotalComponents; ++i) {
13160 Expr *AssociatedExpr = Record.readSubExpr();
13161 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
13162 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
13163 AssociatedExpr, AssociatedDecl));
13164 }
13165 C->setComponents(Components, ListSizes);
13166}