blob: fa4a4b38a0e51ae6ebfd688cd020f8f32ab1cb77 [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"
Guy Benyei11169dd2012-12-18 14:30:41 +0000104#include "llvm/Bitcode/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);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001151 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001152
Richard Smith0f4e2c42015-08-06 04:23:48 +00001153 RecordData Record;
1154 StringRef Blob;
1155 unsigned Code = Cursor.ReadCode();
1156 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1157 if (RecCode != DECL_CONTEXT_LEXICAL) {
1158 Error("Expected lexical block");
1159 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 }
1161
Richard Smith82f8fcd2015-08-06 22:07:25 +00001162 assert(!isa<TranslationUnitDecl>(DC) &&
1163 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001164 // If we are handling a C++ class template instantiation, we can see multiple
1165 // lexical updates for the same record. It's important that we select only one
1166 // of them, so that field numbering works properly. Just pick the first one we
1167 // see.
1168 auto &Lex = LexicalDecls[DC];
1169 if (!Lex.first) {
1170 Lex = std::make_pair(
1171 &M, llvm::makeArrayRef(
1172 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1173 Blob.data()),
1174 Blob.size() / 4));
1175 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001176 DC->setHasExternalLexicalStorage(true);
1177 return false;
1178}
Guy Benyei11169dd2012-12-18 14:30:41 +00001179
Richard Smith0f4e2c42015-08-06 04:23:48 +00001180bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1181 BitstreamCursor &Cursor,
1182 uint64_t Offset,
1183 DeclID ID) {
1184 assert(Offset != 0);
1185
1186 SavedStreamPosition SavedPosition(Cursor);
1187 Cursor.JumpToBit(Offset);
1188
1189 RecordData Record;
1190 StringRef Blob;
1191 unsigned Code = Cursor.ReadCode();
1192 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1193 if (RecCode != DECL_CONTEXT_VISIBLE) {
1194 Error("Expected visible lookup table block");
1195 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001196 }
1197
Richard Smith0f4e2c42015-08-06 04:23:48 +00001198 // We can't safely determine the primary context yet, so delay attaching the
1199 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001200 auto *Data = (const unsigned char*)Blob.data();
1201 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 return false;
1203}
1204
Richard Smith37a93df2017-02-18 00:32:02 +00001205void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001207 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001208 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001209 Diag(diag::note_module_cache_path)
1210 << PP.getHeaderSearchInfo().getModuleCachePath();
1211 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001212}
1213
1214void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001215 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 if (Diags.isDiagnosticInFlight())
1217 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1218 else
1219 Diag(DiagID) << Arg1 << Arg2;
1220}
1221
1222//===----------------------------------------------------------------------===//
1223// Source Manager Deserialization
1224//===----------------------------------------------------------------------===//
1225
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001226/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001227/// \returns true if there was an error.
1228bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001229 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001230 unsigned Idx = 0;
1231 LineTableInfo &LineTable = SourceMgr.getLineTable();
1232
1233 // Parse the file names
1234 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001235 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001236 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001238 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001239 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1240 }
Richard Smith63078492015-09-01 07:41:55 +00001241 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001242
1243 // Parse the line entries
1244 std::vector<LineEntry> Entries;
1245 while (Idx < Record.size()) {
1246 int FID = Record[Idx++];
1247 assert(FID >= 0 && "Serialized line entries for non-local file.");
1248 // Remap FileID from 1-based old view.
1249 FID += F.SLocEntryBaseID - 1;
1250
1251 // Extract the line entries
1252 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001253 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001254 Entries.clear();
1255 Entries.reserve(NumEntries);
1256 for (unsigned I = 0; I != NumEntries; ++I) {
1257 unsigned FileOffset = Record[Idx++];
1258 unsigned LineNo = Record[Idx++];
1259 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001260 SrcMgr::CharacteristicKind FileKind
1261 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001262 unsigned IncludeOffset = Record[Idx++];
1263 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1264 FileKind, IncludeOffset));
1265 }
1266 LineTable.AddEntry(FileID::get(FID), Entries);
1267 }
1268
1269 return false;
1270}
1271
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001272/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001273bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1274 using namespace SrcMgr;
1275
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001276 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001277
1278 // Set the source-location entry cursor to the current position in
1279 // the stream. This cursor will be used to read the contents of the
1280 // source manager block initially, and then lazily read
1281 // source-location entries as needed.
1282 SLocEntryCursor = F.Stream;
1283
1284 // The stream itself is going to skip over the source manager block.
1285 if (F.Stream.SkipBlock()) {
1286 Error("malformed block record in AST file");
1287 return true;
1288 }
1289
1290 // Enter the source manager block.
1291 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1292 Error("malformed source manager block record in AST file");
1293 return true;
1294 }
1295
1296 RecordData Record;
1297 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001298 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001299
Chris Lattnere7b154b2013-01-19 21:39:22 +00001300 switch (E.Kind) {
1301 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1302 case llvm::BitstreamEntry::Error:
1303 Error("malformed block record in AST file");
1304 return true;
1305 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001306 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001307 case llvm::BitstreamEntry::Record:
1308 // The interesting case.
1309 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001311
Guy Benyei11169dd2012-12-18 14:30:41 +00001312 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001314 StringRef Blob;
1315 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001316 default: // Default behavior: ignore.
1317 break;
1318
1319 case SM_SLOC_FILE_ENTRY:
1320 case SM_SLOC_BUFFER_ENTRY:
1321 case SM_SLOC_EXPANSION_ENTRY:
1322 // Once we hit one of the source location entries, we're done.
1323 return false;
1324 }
1325 }
1326}
1327
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001328/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001329/// and the PCH file was moved from its original location, try to resolve the
1330/// file by assuming that header+PCH were moved together and the header is in
1331/// the same place relative to the PCH.
1332static std::string
1333resolveFileRelativeToOriginalDir(const std::string &Filename,
1334 const std::string &OriginalDir,
1335 const std::string &CurrDir) {
1336 assert(OriginalDir != CurrDir &&
1337 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001338
Guy Benyei11169dd2012-12-18 14:30:41 +00001339 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001340
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 SmallString<128> filePath(Filename);
1342 fs::make_absolute(filePath);
1343 assert(path::is_absolute(OriginalDir));
1344 SmallString<128> currPCHPath(CurrDir);
1345
1346 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1347 fileDirE = path::end(path::parent_path(filePath));
1348 path::const_iterator origDirI = path::begin(OriginalDir),
1349 origDirE = path::end(OriginalDir);
1350 // Skip the common path components from filePath and OriginalDir.
1351 while (fileDirI != fileDirE && origDirI != origDirE &&
1352 *fileDirI == *origDirI) {
1353 ++fileDirI;
1354 ++origDirI;
1355 }
1356 for (; origDirI != origDirE; ++origDirI)
1357 path::append(currPCHPath, "..");
1358 path::append(currPCHPath, fileDirI, fileDirE);
1359 path::append(currPCHPath, path::filename(Filename));
1360 return currPCHPath.str();
1361}
1362
1363bool ASTReader::ReadSLocEntry(int ID) {
1364 if (ID == 0)
1365 return false;
1366
1367 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1368 Error("source location entry ID out-of-range for AST file");
1369 return true;
1370 }
1371
Richard Smithaada85c2016-02-06 02:06:43 +00001372 // Local helper to read the (possibly-compressed) buffer data following the
1373 // entry record.
1374 auto ReadBuffer = [this](
1375 BitstreamCursor &SLocEntryCursor,
1376 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1377 RecordData Record;
1378 StringRef Blob;
1379 unsigned Code = SLocEntryCursor.ReadCode();
1380 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1381
1382 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001383 if (!llvm::zlib::isAvailable()) {
1384 Error("zlib is not available");
1385 return nullptr;
1386 }
Richard Smithaada85c2016-02-06 02:06:43 +00001387 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001388 if (llvm::Error E =
1389 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1390 Error("could not decompress embedded file contents: " +
1391 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001392 return nullptr;
1393 }
1394 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1395 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1396 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1397 } else {
1398 Error("AST record has invalid code");
1399 return nullptr;
1400 }
1401 };
1402
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1404 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001405 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 unsigned BaseOffset = F->SLocEntryBaseOffset;
1407
1408 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001409 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1410 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 Error("incorrectly-formatted source location entry in AST file");
1412 return true;
1413 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001414
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001416 StringRef Blob;
1417 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 default:
1419 Error("incorrectly-formatted source location entry in AST file");
1420 return true;
1421
1422 case SM_SLOC_FILE_ENTRY: {
1423 // We will detect whether a file changed and return 'Failure' for it, but
1424 // we will also try to fail gracefully by setting up the SLocEntry.
1425 unsigned InputID = Record[4];
1426 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001427 const FileEntry *File = IF.getFile();
1428 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001429
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001430 // Note that we only check if a File was returned. If it was out-of-date
1431 // we have complained but we will continue creating a FileID to recover
1432 // gracefully.
1433 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 return true;
1435
1436 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1437 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1438 // This is the module's main file.
1439 IncludeLoc = getImportLocation(F);
1440 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001441 SrcMgr::CharacteristicKind
1442 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1444 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001445 SrcMgr::FileInfo &FileInfo =
1446 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001447 FileInfo.NumCreatedFIDs = Record[5];
1448 if (Record[3])
1449 FileInfo.setHasLineDirectives();
1450
1451 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1452 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001453 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001454 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1455 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1456 NumFileDecls));
1457 }
Richard Smithaada85c2016-02-06 02:06:43 +00001458
Guy Benyei11169dd2012-12-18 14:30:41 +00001459 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001460 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001462 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1463 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001464 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1465 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001466 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001467 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 }
1469
1470 break;
1471 }
1472
1473 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001474 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001476 SrcMgr::CharacteristicKind
1477 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001479 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 IncludeLoc = getImportLocation(F);
1481 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001482
Richard Smithaada85c2016-02-06 02:06:43 +00001483 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1484 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001486 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001487 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 break;
1489 }
1490
1491 case SM_SLOC_EXPANSION_ENTRY: {
1492 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1493 SourceMgr.createExpansionLoc(SpellingLoc,
1494 ReadSourceLocation(*F, Record[2]),
1495 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001496 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001497 Record[4],
1498 ID,
1499 BaseOffset + Record[0]);
1500 break;
1501 }
1502 }
1503
1504 return false;
1505}
1506
1507std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1508 if (ID == 0)
1509 return std::make_pair(SourceLocation(), "");
1510
1511 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1512 Error("source location entry ID out-of-range for AST file");
1513 return std::make_pair(SourceLocation(), "");
1514 }
1515
1516 // Find which module file this entry lands in.
1517 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001518 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 return std::make_pair(SourceLocation(), "");
1520
1521 // FIXME: Can we map this down to a particular submodule? That would be
1522 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001523 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001524}
1525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001526/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001527SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1528 if (F->ImportLoc.isValid())
1529 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001530
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 // Otherwise we have a PCH. It's considered to be "imported" at the first
1532 // location of its includer.
1533 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001534 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001535 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001536 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001537 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 return F->ImportedBy[0]->FirstLoc;
1539}
1540
1541/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1542/// specified cursor. Read the abbreviations that are at the top of the block
1543/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001544bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001545 if (Cursor.EnterSubBlock(BlockID))
1546 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001547
1548 while (true) {
1549 uint64_t Offset = Cursor.GetCurrentBitNo();
1550 unsigned Code = Cursor.ReadCode();
1551
1552 // We expect all abbrevs to be at the start of the block.
1553 if (Code != llvm::bitc::DEFINE_ABBREV) {
1554 Cursor.JumpToBit(Offset);
1555 return false;
1556 }
1557 Cursor.ReadAbbrevRecord();
1558 }
1559}
1560
Richard Smithe40f2ba2013-08-07 21:41:30 +00001561Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001562 unsigned &Idx) {
1563 Token Tok;
1564 Tok.startToken();
1565 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1566 Tok.setLength(Record[Idx++]);
1567 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1568 Tok.setIdentifierInfo(II);
1569 Tok.setKind((tok::TokenKind)Record[Idx++]);
1570 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1571 return Tok;
1572}
1573
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001574MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001575 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001576
1577 // Keep track of where we are in the stream, then jump back there
1578 // after reading this macro.
1579 SavedStreamPosition SavedPosition(Stream);
1580
1581 Stream.JumpToBit(Offset);
1582 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001583 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001584 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001585
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001587 // Advance to the next record, but if we get to the end of the block, don't
1588 // pop it (removing all the abbreviations from the cursor) since we want to
1589 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001590 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001591 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001592
Chris Lattnerefa77172013-01-20 00:00:22 +00001593 switch (Entry.Kind) {
1594 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1595 case llvm::BitstreamEntry::Error:
1596 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001597 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001598 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001599 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001600 case llvm::BitstreamEntry::Record:
1601 // The interesting case.
1602 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 }
1604
1605 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001606 Record.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00001607 PreprocessorRecordTypes RecType =
1608 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001609 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001610 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001611 case PP_MACRO_DIRECTIVE_HISTORY:
1612 return Macro;
1613
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 case PP_MACRO_OBJECT_LIKE:
1615 case PP_MACRO_FUNCTION_LIKE: {
1616 // If we already have a macro, that means that we've hit the end
1617 // of the definition of the macro we were looking for. We're
1618 // done.
1619 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001620 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001621
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001622 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001624 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001625 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001627 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001628
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1630 // Decode function-like macro info.
1631 bool isC99VarArgs = Record[NextIndex++];
1632 bool isGNUVarArgs = Record[NextIndex++];
1633 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001634 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 unsigned NumArgs = Record[NextIndex++];
1636 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001637 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001638
1639 // Install function-like macro info.
1640 MI->setIsFunctionLike();
1641 if (isC99VarArgs) MI->setIsC99Varargs();
1642 if (isGNUVarArgs) MI->setIsGNUVarargs();
1643 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001644 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 }
1646
Guy Benyei11169dd2012-12-18 14:30:41 +00001647 // Remember that we saw this macro last so that we add the tokens that
1648 // form its body to it.
1649 Macro = MI;
1650
1651 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1652 Record[NextIndex]) {
1653 // We have a macro definition. Register the association
1654 PreprocessedEntityID
1655 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1656 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001657 PreprocessingRecord::PPEntityID PPID =
1658 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001659 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001660 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001661 if (PPDef)
1662 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001663 }
1664
1665 ++NumMacrosRead;
1666 break;
1667 }
1668
1669 case PP_TOKEN: {
1670 // If we see a TOKEN before a PP_MACRO_*, then the file is
1671 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001672 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001673
John McCallf413f5e2013-05-03 00:10:13 +00001674 unsigned Idx = 0;
1675 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 Macro->AddTokenToBody(Tok);
1677 break;
1678 }
1679 }
1680 }
1681}
1682
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001683PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001684ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1685 unsigned LocalID) const {
1686 if (!M.ModuleOffsetMap.empty())
1687 ReadModuleOffsetMap(M);
1688
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001689 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001691 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001692 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001693
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 return LocalID + I->second;
1695}
1696
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001697unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1698 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001699}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001700
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001701HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001702HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001703 internal_key_type ikey = {FE->getSize(),
1704 M.HasTimestamps ? FE->getModificationTime() : 0,
1705 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001706 return ikey;
1707}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001708
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001709bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001710 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001711 return false;
1712
Mehdi Amini004b9c72016-10-10 22:52:47 +00001713 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001714 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001715
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001717 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001718 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1719 if (!Key.Imported)
1720 return FileMgr.getFile(Key.Filename);
1721
1722 std::string Resolved = Key.Filename;
1723 Reader.ResolveImportedPath(M, Resolved);
1724 return FileMgr.getFile(Resolved);
1725 };
1726
1727 const FileEntry *FEA = GetFile(a);
1728 const FileEntry *FEB = GetFile(b);
1729 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001730}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001731
Guy Benyei11169dd2012-12-18 14:30:41 +00001732std::pair<unsigned, unsigned>
1733HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001734 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001735
Vedant Kumar48b4f762018-04-14 01:40:48 +00001736 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1737 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001738 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001739}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001740
1741HeaderFileInfoTrait::internal_key_type
1742HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001743 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001744
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001745 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001746 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1747 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001748 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001749 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001750 return ikey;
1751}
1752
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001753HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001754HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001756 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001757
1758 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001759 HeaderFileInfo HFI;
1760 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001761 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001762 HFI.isImport |= (Flags >> 5) & 0x01;
1763 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1764 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001766 // FIXME: Find a better way to handle this. Maybe just store a
1767 // "has been included" flag?
1768 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1769 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001770 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1771 M, endian::readNext<uint32_t, little, unaligned>(d));
1772 if (unsigned FrameworkOffset =
1773 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001774 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 // since 0 is used as an indicator for "no framework name".
1776 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1777 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1778 }
Richard Smith386bb072015-08-18 23:42:23 +00001779
1780 assert((End - d) % 4 == 0 &&
1781 "Wrong data length in HeaderFileInfo deserialization");
1782 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001783 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001784 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1785 LocalSMID >>= 2;
1786
1787 // This header is part of a module. Associate it with the module to enable
1788 // implicit module import.
1789 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1790 Module *Mod = Reader.getSubmodule(GlobalSMID);
1791 FileManager &FileMgr = Reader.getFileManager();
1792 ModuleMap &ModMap =
1793 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1794
1795 std::string Filename = key.Filename;
1796 if (key.Imported)
1797 Reader.ResolveImportedPath(M, Filename);
1798 // FIXME: This is not always the right filename-as-written, but we're not
1799 // going to use this information to rebuild the module, so it doesn't make
1800 // a lot of difference.
1801 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001802 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1803 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001804 }
1805
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 // This HeaderFileInfo was externally loaded.
1807 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001808 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 return HFI;
1810}
1811
Richard Smithd7329392015-04-21 21:46:32 +00001812void ASTReader::addPendingMacro(IdentifierInfo *II,
1813 ModuleFile *M,
1814 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001815 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1816 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001817}
1818
1819void ASTReader::ReadDefinedMacros() {
1820 // Note that we are loading defined macros.
1821 Deserializing Macros(this);
1822
Vedant Kumar48b4f762018-04-14 01:40:48 +00001823 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001824 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001825
1826 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001827 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001828 continue;
1829
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001830 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001831 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001832
1833 RecordData Record;
1834 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001835 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001836
Chris Lattnere7b154b2013-01-19 21:39:22 +00001837 switch (E.Kind) {
1838 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1839 case llvm::BitstreamEntry::Error:
1840 Error("malformed block record in AST file");
1841 return;
1842 case llvm::BitstreamEntry::EndBlock:
1843 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001844
Chris Lattnere7b154b2013-01-19 21:39:22 +00001845 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001846 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001847 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001848 default: // Default behavior: ignore.
1849 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001850
Chris Lattnere7b154b2013-01-19 21:39:22 +00001851 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001852 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001853 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001854 if (II->isOutOfDate())
1855 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001856 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001857 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001858
Chris Lattnere7b154b2013-01-19 21:39:22 +00001859 case PP_TOKEN:
1860 // Ignore tokens.
1861 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001863 break;
1864 }
1865 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001866 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001867 }
1868}
1869
1870namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001871
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001872 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 class IdentifierLookupVisitor {
1874 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001875 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001876 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001877 unsigned &NumIdentifierLookups;
1878 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001879 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001880
Guy Benyei11169dd2012-12-18 14:30:41 +00001881 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001882 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1883 unsigned &NumIdentifierLookups,
1884 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001885 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1886 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001887 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001888 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001889
1890 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001892 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001894
Vedant Kumar48b4f762018-04-14 01:40:48 +00001895 ASTIdentifierLookupTable *IdTable
1896 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 if (!IdTable)
1898 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001899
1900 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001901 Found);
1902 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001903 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001904 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 if (Pos == IdTable->end())
1906 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001907
Guy Benyei11169dd2012-12-18 14:30:41 +00001908 // Dereferencing the iterator has the effect of building the
1909 // IdentifierInfo node and populating it with the various
1910 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001911 ++NumIdentifierLookupHits;
1912 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001913 return true;
1914 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001915
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001916 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 // files.
1918 IdentifierInfo *getIdentifierInfo() const { return Found; }
1919 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001920
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001921} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001922
1923void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1924 // Note that we are loading an identifier.
1925 Deserializing AnIdentifier(this);
1926
1927 unsigned PriorGeneration = 0;
1928 if (getContext().getLangOpts().Modules)
1929 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001930
1931 // If there is a global index, look there first to determine which modules
1932 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001933 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001934 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001935 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001936 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1937 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001938 }
1939 }
1940
Douglas Gregor7211ac12013-01-25 23:32:03 +00001941 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001942 NumIdentifierLookups,
1943 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001944 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001945 markIdentifierUpToDate(&II);
1946}
1947
1948void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1949 if (!II)
1950 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001951
Guy Benyei11169dd2012-12-18 14:30:41 +00001952 II->setOutOfDate(false);
1953
1954 // Update the generation for this identifier.
1955 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001956 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001957}
1958
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001959void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1960 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001961 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001962
1963 BitstreamCursor &Cursor = M.MacroCursor;
1964 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001965 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001966
Richard Smith713369b2015-04-23 20:40:50 +00001967 struct ModuleMacroRecord {
1968 SubmoduleID SubModID;
1969 MacroInfo *MI;
1970 SmallVector<SubmoduleID, 8> Overrides;
1971 };
1972 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001973
Richard Smithd7329392015-04-21 21:46:32 +00001974 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1975 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1976 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001977 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001978 while (true) {
1979 llvm::BitstreamEntry Entry =
1980 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1981 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1982 Error("malformed block record in AST file");
1983 return;
1984 }
1985
1986 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001987 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001988 case PP_MACRO_DIRECTIVE_HISTORY:
1989 break;
1990
1991 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001992 ModuleMacros.push_back(ModuleMacroRecord());
1993 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001994 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1995 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001996 for (int I = 2, N = Record.size(); I != N; ++I)
1997 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001998 continue;
1999 }
2000
2001 default:
2002 Error("malformed block record in AST file");
2003 return;
2004 }
2005
2006 // We found the macro directive history; that's the last record
2007 // for this macro.
2008 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002009 }
2010
Richard Smithd7329392015-04-21 21:46:32 +00002011 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002012 {
2013 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002014 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002015 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002016 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002017 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002018 Module *Mod = getSubmodule(ModID);
2019 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002020 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002021 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002022 }
2023
2024 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002025 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002026 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002027 }
2028 }
2029
2030 // Don't read the directive history for a module; we don't have anywhere
2031 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002032 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002033 return;
2034
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002035 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002036 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002037 unsigned Idx = 0, N = Record.size();
2038 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002039 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002040 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002041 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002042 switch (K) {
2043 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002044 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002045 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002046 break;
2047 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002048 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002049 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002050 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002051 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002052 bool isPublic = Record[Idx++];
2053 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2054 break;
2055 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002056
2057 if (!Latest)
2058 Latest = MD;
2059 if (Earliest)
2060 Earliest->setPrevious(MD);
2061 Earliest = MD;
2062 }
2063
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002064 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002065 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002066}
2067
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002068ASTReader::InputFileInfo
2069ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002070 // Go find this input file.
2071 BitstreamCursor &Cursor = F.InputFilesCursor;
2072 SavedStreamPosition SavedPosition(Cursor);
2073 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2074
2075 unsigned Code = Cursor.ReadCode();
2076 RecordData Record;
2077 StringRef Blob;
2078
2079 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2080 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2081 "invalid record type for input file");
2082 (void)Result;
2083
2084 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002085 InputFileInfo R;
2086 R.StoredSize = static_cast<off_t>(Record[1]);
2087 R.StoredTime = static_cast<time_t>(Record[2]);
2088 R.Overridden = static_cast<bool>(Record[3]);
2089 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002090 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002091 R.Filename = Blob;
2092 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002093 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002094}
2095
Manman Renc8c94152016-10-21 23:35:03 +00002096static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002097InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 // If this ID is bogus, just return an empty input file.
2099 if (ID == 0 || ID > F.InputFilesLoaded.size())
2100 return InputFile();
2101
2102 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002103 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 return F.InputFilesLoaded[ID-1];
2105
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002106 if (F.InputFilesLoaded[ID-1].isNotFound())
2107 return InputFile();
2108
Guy Benyei11169dd2012-12-18 14:30:41 +00002109 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002110 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 SavedStreamPosition SavedPosition(Cursor);
2112 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002113
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002114 InputFileInfo FI = readInputFileInfo(F, ID);
2115 off_t StoredSize = FI.StoredSize;
2116 time_t StoredTime = FI.StoredTime;
2117 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002118 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002119 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002120
Richard Smitha8cfffa2015-11-26 02:04:16 +00002121 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002122 // If we didn't find the file, resolve it relative to the
2123 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002124 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2125 F.OriginalDir != F.BaseDirectory) {
2126 std::string Resolved = resolveFileRelativeToOriginalDir(
2127 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002128 if (!Resolved.empty())
2129 File = FileMgr.getFile(Resolved);
2130 }
2131
2132 // For an overridden file, create a virtual file with the stored
2133 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002134 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002135 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002136
Craig Toppera13603a2014-05-22 05:54:18 +00002137 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002138 if (Complain) {
2139 std::string ErrorStr = "could not find file '";
2140 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002141 ErrorStr += "' referenced by AST file '";
2142 ErrorStr += F.FileName;
2143 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002144 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002146 // Record that we didn't find the file.
2147 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2148 return InputFile();
2149 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002150
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002152 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002153 // can lead to problems when lexing using the source locations from the
2154 // PCH.
2155 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002156 // FIXME: Reject if the overrides are different.
2157 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002158 if (Complain)
2159 Error(diag::err_fe_pch_file_overridden, Filename);
2160 // After emitting the diagnostic, recover by disabling the override so
2161 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002162 //
2163 // FIXME: This recovery is just as broken as the original state; there may
2164 // be another precompiled module that's using the overridden contents, or
2165 // we might be half way through parsing it. Instead, we should treat the
2166 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002167 SM.disableFileContentsOverride(File);
2168 // The FileEntry is a virtual file entry with the size of the contents
2169 // that would override the original contents. Set it to the original's
2170 // size/time.
2171 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2172 StoredSize, StoredTime);
2173 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002174
Ben Langmuir198c1682014-03-07 07:27:49 +00002175 bool IsOutOfDate = false;
2176
2177 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002178 if (!Overridden && //
2179 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002180 (StoredTime && StoredTime != File->getModificationTime() &&
2181 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002182 )) {
2183 if (Complain) {
2184 // Build a list of the PCH imports that got us here (in reverse).
2185 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002186 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002187 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002188
Ben Langmuir198c1682014-03-07 07:27:49 +00002189 // The top-level PCH is stale.
2190 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002191 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2192 if (DiagnosticKind == 0)
2193 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2194 else if (DiagnosticKind == 1)
2195 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2196 else
2197 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002198
Ben Langmuir198c1682014-03-07 07:27:49 +00002199 // Print the import stack.
2200 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2201 Diag(diag::note_pch_required_by)
2202 << Filename << ImportStack[0]->FileName;
2203 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002204 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002205 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002206 }
2207
Ben Langmuir198c1682014-03-07 07:27:49 +00002208 if (!Diags.isDiagnosticInFlight())
2209 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002210 }
2211
Ben Langmuir198c1682014-03-07 07:27:49 +00002212 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002213 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002214 // FIXME: If the file is overridden and we've already opened it,
2215 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002216
Richard Smitha8cfffa2015-11-26 02:04:16 +00002217 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002218
2219 // Note that we've loaded this input file.
2220 F.InputFilesLoaded[ID-1] = IF;
2221 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002222}
2223
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002224/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002225/// is not an absolute path, add the system or module root to the beginning of
2226/// the file name.
2227void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2228 // Resolve relative to the base directory, if we have one.
2229 if (!M.BaseDirectory.empty())
2230 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002231}
2232
Richard Smith7ed1bc92014-12-05 22:42:13 +00002233void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2235 return;
2236
Richard Smith7ed1bc92014-12-05 22:42:13 +00002237 SmallString<128> Buffer;
2238 llvm::sys::path::append(Buffer, Prefix, Filename);
2239 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002240}
2241
Richard Smith0f99d6a2015-08-09 08:48:41 +00002242static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2243 switch (ARR) {
2244 case ASTReader::Failure: return true;
2245 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2246 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2247 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2248 case ASTReader::ConfigurationMismatch:
2249 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2250 case ASTReader::HadErrors: return true;
2251 case ASTReader::Success: return false;
2252 }
2253
2254 llvm_unreachable("unknown ASTReadResult");
2255}
2256
Richard Smith0516b182015-09-08 19:40:14 +00002257ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2258 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2259 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002260 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002261 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2262 return Failure;
2263
2264 // Read all of the records in the options block.
2265 RecordData Record;
2266 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002267 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002268 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002269
Richard Smith0516b182015-09-08 19:40:14 +00002270 switch (Entry.Kind) {
2271 case llvm::BitstreamEntry::Error:
2272 case llvm::BitstreamEntry::SubBlock:
2273 return Failure;
2274
2275 case llvm::BitstreamEntry::EndBlock:
2276 return Result;
2277
2278 case llvm::BitstreamEntry::Record:
2279 // The interesting case.
2280 break;
2281 }
2282
2283 // Read and process a record.
2284 Record.clear();
2285 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2286 case LANGUAGE_OPTIONS: {
2287 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2288 if (ParseLanguageOptions(Record, Complain, Listener,
2289 AllowCompatibleConfigurationMismatch))
2290 Result = ConfigurationMismatch;
2291 break;
2292 }
2293
2294 case TARGET_OPTIONS: {
2295 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2296 if (ParseTargetOptions(Record, Complain, Listener,
2297 AllowCompatibleConfigurationMismatch))
2298 Result = ConfigurationMismatch;
2299 break;
2300 }
2301
Richard Smith0516b182015-09-08 19:40:14 +00002302 case FILE_SYSTEM_OPTIONS: {
2303 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2304 if (!AllowCompatibleConfigurationMismatch &&
2305 ParseFileSystemOptions(Record, Complain, Listener))
2306 Result = ConfigurationMismatch;
2307 break;
2308 }
2309
2310 case HEADER_SEARCH_OPTIONS: {
2311 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2312 if (!AllowCompatibleConfigurationMismatch &&
2313 ParseHeaderSearchOptions(Record, Complain, Listener))
2314 Result = ConfigurationMismatch;
2315 break;
2316 }
2317
2318 case PREPROCESSOR_OPTIONS:
2319 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2320 if (!AllowCompatibleConfigurationMismatch &&
2321 ParsePreprocessorOptions(Record, Complain, Listener,
2322 SuggestedPredefines))
2323 Result = ConfigurationMismatch;
2324 break;
2325 }
2326 }
2327}
2328
Guy Benyei11169dd2012-12-18 14:30:41 +00002329ASTReader::ASTReadResult
2330ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002331 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002332 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002334 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002335 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002336
2337 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2338 Error("malformed block record in AST file");
2339 return Failure;
2340 }
2341
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002342 // Lambda to read the unhashed control block the first time it's called.
2343 //
2344 // For PCM files, the unhashed control block cannot be read until after the
2345 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2346 // need to look ahead before reading the IMPORTS record. For consistency,
2347 // this block is always read somehow (see BitstreamEntry::EndBlock).
2348 bool HasReadUnhashedControlBlock = false;
2349 auto readUnhashedControlBlockOnce = [&]() {
2350 if (!HasReadUnhashedControlBlock) {
2351 HasReadUnhashedControlBlock = true;
2352 if (ASTReadResult Result =
2353 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2354 return Result;
2355 }
2356 return Success;
2357 };
2358
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 // Read all of the records and blocks in the control block.
2360 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002361 unsigned NumInputs = 0;
2362 unsigned NumUserInputs = 0;
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002363 StringRef BaseDirectoryAsWritten;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002364 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002365 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002366
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367 switch (Entry.Kind) {
2368 case llvm::BitstreamEntry::Error:
2369 Error("malformed block record in AST file");
2370 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002371 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002372 // Validate the module before returning. This call catches an AST with
2373 // no module name and no imports.
2374 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2375 return Result;
2376
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002377 // Validate input files.
2378 const HeaderSearchOptions &HSOpts =
2379 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002380
Richard Smitha1825302014-10-23 22:18:29 +00002381 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002382 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2383 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002384 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2385 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002387
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002388 // If we are reading a module, we will create a verification timestamp,
2389 // so we verify all input files. Otherwise, verify only user input
2390 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002391
2392 unsigned N = NumUserInputs;
2393 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002394 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002395 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002396 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002397 N = NumInputs;
2398
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002399 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002400 InputFile IF = getInputFile(F, I+1, Complain);
2401 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002403 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002405
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002406 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002407 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002408
Ben Langmuircb69b572014-03-07 06:40:32 +00002409 if (Listener && Listener->needsInputFileVisitation()) {
2410 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2411 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002412 for (unsigned I = 0; I < N; ++I) {
2413 bool IsSystem = I >= NumUserInputs;
2414 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002415 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002416 F.Kind == MK_ExplicitModule ||
2417 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002418 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002419 }
2420
Richard Smith8a308ec2015-11-05 00:54:55 +00002421 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002422 }
2423
Chris Lattnere7b154b2013-01-19 21:39:22 +00002424 case llvm::BitstreamEntry::SubBlock:
2425 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 case INPUT_FILES_BLOCK_ID:
2427 F.InputFilesCursor = Stream;
2428 if (Stream.SkipBlock() || // Skip with the main cursor
2429 // Read the abbreviations
2430 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2431 Error("malformed block record in AST file");
2432 return Failure;
2433 }
2434 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002435
2436 case OPTIONS_BLOCK_ID:
2437 // If we're reading the first module for this group, check its options
2438 // are compatible with ours. For modules it imports, no further checking
2439 // is required, because we checked them when we built it.
2440 if (Listener && !ImportedBy) {
2441 // Should we allow the configuration of the module file to differ from
2442 // the configuration of the current translation unit in a compatible
2443 // way?
2444 //
2445 // FIXME: Allow this for files explicitly specified with -include-pch.
2446 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002447 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002448
Richard Smith8a308ec2015-11-05 00:54:55 +00002449 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2450 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002451 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002452 if (Result == Failure) {
2453 Error("malformed block record in AST file");
2454 return Result;
2455 }
2456
Richard Smith8a308ec2015-11-05 00:54:55 +00002457 if (DisableValidation ||
2458 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2459 Result = Success;
2460
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002461 // If we can't load the module, exit early since we likely
2462 // will rebuild the module anyway. The stream may be in the
2463 // middle of a block.
2464 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002465 return Result;
2466 } else if (Stream.SkipBlock()) {
2467 Error("malformed block record in AST file");
2468 return Failure;
2469 }
2470 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002471
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002473 if (Stream.SkipBlock()) {
2474 Error("malformed block record in AST file");
2475 return Failure;
2476 }
2477 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002478 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002479
Chris Lattnere7b154b2013-01-19 21:39:22 +00002480 case llvm::BitstreamEntry::Record:
2481 // The interesting case.
2482 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 }
2484
2485 // Read and process a record.
2486 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002487 StringRef Blob;
2488 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002489 case METADATA: {
2490 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2491 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002492 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2493 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 return VersionMismatch;
2495 }
2496
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002497 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2499 Diag(diag::err_pch_with_compiler_errors);
2500 return HadErrors;
2501 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002502 if (hasErrors) {
2503 Diags.ErrorOccurred = true;
2504 Diags.UncompilableErrorOccurred = true;
2505 Diags.UnrecoverableErrorOccurred = true;
2506 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002507
2508 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002509 // Relative paths in a relocatable PCH are relative to our sysroot.
2510 if (F.RelocatablePCH)
2511 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002512
Richard Smithe75ee0f2015-08-17 07:13:32 +00002513 F.HasTimestamps = Record[5];
2514
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002515 F.PCHHasObjectFile = Record[6];
2516
Guy Benyei11169dd2012-12-18 14:30:41 +00002517 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002518 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002519 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2520 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002521 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 return VersionMismatch;
2523 }
2524 break;
2525 }
2526
2527 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002528 // Validate the AST before processing any imports (otherwise, untangling
2529 // them can be error-prone and expensive). A module will have a name and
2530 // will already have been validated, but this catches the PCH case.
2531 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2532 return Result;
2533
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002534 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 unsigned Idx = 0, N = Record.size();
2536 while (Idx < N) {
2537 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002538 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 // The import location will be the local one for now; we will adjust
2540 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002541 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002542 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002543 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002544 off_t StoredSize = (off_t)Record[Idx++];
2545 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002546 ASTFileSignature StoredSignature = {
2547 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2548 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2549 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002550
2551 std::string ImportedName = ReadString(Record, Idx);
2552 std::string ImportedFile;
2553
2554 // For prebuilt and explicit modules first consult the file map for
2555 // an override. Note that here we don't search prebuilt module
2556 // directories, only the explicit name to file mappings. Also, we will
2557 // still verify the size/signature making sure it is essentially the
2558 // same file but perhaps in a different location.
2559 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2560 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2561 ImportedName, /*FileMapOnly*/ true);
2562
2563 if (ImportedFile.empty())
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002564 // Use BaseDirectoryAsWritten to ensure we use the same path in the
2565 // ModuleCache as when writing.
2566 ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002567 else
2568 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002569
Richard Smith0f99d6a2015-08-09 08:48:41 +00002570 // If our client can't cope with us being out of date, we can't cope with
2571 // our dependency being missing.
2572 unsigned Capabilities = ClientLoadCapabilities;
2573 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2574 Capabilities &= ~ARR_Missing;
2575
Guy Benyei11169dd2012-12-18 14:30:41 +00002576 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002577 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2578 Loaded, StoredSize, StoredModTime,
2579 StoredSignature, Capabilities);
2580
2581 // If we diagnosed a problem, produce a backtrace.
2582 if (isDiagnosedResult(Result, Capabilities))
2583 Diag(diag::note_module_file_imported_by)
2584 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2585
2586 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 case Failure: return Failure;
2588 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002589 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002590 case OutOfDate: return OutOfDate;
2591 case VersionMismatch: return VersionMismatch;
2592 case ConfigurationMismatch: return ConfigurationMismatch;
2593 case HadErrors: return HadErrors;
2594 case Success: break;
2595 }
2596 }
2597 break;
2598 }
2599
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 case ORIGINAL_FILE:
2601 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002602 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002604 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 break;
2606
2607 case ORIGINAL_FILE_ID:
2608 F.OriginalSourceFileID = FileID::get(Record[0]);
2609 break;
2610
2611 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002612 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 break;
2614
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002615 case MODULE_NAME:
2616 F.ModuleName = Blob;
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00002617 Diag(diag::remark_module_import)
2618 << F.ModuleName << F.FileName << (ImportedBy ? true : false)
2619 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002620 if (Listener)
2621 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002622
2623 // Validate the AST as soon as we have a name so we can exit early on
2624 // failure.
2625 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2626 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002627
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002628 break;
2629
Richard Smith223d3f22014-12-06 03:21:08 +00002630 case MODULE_DIRECTORY: {
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00002631 // Save the BaseDirectory as written in the PCM for computing the module
2632 // filename for the ModuleCache.
2633 BaseDirectoryAsWritten = Blob;
Richard Smith223d3f22014-12-06 03:21:08 +00002634 assert(!F.ModuleName.empty() &&
2635 "MODULE_DIRECTORY found before MODULE_NAME");
2636 // If we've already loaded a module map file covering this module, we may
2637 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002638 Module *M = PP.getHeaderSearchInfo().lookupModule(
2639 F.ModuleName, /*AllowSearch*/ true,
2640 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002641 if (M && M->Directory) {
2642 // If we're implicitly loading a module, the base directory can't
2643 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002644 // Don't emit module relocation error if we have -fno-validate-pch
2645 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2646 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002647 const DirectoryEntry *BuildDir =
2648 PP.getFileManager().getDirectory(Blob);
2649 if (!BuildDir || BuildDir != M->Directory) {
2650 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2651 Diag(diag::err_imported_module_relocated)
2652 << F.ModuleName << Blob << M->Directory->getName();
2653 return OutOfDate;
2654 }
2655 }
2656 F.BaseDirectory = M->Directory->getName();
2657 } else {
2658 F.BaseDirectory = Blob;
2659 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002660 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002661 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002662
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002663 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002664 if (ASTReadResult Result =
2665 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2666 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002667 break;
2668
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002669 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002670 NumInputs = Record[0];
2671 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002672 F.InputFileOffsets =
2673 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002674 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002675 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 break;
2677 }
2678 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002679}
2680
Ben Langmuir2c9af442014-04-10 17:57:43 +00002681ASTReader::ASTReadResult
2682ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002683 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002684
2685 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2686 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002687 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 }
2689
2690 // Read all of the records and blocks for the AST file.
2691 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002692 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002693 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002694
Chris Lattnere7b154b2013-01-19 21:39:22 +00002695 switch (Entry.Kind) {
2696 case llvm::BitstreamEntry::Error:
2697 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002698 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002699 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002700 // Outside of C++, we do not store a lookup map for the translation unit.
2701 // Instead, mark it as needing a lookup map to be built if this module
2702 // contains any declarations lexically within it (which it always does!).
2703 // This usually has no cost, since we very rarely need the lookup map for
2704 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002705 if (ASTContext *Ctx = ContextObj) {
2706 DeclContext *DC = Ctx->getTranslationUnitDecl();
2707 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2708 DC->setMustBuildLookupTable();
2709 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002710
Ben Langmuir2c9af442014-04-10 17:57:43 +00002711 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002712 case llvm::BitstreamEntry::SubBlock:
2713 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 case DECLTYPES_BLOCK_ID:
2715 // We lazily load the decls block, but we want to set up the
2716 // DeclsCursor cursor to point into it. Clone our current bitcode
2717 // cursor to it, enter the block and read the abbrevs in that block.
2718 // With the main cursor, we just skip over it.
2719 F.DeclsCursor = Stream;
2720 if (Stream.SkipBlock() || // Skip with the main cursor.
2721 // Read the abbrevs.
2722 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2723 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002724 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 }
2726 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002727
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 case PREPROCESSOR_BLOCK_ID:
2729 F.MacroCursor = Stream;
2730 if (!PP.getExternalSource())
2731 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002732
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 if (Stream.SkipBlock() ||
2734 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2735 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002736 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 }
2738 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2739 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002740
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 case PREPROCESSOR_DETAIL_BLOCK_ID:
2742 F.PreprocessorDetailCursor = Stream;
2743 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002744 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002746 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002747 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002748 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002750 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002751
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 if (!PP.getPreprocessingRecord())
2753 PP.createPreprocessingRecord();
2754 if (!PP.getPreprocessingRecord()->getExternalSource())
2755 PP.getPreprocessingRecord()->SetExternalSource(*this);
2756 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002757
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 case SOURCE_MANAGER_BLOCK_ID:
2759 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002760 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002761 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002762
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002764 if (ASTReadResult Result =
2765 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002766 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002768
Guy Benyei11169dd2012-12-18 14:30:41 +00002769 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002770 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 if (Stream.SkipBlock() ||
2772 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2773 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002774 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 }
2776 CommentsCursors.push_back(std::make_pair(C, &F));
2777 break;
2778 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002779
Guy Benyei11169dd2012-12-18 14:30:41 +00002780 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002781 if (Stream.SkipBlock()) {
2782 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002783 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002784 }
2785 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 }
2787 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002788
Chris Lattnere7b154b2013-01-19 21:39:22 +00002789 case llvm::BitstreamEntry::Record:
2790 // The interesting case.
2791 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002792 }
2793
2794 // Read and process a record.
2795 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002796 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002797 auto RecordType =
2798 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2799
2800 // If we're not loading an AST context, we don't care about most records.
2801 if (!ContextObj) {
2802 switch (RecordType) {
2803 case IDENTIFIER_TABLE:
2804 case IDENTIFIER_OFFSET:
2805 case INTERESTING_IDENTIFIERS:
2806 case STATISTICS:
2807 case PP_CONDITIONAL_STACK:
2808 case PP_COUNTER_VALUE:
2809 case SOURCE_LOCATION_OFFSETS:
2810 case MODULE_OFFSET_MAP:
2811 case SOURCE_MANAGER_LINE_TABLE:
2812 case SOURCE_LOCATION_PRELOADS:
2813 case PPD_ENTITIES_OFFSETS:
2814 case HEADER_SEARCH_TABLE:
2815 case IMPORTED_MODULES:
2816 case MACRO_OFFSET:
2817 break;
2818 default:
2819 continue;
2820 }
2821 }
2822
2823 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 default: // Default behavior: ignore.
2825 break;
2826
2827 case TYPE_OFFSET: {
2828 if (F.LocalNumTypes != 0) {
2829 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002830 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002832 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 F.LocalNumTypes = Record[0];
2834 unsigned LocalBaseTypeIndex = Record[1];
2835 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002836
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 if (F.LocalNumTypes > 0) {
2838 // Introduce the global -> local mapping for types within this module.
2839 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002840
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 // Introduce the local -> global mapping for types within this module.
2842 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002843 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002844 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002845
2846 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 }
2848 break;
2849 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002850
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 case DECL_OFFSET: {
2852 if (F.LocalNumDecls != 0) {
2853 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002854 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002856 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 F.LocalNumDecls = Record[0];
2858 unsigned LocalBaseDeclID = Record[1];
2859 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002860
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002862 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 // module.
2864 GlobalDeclMap.insert(
2865 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002866
Guy Benyei11169dd2012-12-18 14:30:41 +00002867 // Introduce the local -> global mapping for declarations within this
2868 // module.
2869 F.DeclRemap.insertOrReplace(
2870 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002871
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 // Introduce the global -> local mapping for declarations within this
2873 // module.
2874 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002875
Ben Langmuir52ca6782014-10-20 16:27:32 +00002876 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2877 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002878 break;
2879 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002880
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002882 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002883 LexicalContents Contents(
2884 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2885 Blob.data()),
2886 static_cast<unsigned int>(Blob.size() / 4));
2887 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 TU->setHasExternalLexicalStorage(true);
2889 break;
2890 }
2891
2892 case UPDATE_VISIBLE: {
2893 unsigned Idx = 0;
2894 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002895 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002896 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002897 // If we've already loaded the decl, perform the updates when we finish
2898 // loading this block.
2899 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002900 PendingUpdateRecords.push_back(
2901 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 break;
2903 }
2904
2905 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002906 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002908 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2909 (const unsigned char *)F.IdentifierTableData + Record[0],
2910 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2911 (const unsigned char *)F.IdentifierTableData,
2912 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002913
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2915 }
2916 break;
2917
2918 case IDENTIFIER_OFFSET: {
2919 if (F.LocalNumIdentifiers != 0) {
2920 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002921 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002923 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 F.LocalNumIdentifiers = Record[0];
2925 unsigned LocalBaseIdentifierID = Record[1];
2926 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002927
Guy Benyei11169dd2012-12-18 14:30:41 +00002928 if (F.LocalNumIdentifiers > 0) {
2929 // Introduce the global -> local mapping for identifiers within this
2930 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002931 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002933
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 // Introduce the local -> global mapping for identifiers within this
2935 // module.
2936 F.IdentifierRemap.insertOrReplace(
2937 std::make_pair(LocalBaseIdentifierID,
2938 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002939
Ben Langmuir52ca6782014-10-20 16:27:32 +00002940 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2941 + F.LocalNumIdentifiers);
2942 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002943 break;
2944 }
2945
Richard Smith33e0f7e2015-07-22 02:08:40 +00002946 case INTERESTING_IDENTIFIERS:
2947 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2948 break;
2949
Ben Langmuir332aafe2014-01-31 01:06:56 +00002950 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002951 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2952 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002953 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002954 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002955 break;
2956
David Blaikie9ffe5a32017-01-30 05:00:26 +00002957 case MODULAR_CODEGEN_DECLS:
2958 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2959 // them (ie: if we're not codegenerating this module).
2960 if (F.Kind == MK_MainFile)
2961 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2962 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2963 break;
2964
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002966 if (SpecialTypes.empty()) {
2967 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2968 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2969 break;
2970 }
2971
2972 if (SpecialTypes.size() != Record.size()) {
2973 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002974 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002975 }
2976
2977 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2978 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2979 if (!SpecialTypes[I])
2980 SpecialTypes[I] = ID;
2981 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2982 // merge step?
2983 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 break;
2985
2986 case STATISTICS:
2987 TotalNumStatements += Record[0];
2988 TotalNumMacros += Record[1];
2989 TotalLexicalDeclContexts += Record[2];
2990 TotalVisibleDeclContexts += Record[3];
2991 break;
2992
2993 case UNUSED_FILESCOPED_DECLS:
2994 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2995 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2996 break;
2997
2998 case DELEGATING_CTORS:
2999 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3000 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
3001 break;
3002
3003 case WEAK_UNDECLARED_IDENTIFIERS:
3004 if (Record.size() % 4 != 0) {
3005 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003006 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003008
3009 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 // files. This isn't the way to do it :)
3011 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003012
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 // Translate the weak, undeclared identifiers into global IDs.
3014 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3015 WeakUndeclaredIdentifiers.push_back(
3016 getGlobalIdentifierID(F, Record[I++]));
3017 WeakUndeclaredIdentifiers.push_back(
3018 getGlobalIdentifierID(F, Record[I++]));
3019 WeakUndeclaredIdentifiers.push_back(
3020 ReadSourceLocation(F, Record, I).getRawEncoding());
3021 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3022 }
3023 break;
3024
Guy Benyei11169dd2012-12-18 14:30:41 +00003025 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003026 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 F.LocalNumSelectors = Record[0];
3028 unsigned LocalBaseSelectorID = Record[1];
3029 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003030
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003032 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 // module.
3034 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003035
3036 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003037 // module.
3038 F.SelectorRemap.insertOrReplace(
3039 std::make_pair(LocalBaseSelectorID,
3040 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003041
3042 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 }
3044 break;
3045 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003046
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003048 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 if (Record[0])
3050 F.SelectorLookupTable
3051 = ASTSelectorLookupTable::Create(
3052 F.SelectorLookupTableData + Record[0],
3053 F.SelectorLookupTableData,
3054 ASTSelectorLookupTrait(*this, F));
3055 TotalNumMethodPoolEntries += Record[1];
3056 break;
3057
3058 case REFERENCED_SELECTOR_POOL:
3059 if (!Record.empty()) {
3060 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003061 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 Record[Idx++]));
3063 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3064 getRawEncoding());
3065 }
3066 }
3067 break;
3068
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003069 case PP_CONDITIONAL_STACK:
3070 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003071 unsigned Idx = 0, End = Record.size() - 1;
3072 bool ReachedEOFWhileSkipping = Record[Idx++];
3073 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3074 if (ReachedEOFWhileSkipping) {
3075 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3076 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3077 bool FoundNonSkipPortion = Record[Idx++];
3078 bool FoundElse = Record[Idx++];
3079 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3080 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3081 FoundElse, ElseLoc);
3082 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003083 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003084 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003085 auto Loc = ReadSourceLocation(F, Record, Idx);
3086 bool WasSkipping = Record[Idx++];
3087 bool FoundNonSkip = Record[Idx++];
3088 bool FoundElse = Record[Idx++];
3089 ConditionalStack.push_back(
3090 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3091 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003092 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003093 }
3094 break;
3095
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 case PP_COUNTER_VALUE:
3097 if (!Record.empty() && Listener)
3098 Listener->ReadCounter(F, Record[0]);
3099 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003102 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 F.NumFileSortedDecls = Record[0];
3104 break;
3105
3106 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003107 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 F.LocalNumSLocEntries = Record[0];
3109 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003110 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003111 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003113 if (!F.SLocEntryBaseID) {
3114 Error("ran out of source locations");
3115 break;
3116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 // Make our entry in the range map. BaseID is negative and growing, so
3118 // we invert it. Because we invert it, though, we need the other end of
3119 // the range.
3120 unsigned RangeStart =
3121 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3122 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3123 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3124
3125 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3126 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3127 GlobalSLocOffsetMap.insert(
3128 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3129 - SLocSpaceSize,&F));
3130
3131 // Initialize the remapping table.
3132 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003133 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003135 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003137
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 TotalNumSLocEntries += F.LocalNumSLocEntries;
3139 break;
3140 }
3141
Richard Smith37a93df2017-02-18 00:32:02 +00003142 case MODULE_OFFSET_MAP:
3143 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003145
3146 case SOURCE_MANAGER_LINE_TABLE:
3147 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003148 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 break;
3150
3151 case SOURCE_LOCATION_PRELOADS: {
3152 // Need to transform from the local view (1-based IDs) to the global view,
3153 // which is based off F.SLocEntryBaseID.
3154 if (!F.PreloadSLocEntries.empty()) {
3155 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003156 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003157 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159 F.PreloadSLocEntries.swap(Record);
3160 break;
3161 }
3162
3163 case EXT_VECTOR_DECLS:
3164 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3165 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3166 break;
3167
3168 case VTABLE_USES:
3169 if (Record.size() % 3 != 0) {
3170 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003171 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003172 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003173
Guy Benyei11169dd2012-12-18 14:30:41 +00003174 // Later tables overwrite earlier ones.
3175 // FIXME: Modules will have some trouble with this. This is clearly not
3176 // the right way to do this.
3177 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003178
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3180 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3181 VTableUses.push_back(
3182 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3183 VTableUses.push_back(Record[Idx++]);
3184 }
3185 break;
3186
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 case PENDING_IMPLICIT_INSTANTIATIONS:
3188 if (PendingInstantiations.size() % 2 != 0) {
3189 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003190 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003191 }
3192
3193 if (Record.size() % 2 != 0) {
3194 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003195 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 }
3197
3198 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3199 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3200 PendingInstantiations.push_back(
3201 ReadSourceLocation(F, Record, I).getRawEncoding());
3202 }
3203 break;
3204
3205 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003206 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003207 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003208 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003209 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3211 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3212 break;
3213
3214 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003215 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3216 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3217 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003218
3219 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003220
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 unsigned StartingID;
3222 if (!PP.getPreprocessingRecord())
3223 PP.createPreprocessingRecord();
3224 if (!PP.getPreprocessingRecord()->getExternalSource())
3225 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003226 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003228 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 F.BasePreprocessedEntityID = StartingID;
3230
3231 if (F.NumPreprocessedEntities > 0) {
3232 // Introduce the global -> local mapping for preprocessed entities in
3233 // this module.
3234 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003235
Guy Benyei11169dd2012-12-18 14:30:41 +00003236 // Introduce the local -> global mapping for preprocessed entities in
3237 // this module.
3238 F.PreprocessedEntityRemap.insertOrReplace(
3239 std::make_pair(LocalBasePreprocessedEntityID,
3240 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3241 }
3242
3243 break;
3244 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003245
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003246 case PPD_SKIPPED_RANGES: {
3247 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3248 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3249 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3250
3251 if (!PP.getPreprocessingRecord())
3252 PP.createPreprocessingRecord();
3253 if (!PP.getPreprocessingRecord()->getExternalSource())
3254 PP.getPreprocessingRecord()->SetExternalSource(*this);
3255 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3256 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003257
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003258 if (F.NumPreprocessedSkippedRanges > 0)
3259 GlobalSkippedRangeMap.insert(
3260 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3261 break;
3262 }
3263
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003264 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 if (Record.size() % 2 != 0) {
3266 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003267 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003269 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3270 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3271 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3272
3273 // If we've already loaded the decl, perform the updates when we finish
3274 // loading this block.
3275 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003276 PendingUpdateRecords.push_back(
3277 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003278 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003280
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003281 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 if (F.LocalNumObjCCategoriesInMap != 0) {
3283 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003284 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003288 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003290
Guy Benyei11169dd2012-12-18 14:30:41 +00003291 case OBJC_CATEGORIES:
3292 F.ObjCCategories.swap(Record);
3293 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 case CUDA_SPECIAL_DECL_REFS:
3296 // Later tables overwrite earlier ones.
3297 // FIXME: Modules will have trouble with this.
3298 CUDASpecialDeclRefs.clear();
3299 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3300 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3301 break;
3302
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003303 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003304 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003305 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 if (Record[0]) {
3307 F.HeaderFileInfoTable
3308 = HeaderFileInfoLookupTable::Create(
3309 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3310 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003311 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003313 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003314
Guy Benyei11169dd2012-12-18 14:30:41 +00003315 PP.getHeaderSearchInfo().SetExternalSource(this);
3316 if (!PP.getHeaderSearchInfo().getExternalLookup())
3317 PP.getHeaderSearchInfo().SetExternalLookup(this);
3318 }
3319 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003320
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 case FP_PRAGMA_OPTIONS:
3322 // Later tables overwrite earlier ones.
3323 FPPragmaOptions.swap(Record);
3324 break;
3325
3326 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003327 for (unsigned I = 0, E = Record.size(); I != E; ) {
3328 auto Name = ReadString(Record, I);
3329 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003330 Opt.Supported = Record[I++] != 0;
3331 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003332 Opt.Avail = Record[I++];
3333 Opt.Core = Record[I++];
3334 }
3335 break;
3336
3337 case OPENCL_EXTENSION_TYPES:
3338 for (unsigned I = 0, E = Record.size(); I != E;) {
3339 auto TypeID = static_cast<::TypeID>(Record[I++]);
3340 auto *Type = GetType(TypeID).getTypePtr();
3341 auto NumExt = static_cast<unsigned>(Record[I++]);
3342 for (unsigned II = 0; II != NumExt; ++II) {
3343 auto Ext = ReadString(Record, I);
3344 OpenCLTypeExtMap[Type].insert(Ext);
3345 }
3346 }
3347 break;
3348
3349 case OPENCL_EXTENSION_DECLS:
3350 for (unsigned I = 0, E = Record.size(); I != E;) {
3351 auto DeclID = static_cast<::DeclID>(Record[I++]);
3352 auto *Decl = GetDecl(DeclID);
3353 auto NumExt = static_cast<unsigned>(Record[I++]);
3354 for (unsigned II = 0; II != NumExt; ++II) {
3355 auto Ext = ReadString(Record, I);
3356 OpenCLDeclExtMap[Decl].insert(Ext);
3357 }
3358 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003359 break;
3360
3361 case TENTATIVE_DEFINITIONS:
3362 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3363 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3364 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003365
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 case KNOWN_NAMESPACES:
3367 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3368 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3369 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003370
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003371 case UNDEFINED_BUT_USED:
3372 if (UndefinedButUsed.size() % 2 != 0) {
3373 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003374 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003375 }
3376
3377 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003378 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003379 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003380 }
3381 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003382 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3383 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003384 ReadSourceLocation(F, Record, I).getRawEncoding());
3385 }
3386 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003387
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003388 case DELETE_EXPRS_TO_ANALYZE:
3389 for (unsigned I = 0, N = Record.size(); I != N;) {
3390 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3391 const uint64_t Count = Record[I++];
3392 DelayedDeleteExprs.push_back(Count);
3393 for (uint64_t C = 0; C < Count; ++C) {
3394 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3395 bool IsArrayForm = Record[I++] == 1;
3396 DelayedDeleteExprs.push_back(IsArrayForm);
3397 }
3398 }
3399 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003400
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003401 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003402 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003403 // If we aren't loading a module (which has its own exports), make
3404 // all of the imported modules visible.
3405 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003406 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3407 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3408 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003409 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003410 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003411 if (DeserializationListener)
3412 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3413 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003414 }
3415 }
3416 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
Guy Benyei11169dd2012-12-18 14:30:41 +00003418 case MACRO_OFFSET: {
3419 if (F.LocalNumMacros != 0) {
3420 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003421 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003422 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003423 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003424 F.LocalNumMacros = Record[0];
3425 unsigned LocalBaseMacroID = Record[1];
3426 F.BaseMacroID = getTotalNumMacros();
3427
3428 if (F.LocalNumMacros > 0) {
3429 // Introduce the global -> local mapping for macros within this module.
3430 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3431
3432 // Introduce the local -> global mapping for macros within this module.
3433 F.MacroRemap.insertOrReplace(
3434 std::make_pair(LocalBaseMacroID,
3435 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003436
3437 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003438 }
3439 break;
3440 }
3441
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003442 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003443 LateParsedTemplates.append(Record.begin(), Record.end());
3444 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003445
3446 case OPTIMIZE_PRAGMA_OPTIONS:
3447 if (Record.size() != 1) {
3448 Error("invalid pragma optimize record");
3449 return Failure;
3450 }
3451 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3452 break;
Nico Weber72889432014-09-06 01:25:55 +00003453
Nico Weber779355f2016-03-02 23:22:00 +00003454 case MSSTRUCT_PRAGMA_OPTIONS:
3455 if (Record.size() != 1) {
3456 Error("invalid pragma ms_struct record");
3457 return Failure;
3458 }
3459 PragmaMSStructState = Record[0];
3460 break;
3461
Nico Weber42932312016-03-03 00:17:35 +00003462 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3463 if (Record.size() != 2) {
3464 Error("invalid pragma ms_struct record");
3465 return Failure;
3466 }
3467 PragmaMSPointersToMembersState = Record[0];
3468 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3469 break;
3470
Nico Weber72889432014-09-06 01:25:55 +00003471 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3472 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3473 UnusedLocalTypedefNameCandidates.push_back(
3474 getGlobalDeclID(F, Record[I]));
3475 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003476
3477 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3478 if (Record.size() != 1) {
3479 Error("invalid cuda pragma options record");
3480 return Failure;
3481 }
3482 ForceCUDAHostDeviceDepth = Record[0];
3483 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003484
3485 case PACK_PRAGMA_OPTIONS: {
3486 if (Record.size() < 3) {
3487 Error("invalid pragma pack record");
3488 return Failure;
3489 }
3490 PragmaPackCurrentValue = Record[0];
3491 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3492 unsigned NumStackEntries = Record[2];
3493 unsigned Idx = 3;
3494 // Reset the stack when importing a new module.
3495 PragmaPackStack.clear();
3496 for (unsigned I = 0; I < NumStackEntries; ++I) {
3497 PragmaPackStackEntry Entry;
3498 Entry.Value = Record[Idx++];
3499 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003500 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003501 PragmaPackStrings.push_back(ReadString(Record, Idx));
3502 Entry.SlotLabel = PragmaPackStrings.back();
3503 PragmaPackStack.push_back(Entry);
3504 }
3505 break;
3506 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003507 }
3508 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003509}
3510
Richard Smith37a93df2017-02-18 00:32:02 +00003511void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3512 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3513
3514 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003515 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003516 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3517 F.ModuleOffsetMap = StringRef();
3518
3519 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3520 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3521 F.SLocRemap.insert(std::make_pair(0U, 0));
3522 F.SLocRemap.insert(std::make_pair(2U, 1));
3523 }
3524
3525 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003526 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003527 RemapBuilder SLocRemap(F.SLocRemap);
3528 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3529 RemapBuilder MacroRemap(F.MacroRemap);
3530 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3531 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3532 RemapBuilder SelectorRemap(F.SelectorRemap);
3533 RemapBuilder DeclRemap(F.DeclRemap);
3534 RemapBuilder TypeRemap(F.TypeRemap);
3535
3536 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003537 // FIXME: Looking up dependency modules by filename is horrible. Let's
3538 // start fixing this with prebuilt and explicit modules and see how it
3539 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003540 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003541 ModuleKind Kind = static_cast<ModuleKind>(
3542 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003543 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3544 StringRef Name = StringRef((const char*)Data, Len);
3545 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003546 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3547 ? ModuleMgr.lookupByModuleName(Name)
3548 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003549 if (!OM) {
3550 std::string Msg =
3551 "SourceLocation remap refers to unknown module, cannot find ";
3552 Msg.append(Name);
3553 Error(Msg);
3554 return;
3555 }
3556
3557 uint32_t SLocOffset =
3558 endian::readNext<uint32_t, little, unaligned>(Data);
3559 uint32_t IdentifierIDOffset =
3560 endian::readNext<uint32_t, little, unaligned>(Data);
3561 uint32_t MacroIDOffset =
3562 endian::readNext<uint32_t, little, unaligned>(Data);
3563 uint32_t PreprocessedEntityIDOffset =
3564 endian::readNext<uint32_t, little, unaligned>(Data);
3565 uint32_t SubmoduleIDOffset =
3566 endian::readNext<uint32_t, little, unaligned>(Data);
3567 uint32_t SelectorIDOffset =
3568 endian::readNext<uint32_t, little, unaligned>(Data);
3569 uint32_t DeclIDOffset =
3570 endian::readNext<uint32_t, little, unaligned>(Data);
3571 uint32_t TypeIndexOffset =
3572 endian::readNext<uint32_t, little, unaligned>(Data);
3573
3574 uint32_t None = std::numeric_limits<uint32_t>::max();
3575
3576 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3577 RemapBuilder &Remap) {
3578 if (Offset != None)
3579 Remap.insert(std::make_pair(Offset,
3580 static_cast<int>(BaseOffset - Offset)));
3581 };
3582 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3583 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3584 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3585 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3586 PreprocessedEntityRemap);
3587 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3588 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3589 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3590 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3591
3592 // Global -> local mappings.
3593 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3594 }
3595}
3596
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003597ASTReader::ASTReadResult
3598ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3599 const ModuleFile *ImportedBy,
3600 unsigned ClientLoadCapabilities) {
3601 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003602 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003603
3604 // Try to resolve ModuleName in the current header search context and
3605 // verify that it is found in the same module map file as we saved. If the
3606 // top-level AST file is a main file, skip this check because there is no
3607 // usable header search context.
3608 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003609 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003610 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003611 // An implicitly-loaded module file should have its module listed in some
3612 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003613 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003614 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3615 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003616 // Don't emit module relocation error if we have -fno-validate-pch
3617 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003618 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003619 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003620 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003621 // This module was defined by an imported (explicit) module.
3622 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3623 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003624 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003625 // This module was built with a different module map.
3626 Diag(diag::err_imported_module_not_found)
3627 << F.ModuleName << F.FileName << ImportedBy->FileName
3628 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003629 // In case it was imported by a PCH, there's a chance the user is
3630 // just missing to include the search path to the directory containing
3631 // the modulemap.
3632 if (ImportedBy->Kind == MK_PCH)
3633 Diag(diag::note_imported_by_pch_module_not_found)
3634 << llvm::sys::path::parent_path(F.ModuleMapPath);
3635 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003636 }
3637 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003638 }
3639
Richard Smithe842a472014-10-22 02:05:46 +00003640 assert(M->Name == F.ModuleName && "found module with different name");
3641
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003642 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003643 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003644 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3645 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003646 assert(ImportedBy && "top-level import should be verified");
3647 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3648 Diag(diag::err_imported_module_modmap_changed)
3649 << F.ModuleName << ImportedBy->FileName
3650 << ModMap->getName() << F.ModuleMapPath;
3651 return OutOfDate;
3652 }
3653
3654 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3655 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3656 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003657 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003658 const FileEntry *F =
3659 FileMgr.getFile(Filename, false, false);
3660 if (F == nullptr) {
3661 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3662 Error("could not find file '" + Filename +"' referenced by AST file");
3663 return OutOfDate;
3664 }
3665 AdditionalStoredMaps.insert(F);
3666 }
3667
3668 // Check any additional module map files (e.g. module.private.modulemap)
3669 // that are not in the pcm.
3670 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003671 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003672 // Remove files that match
3673 // Note: SmallPtrSet::erase is really remove
3674 if (!AdditionalStoredMaps.erase(ModMap)) {
3675 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3676 Diag(diag::err_module_different_modmap)
3677 << F.ModuleName << /*new*/0 << ModMap->getName();
3678 return OutOfDate;
3679 }
3680 }
3681 }
3682
3683 // Check any additional module map files that are in the pcm, but not
3684 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003685 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003686 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3687 Diag(diag::err_module_different_modmap)
3688 << F.ModuleName << /*not new*/1 << ModMap->getName();
3689 return OutOfDate;
3690 }
3691 }
3692
3693 if (Listener)
3694 Listener->ReadModuleMapFile(F.ModuleMapPath);
3695 return Success;
3696}
3697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003698/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003699static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3700 // Find the entry for this selector in the method pool.
3701 Sema::GlobalMethodPool::iterator Known
3702 = S.MethodPool.find(Method->getSelector());
3703 if (Known == S.MethodPool.end())
3704 return;
3705
3706 // Retrieve the appropriate method list.
3707 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3708 : Known->second.second;
3709 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003710 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003711 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003712 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003713 Found = true;
3714 } else {
3715 // Keep searching.
3716 continue;
3717 }
3718 }
3719
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003720 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003721 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003722 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003723 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003724 }
3725}
3726
Richard Smithde711422015-04-23 21:20:19 +00003727void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003728 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003729 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003730 bool wasHidden = D->isHidden();
3731 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003732
Vedant Kumar48b4f762018-04-14 01:40:48 +00003733 if (wasHidden && SemaObj) {
3734 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003735 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003736 }
3737 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003738 }
3739}
3740
Richard Smith49f906a2014-03-01 00:08:04 +00003741void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003742 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003743 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003745 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003746 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003748 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003749
3750 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003751 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003752 // there is nothing more to do.
3753 continue;
3754 }
Richard Smith49f906a2014-03-01 00:08:04 +00003755
Guy Benyei11169dd2012-12-18 14:30:41 +00003756 if (!Mod->isAvailable()) {
3757 // Modules that aren't available cannot be made visible.
3758 continue;
3759 }
3760
3761 // Update the module's name visibility.
3762 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003763
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 // If we've already deserialized any names from this module,
3765 // mark them as visible.
3766 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3767 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003768 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003770 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003771 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3772 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003774
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003776 SmallVector<Module *, 16> Exports;
3777 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003778 for (SmallVectorImpl<Module *>::iterator
3779 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3780 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003781 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003782 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003783 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 }
3785}
3786
Richard Smith6561f922016-09-12 21:06:40 +00003787/// We've merged the definition \p MergedDef into the existing definition
3788/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3789/// visible.
3790void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3791 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00003792 if (Def->isHidden()) {
3793 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003794 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003795 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00003796 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003797 getContext().mergeDefinitionIntoModule(
3798 Def, MergedDef->getImportedOwningModule(),
3799 /*NotifyListeners*/ false);
3800 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003801 }
Richard Smith6561f922016-09-12 21:06:40 +00003802 }
3803}
3804
Douglas Gregore060e572013-01-25 01:03:03 +00003805bool ASTReader::loadGlobalIndex() {
3806 if (GlobalIndex)
3807 return false;
3808
3809 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003810 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003811 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003812
Douglas Gregore060e572013-01-25 01:03:03 +00003813 // Try to load the global index.
3814 TriedLoadingGlobalIndex = true;
3815 StringRef ModuleCachePath
3816 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3817 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003818 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003819 if (!Result.first)
3820 return true;
3821
3822 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003823 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003824 return false;
3825}
3826
3827bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003828 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003829 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3830}
3831
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003832static void updateModuleTimestamp(ModuleFile &MF) {
3833 // Overwrite the timestamp file contents so that file's mtime changes.
3834 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003835 std::error_code EC;
3836 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3837 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003838 return;
3839 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003840 OS.close();
3841 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003842}
3843
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003844/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003845/// cursor into the start of the given block ID, returning false on success and
3846/// true on failure.
3847static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003848 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003849 llvm::BitstreamEntry Entry = Cursor.advance();
3850 switch (Entry.Kind) {
3851 case llvm::BitstreamEntry::Error:
3852 case llvm::BitstreamEntry::EndBlock:
3853 return true;
3854
3855 case llvm::BitstreamEntry::Record:
3856 // Ignore top-level records.
3857 Cursor.skipRecord(Entry.ID);
3858 break;
3859
3860 case llvm::BitstreamEntry::SubBlock:
3861 if (Entry.ID == BlockID) {
3862 if (Cursor.EnterSubBlock(BlockID))
3863 return true;
3864 // Found it!
3865 return false;
3866 }
3867
3868 if (Cursor.SkipBlock())
3869 return true;
3870 }
3871 }
3872}
3873
Benjamin Kramer0772c422016-02-13 13:42:54 +00003874ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003875 ModuleKind Type,
3876 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003877 unsigned ClientLoadCapabilities,
3878 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003879 llvm::SaveAndRestore<SourceLocation>
3880 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3881
Richard Smithd1c46742014-04-30 02:24:17 +00003882 // Defer any pending actions until we get to the end of reading the AST file.
3883 Deserializing AnASTFile(this);
3884
Guy Benyei11169dd2012-12-18 14:30:41 +00003885 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003886 unsigned PreviousGeneration = 0;
3887 if (ContextObj)
3888 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003889
3890 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003891 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003892 switch (ASTReadResult ReadResult =
3893 ReadASTCore(FileName, Type, ImportLoc,
3894 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3895 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003896 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003897 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003898 case OutOfDate:
3899 case VersionMismatch:
3900 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003901 case HadErrors: {
3902 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003903 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00003904 LoadedSet.insert(IM.Mod);
3905
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003906 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003907 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003908 ? &PP.getHeaderSearchInfo().getModuleMap()
3909 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003910
3911 // If we find that any modules are unusable, the global index is going
3912 // to be out-of-date. Just remove it.
3913 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003914 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003915 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003916 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003917 case Success:
3918 break;
3919 }
3920
3921 // Here comes stuff that we only do once the entire chain is loaded.
3922
3923 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003924 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3925 MEnd = Loaded.end();
3926 M != MEnd; ++M) {
3927 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00003928
3929 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003930 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3931 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003932
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003933 // Read the extension blocks.
3934 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3935 if (ASTReadResult Result = ReadExtensionBlock(F))
3936 return Result;
3937 }
3938
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003939 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003940 // bits of all files we've seen.
3941 F.GlobalBitOffset = TotalModulesSizeInBits;
3942 TotalModulesSizeInBits += F.SizeInBits;
3943 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003944
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003946 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3947 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00003948 // Load it through the SourceManager and don't call ReadSLocEntry()
3949 // directly because the entry may have already been loaded in which case
3950 // calling ReadSLocEntry() directly would trigger an assertion in
3951 // SourceManager.
3952 SourceMgr.getLoadedSLocEntryByID(Index);
3953 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003954
Richard Smithea741482017-05-01 22:10:47 +00003955 // Map the original source file ID into the ID space of the current
3956 // compilation.
3957 if (F.OriginalSourceFileID.isValid()) {
3958 F.OriginalSourceFileID = FileID::get(
3959 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3960 }
3961
Richard Smith33e0f7e2015-07-22 02:08:40 +00003962 // Preload all the pending interesting identifiers by marking them out of
3963 // date.
3964 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003965 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00003966 F.IdentifierTableData + Offset);
3967
3968 ASTIdentifierLookupTrait Trait(*this, F);
3969 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3970 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003971 auto &II = PP.getIdentifierTable().getOwn(Key);
3972 II.setOutOfDate(true);
3973
3974 // Mark this identifier as being from an AST file so that we can track
3975 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003976 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003977
3978 // Associate the ID with the identifier so that the writer can reuse it.
3979 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3980 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003981 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003982 }
3983
Douglas Gregor603cd862013-03-22 18:50:14 +00003984 // Setup the import locations and notify the module manager that we've
3985 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003986 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3987 MEnd = Loaded.end();
3988 M != MEnd; ++M) {
3989 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003990
3991 ModuleMgr.moduleFileAccepted(&F);
3992
3993 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003994 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003995 // FIXME: We assume that locations from PCH / preamble do not need
3996 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003997 if (!M->ImportedBy)
3998 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00004000 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00004001 }
4002
Richard Smithdbafb6c2017-06-29 23:23:46 +00004003 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00004004 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
4005 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00004006 // Mark all of the identifiers in the identifier table as being out of date,
4007 // so that various accessors know to check the loaded modules when the
4008 // identifier is used.
4009 //
4010 // For C++ modules, we don't need information on many identifiers (just
4011 // those that provide macros or are poisoned), so we mark all of
4012 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004013 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4014 IdEnd = PP.getIdentifierTable().end();
4015 Id != IdEnd; ++Id)
4016 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004017 }
Manman Rena0f31a02016-04-29 19:04:05 +00004018 // Mark selectors as out of date.
4019 for (auto Sel : SelectorGeneration)
4020 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004021
Guy Benyei11169dd2012-12-18 14:30:41 +00004022 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004023 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4024 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004025 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4026 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004027
4028 switch (Unresolved.Kind) {
4029 case UnresolvedModuleRef::Conflict:
4030 if (ResolvedMod) {
4031 Module::Conflict Conflict;
4032 Conflict.Other = ResolvedMod;
4033 Conflict.Message = Unresolved.String.str();
4034 Unresolved.Mod->Conflicts.push_back(Conflict);
4035 }
4036 continue;
4037
4038 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004039 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004040 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004041 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004042
Douglas Gregorfb912652013-03-20 21:10:35 +00004043 case UnresolvedModuleRef::Export:
4044 if (ResolvedMod || Unresolved.IsWildcard)
4045 Unresolved.Mod->Exports.push_back(
4046 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4047 continue;
4048 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004049 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004050 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004051
Graydon Hoaree7196af2016-12-09 21:45:49 +00004052 if (Imported)
4053 Imported->append(ImportedModules.begin(),
4054 ImportedModules.end());
4055
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004056 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4057 // Might be unnecessary as use declarations are only used to build the
4058 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004059
Richard Smithdbafb6c2017-06-29 23:23:46 +00004060 if (ContextObj)
4061 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004062
Richard Smith3d8e97e2013-10-18 06:54:39 +00004063 if (SemaObj)
4064 UpdateSema();
4065
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 if (DeserializationListener)
4067 DeserializationListener->ReaderInitialized(this);
4068
4069 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004070 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004071 // If this AST file is a precompiled preamble, then set the
4072 // preamble file ID of the source manager to the file source file
4073 // from which the preamble was built.
4074 if (Type == MK_Preamble) {
4075 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4076 } else if (Type == MK_MainFile) {
4077 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4078 }
4079 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004080
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 // For any Objective-C class definitions we have already loaded, make sure
4082 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004083 if (ContextObj) {
4084 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4085 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4086 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004087 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004088 }
4089 }
Douglas Gregore060e572013-01-25 01:03:03 +00004090
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004091 if (PP.getHeaderSearchInfo()
4092 .getHeaderSearchOpts()
4093 .ModulesValidateOncePerBuildSession) {
4094 // Now we are certain that the module and all modules it depends on are
4095 // up to date. Create or update timestamp files for modules that are
4096 // located in the module cache (not for PCH files that could be anywhere
4097 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004098 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4099 ImportedModule &M = Loaded[I];
4100 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004101 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004102 }
4103 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004104 }
4105
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 return Success;
4107}
4108
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004109static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004110
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004111/// Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004112static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004113 return Stream.canSkipToPos(4) &&
4114 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004115 Stream.Read(8) == 'P' &&
4116 Stream.Read(8) == 'C' &&
4117 Stream.Read(8) == 'H';
4118}
4119
Richard Smith0f99d6a2015-08-09 08:48:41 +00004120static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4121 switch (Kind) {
4122 case MK_PCH:
4123 return 0; // PCH
4124 case MK_ImplicitModule:
4125 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004126 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004127 return 1; // module
4128 case MK_MainFile:
4129 case MK_Preamble:
4130 return 2; // main source file
4131 }
4132 llvm_unreachable("unknown module kind");
4133}
4134
Guy Benyei11169dd2012-12-18 14:30:41 +00004135ASTReader::ASTReadResult
4136ASTReader::ReadASTCore(StringRef FileName,
4137 ModuleKind Type,
4138 SourceLocation ImportLoc,
4139 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004140 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004141 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004142 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004143 unsigned ClientLoadCapabilities) {
4144 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004146 ModuleManager::AddModuleResult AddResult
4147 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004148 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004149 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004150 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004151
Douglas Gregor7029ce12013-03-19 00:28:20 +00004152 switch (AddResult) {
4153 case ModuleManager::AlreadyLoaded:
Duncan P. N. Exon Smith9dda8f52019-03-06 02:50:46 +00004154 Diag(diag::remark_module_import)
4155 << M->ModuleName << M->FileName << (ImportedBy ? true : false)
4156 << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
Douglas Gregor7029ce12013-03-19 00:28:20 +00004157 return Success;
4158
4159 case ModuleManager::NewlyLoaded:
4160 // Load module file below.
4161 break;
4162
4163 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004164 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004165 // it.
4166 if (ClientLoadCapabilities & ARR_Missing)
4167 return Missing;
4168
4169 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004170 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004171 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004172 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004173 return Failure;
4174
4175 case ModuleManager::OutOfDate:
4176 // We couldn't load the module file because it is out-of-date. If the
4177 // client can handle out-of-date, return it.
4178 if (ClientLoadCapabilities & ARR_OutOfDate)
4179 return OutOfDate;
4180
4181 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004182 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004183 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004184 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004185 return Failure;
4186 }
4187
Douglas Gregor7029ce12013-03-19 00:28:20 +00004188 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004189
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004190 bool ShouldFinalizePCM = false;
4191 auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
4192 auto &MC = getModuleManager().getModuleCache();
4193 if (ShouldFinalizePCM)
4194 MC.finalizePCM(FileName);
4195 else
4196 MC.tryToDropPCM(FileName);
4197 });
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004199 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004200 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004201 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004202
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004204 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004205 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4206 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 return Failure;
4208 }
4209
4210 // This is used for compatibility with older PCH formats.
4211 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004212 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004213 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004214
Chris Lattnerefa77172013-01-20 00:00:22 +00004215 switch (Entry.Kind) {
4216 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004217 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004218 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 Error("invalid record at top-level of AST file");
4220 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004221
Chris Lattnerefa77172013-01-20 00:00:22 +00004222 case llvm::BitstreamEntry::SubBlock:
4223 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 }
4225
Chris Lattnerefa77172013-01-20 00:00:22 +00004226 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004227 case CONTROL_BLOCK_ID:
4228 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004229 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004231 // Check that we didn't try to load a non-module AST file as a module.
4232 //
4233 // FIXME: Should we also perform the converse check? Loading a module as
4234 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004235 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4236 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004237 F.ModuleName.empty()) {
4238 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4239 if (Result != OutOfDate ||
4240 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4241 Diag(diag::err_module_file_not_module) << FileName;
4242 return Result;
4243 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004244 break;
4245
4246 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004247 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004248 case OutOfDate: return OutOfDate;
4249 case VersionMismatch: return VersionMismatch;
4250 case ConfigurationMismatch: return ConfigurationMismatch;
4251 case HadErrors: return HadErrors;
4252 }
4253 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004254
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 case AST_BLOCK_ID:
4256 if (!HaveReadControlBlock) {
4257 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004258 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004259 return VersionMismatch;
4260 }
4261
4262 // Record that we've loaded this module.
4263 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004264 ShouldFinalizePCM = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 return Success;
4266
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004267 case UNHASHED_CONTROL_BLOCK_ID:
4268 // This block is handled using look-ahead during ReadControlBlock. We
4269 // shouldn't get here!
4270 Error("malformed block record in AST file");
4271 return Failure;
4272
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 default:
4274 if (Stream.SkipBlock()) {
4275 Error("malformed block record in AST file");
4276 return Failure;
4277 }
4278 break;
4279 }
4280 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004281
Duncan P. N. Exon Smithfae03d82019-03-03 20:17:53 +00004282 llvm_unreachable("unexpected break; expected return");
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004283}
4284
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004285ASTReader::ASTReadResult
4286ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4287 unsigned ClientLoadCapabilities) {
4288 const HeaderSearchOptions &HSOpts =
4289 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4290 bool AllowCompatibleConfigurationMismatch =
4291 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4292
4293 ASTReadResult Result = readUnhashedControlBlockImpl(
4294 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4295 Listener.get(),
4296 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4297
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004298 // If F was directly imported by another module, it's implicitly validated by
4299 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004300 if (DisableValidation || WasImportedBy ||
4301 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4302 return Success;
4303
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004304 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004305 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004306 return Failure;
4307 }
4308
4309 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +00004310 // If this module has already been finalized in the ModuleCache, we're stuck
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004311 // with it; we can only load a single version of each module.
4312 //
4313 // This can happen when a module is imported in two contexts: in one, as a
4314 // user module; in another, as a system module (due to an import from
4315 // another module marked with the [system] flag). It usually indicates a
4316 // bug in the module map: this module should also be marked with [system].
4317 //
4318 // If -Wno-system-headers (the default), and the first import is as a
4319 // system module, then validation will fail during the as-user import,
4320 // since -Werror flags won't have been validated. However, it's reasonable
4321 // to treat this consistently as a system module.
4322 //
4323 // If -Wsystem-headers, the PCM on disk was built with
4324 // -Wno-system-headers, and the first import is as a user module, then
4325 // validation will fail during the as-system import since the PCM on disk
4326 // doesn't guarantee that -Werror was respected. However, the -Werror
4327 // flags were checked during the initial as-user import.
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00004328 if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004329 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4330 return Success;
4331 }
4332 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004333
4334 return Result;
4335}
4336
4337ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4338 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4339 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4340 bool ValidateDiagnosticOptions) {
4341 // Initialize a stream.
4342 BitstreamCursor Stream(StreamData);
4343
4344 // Sniff for the signature.
4345 if (!startsWithASTFileMagic(Stream))
4346 return Failure;
4347
4348 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4349 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4350 return Failure;
4351
4352 // Read all of the records in the options block.
4353 RecordData Record;
4354 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004355 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004356 llvm::BitstreamEntry Entry = Stream.advance();
4357
4358 switch (Entry.Kind) {
4359 case llvm::BitstreamEntry::Error:
4360 case llvm::BitstreamEntry::SubBlock:
4361 return Failure;
4362
4363 case llvm::BitstreamEntry::EndBlock:
4364 return Result;
4365
4366 case llvm::BitstreamEntry::Record:
4367 // The interesting case.
4368 break;
4369 }
4370
4371 // Read and process a record.
4372 Record.clear();
4373 switch (
4374 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004375 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004376 if (F)
4377 std::copy(Record.begin(), Record.end(), F->Signature.data());
4378 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004379 case DIAGNOSTIC_OPTIONS: {
4380 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4381 if (Listener && ValidateDiagnosticOptions &&
4382 !AllowCompatibleConfigurationMismatch &&
4383 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004384 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004385 break;
4386 }
4387 case DIAG_PRAGMA_MAPPINGS:
4388 if (!F)
4389 break;
4390 if (F->PragmaDiagMappings.empty())
4391 F->PragmaDiagMappings.swap(Record);
4392 else
4393 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4394 Record.begin(), Record.end());
4395 break;
4396 }
4397 }
4398}
4399
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004400/// Parse a record and blob containing module file extension metadata.
4401static bool parseModuleFileExtensionMetadata(
4402 const SmallVectorImpl<uint64_t> &Record,
4403 StringRef Blob,
4404 ModuleFileExtensionMetadata &Metadata) {
4405 if (Record.size() < 4) return true;
4406
4407 Metadata.MajorVersion = Record[0];
4408 Metadata.MinorVersion = Record[1];
4409
4410 unsigned BlockNameLen = Record[2];
4411 unsigned UserInfoLen = Record[3];
4412
4413 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4414
4415 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4416 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4417 Blob.data() + BlockNameLen + UserInfoLen);
4418 return false;
4419}
4420
4421ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4422 BitstreamCursor &Stream = F.Stream;
4423
4424 RecordData Record;
4425 while (true) {
4426 llvm::BitstreamEntry Entry = Stream.advance();
4427 switch (Entry.Kind) {
4428 case llvm::BitstreamEntry::SubBlock:
4429 if (Stream.SkipBlock())
4430 return Failure;
4431
4432 continue;
4433
4434 case llvm::BitstreamEntry::EndBlock:
4435 return Success;
4436
4437 case llvm::BitstreamEntry::Error:
4438 return HadErrors;
4439
4440 case llvm::BitstreamEntry::Record:
4441 break;
4442 }
4443
4444 Record.clear();
4445 StringRef Blob;
4446 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4447 switch (RecCode) {
4448 case EXTENSION_METADATA: {
4449 ModuleFileExtensionMetadata Metadata;
4450 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4451 return Failure;
4452
4453 // Find a module file extension with this block name.
4454 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4455 if (Known == ModuleFileExtensions.end()) break;
4456
4457 // Form a reader.
4458 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4459 F, Stream)) {
4460 F.ExtensionReaders.push_back(std::move(Reader));
4461 }
4462
4463 break;
4464 }
4465 }
4466 }
4467
4468 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004469}
4470
Richard Smitha7e2cc62015-05-01 01:53:09 +00004471void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004472 assert(ContextObj && "no context to initialize");
4473 ASTContext &Context = *ContextObj;
4474
Guy Benyei11169dd2012-12-18 14:30:41 +00004475 // If there's a listener, notify them that we "read" the translation unit.
4476 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004477 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 Context.getTranslationUnitDecl());
4479
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 // FIXME: Find a better way to deal with collisions between these
4481 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004482
Guy Benyei11169dd2012-12-18 14:30:41 +00004483 // Load the special types.
4484 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4485 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4486 if (!Context.CFConstantStringTypeDecl)
4487 Context.setCFConstantStringType(GetType(String));
4488 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004489
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4491 QualType FileType = GetType(File);
4492 if (FileType.isNull()) {
4493 Error("FILE type is NULL");
4494 return;
4495 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004496
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004498 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 Context.setFILEDecl(Typedef->getDecl());
4500 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004501 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 if (!Tag) {
4503 Error("Invalid FILE type in AST file");
4504 return;
4505 }
4506 Context.setFILEDecl(Tag->getDecl());
4507 }
4508 }
4509 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004510
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4512 QualType Jmp_bufType = GetType(Jmp_buf);
4513 if (Jmp_bufType.isNull()) {
4514 Error("jmp_buf type is NULL");
4515 return;
4516 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004517
Guy Benyei11169dd2012-12-18 14:30:41 +00004518 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004519 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 Context.setjmp_bufDecl(Typedef->getDecl());
4521 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004522 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 if (!Tag) {
4524 Error("Invalid jmp_buf type in AST file");
4525 return;
4526 }
4527 Context.setjmp_bufDecl(Tag->getDecl());
4528 }
4529 }
4530 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004531
Guy Benyei11169dd2012-12-18 14:30:41 +00004532 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4533 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4534 if (Sigjmp_bufType.isNull()) {
4535 Error("sigjmp_buf type is NULL");
4536 return;
4537 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004538
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004540 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004541 Context.setsigjmp_bufDecl(Typedef->getDecl());
4542 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004543 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004544 assert(Tag && "Invalid sigjmp_buf type in AST file");
4545 Context.setsigjmp_bufDecl(Tag->getDecl());
4546 }
4547 }
4548 }
4549
4550 if (unsigned ObjCIdRedef
4551 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4552 if (Context.ObjCIdRedefinitionType.isNull())
4553 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4554 }
4555
4556 if (unsigned ObjCClassRedef
4557 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4558 if (Context.ObjCClassRedefinitionType.isNull())
4559 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4560 }
4561
4562 if (unsigned ObjCSelRedef
4563 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4564 if (Context.ObjCSelRedefinitionType.isNull())
4565 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4566 }
4567
4568 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4569 QualType Ucontext_tType = GetType(Ucontext_t);
4570 if (Ucontext_tType.isNull()) {
4571 Error("ucontext_t type is NULL");
4572 return;
4573 }
4574
4575 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004576 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 Context.setucontext_tDecl(Typedef->getDecl());
4578 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004579 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 assert(Tag && "Invalid ucontext_t type in AST file");
4581 Context.setucontext_tDecl(Tag->getDecl());
4582 }
4583 }
4584 }
4585 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004586
Guy Benyei11169dd2012-12-18 14:30:41 +00004587 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4588
4589 // If there were any CUDA special declarations, deserialize them.
4590 if (!CUDASpecialDeclRefs.empty()) {
4591 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4592 Context.setcudaConfigureCallDecl(
4593 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4594 }
Richard Smith56be7542014-03-21 00:33:59 +00004595
Guy Benyei11169dd2012-12-18 14:30:41 +00004596 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004597 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004598 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004599 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004600 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004601 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004602 if (Import.ImportLoc.isValid())
4603 PP.makeModuleVisible(Imported, Import.ImportLoc);
4604 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004605 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
4607 ImportedModules.clear();
4608}
4609
4610void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004611 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004612}
4613
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004614/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004615/// else returns 0.
4616static ASTFileSignature readASTFileSignature(StringRef PCH) {
4617 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004618 if (!startsWithASTFileMagic(Stream))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004619 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004620
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004621 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4622 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004623 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004624
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004625 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004626 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004627 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004628 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004629 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004630 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004631
4632 Record.clear();
4633 StringRef Blob;
4634 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004635 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4636 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004637 }
4638}
4639
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004640/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004641/// directly from the AST file, without actually loading the AST
4642/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004643std::string ASTReader::getOriginalSourceFile(
4644 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004645 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004646 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004647 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004649 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4650 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004651 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004652 }
4653
4654 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004655 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004656
4657 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004658 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004660 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004662
Chris Lattnere7b154b2013-01-19 21:39:22 +00004663 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004664 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004665 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004666 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004667 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004668
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004669 // Scan for ORIGINAL_FILE inside the control block.
4670 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004671 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004672 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004673 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004674 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004675
Chris Lattnere7b154b2013-01-19 21:39:22 +00004676 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4677 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004678 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004679 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004680
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004682 StringRef Blob;
4683 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4684 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004685 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004686}
4687
4688namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004689
Guy Benyei11169dd2012-12-18 14:30:41 +00004690 class SimplePCHValidator : public ASTReaderListener {
4691 const LangOptions &ExistingLangOpts;
4692 const TargetOptions &ExistingTargetOpts;
4693 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004694 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004695 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004696
Guy Benyei11169dd2012-12-18 14:30:41 +00004697 public:
4698 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4699 const TargetOptions &ExistingTargetOpts,
4700 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004701 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 FileManager &FileMgr)
4703 : ExistingLangOpts(ExistingLangOpts),
4704 ExistingTargetOpts(ExistingTargetOpts),
4705 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004706 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004707 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004708
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004709 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4710 bool AllowCompatibleDifferences) override {
4711 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4712 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004714
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004715 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4716 bool AllowCompatibleDifferences) override {
4717 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4718 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004720
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004721 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4722 StringRef SpecificModuleCachePath,
4723 bool Complain) override {
4724 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4725 ExistingModuleCachePath,
4726 nullptr, ExistingLangOpts);
4727 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004728
Craig Topper3e89dfe2014-03-13 02:13:41 +00004729 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4730 bool Complain,
4731 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004732 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004733 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004734 }
4735 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004736
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004737} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004738
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004739bool ASTReader::readASTFileControlBlock(
4740 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004741 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004742 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004743 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004744 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004745 // FIXME: This allows use of the VFS; we do not allow use of the
4746 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004747 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 if (!Buffer) {
4749 return true;
4750 }
4751
4752 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004753 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4754 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004755
4756 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004757 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004758 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004759
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004760 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004761 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004762 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004763
4764 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004765 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004766 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004767 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004768
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004770 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004771 bool DoneWithControlBlock = false;
4772 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004773 llvm::BitstreamEntry Entry = Stream.advance();
4774
4775 switch (Entry.Kind) {
4776 case llvm::BitstreamEntry::SubBlock: {
4777 switch (Entry.ID) {
4778 case OPTIONS_BLOCK_ID: {
4779 std::string IgnoredSuggestedPredefines;
4780 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4781 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004782 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004783 return true;
4784 break;
4785 }
4786
4787 case INPUT_FILES_BLOCK_ID:
4788 InputFilesCursor = Stream;
4789 if (Stream.SkipBlock() ||
4790 (NeedsInputFiles &&
4791 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4792 return true;
4793 break;
4794
4795 default:
4796 if (Stream.SkipBlock())
4797 return true;
4798 break;
4799 }
4800
4801 continue;
4802 }
4803
4804 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004805 DoneWithControlBlock = true;
4806 break;
Richard Smith0516b182015-09-08 19:40:14 +00004807
4808 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004809 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004810
4811 case llvm::BitstreamEntry::Record:
4812 break;
4813 }
4814
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004815 if (DoneWithControlBlock) break;
4816
Guy Benyei11169dd2012-12-18 14:30:41 +00004817 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004818 StringRef Blob;
4819 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004820 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004821 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004822 if (Record[0] != VERSION_MAJOR)
4823 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004824 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004825 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004826 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004827 case MODULE_NAME:
4828 Listener.ReadModuleName(Blob);
4829 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004830 case MODULE_DIRECTORY:
4831 ModuleDir = Blob;
4832 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004833 case MODULE_MAP_FILE: {
4834 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004835 auto Path = ReadString(Record, Idx);
4836 ResolveImportedPath(Path, ModuleDir);
4837 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004838 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004839 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004840 case INPUT_FILE_OFFSETS: {
4841 if (!NeedsInputFiles)
4842 break;
4843
4844 unsigned NumInputFiles = Record[0];
4845 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00004846 const llvm::support::unaligned_uint64_t *InputFileOffs =
4847 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004848 for (unsigned I = 0; I != NumInputFiles; ++I) {
4849 // Go find this input file.
4850 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004851
4852 if (isSystemFile && !NeedsSystemInputFiles)
4853 break; // the rest are system input files
4854
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004855 BitstreamCursor &Cursor = InputFilesCursor;
4856 SavedStreamPosition SavedPosition(Cursor);
4857 Cursor.JumpToBit(InputFileOffs[I]);
4858
4859 unsigned Code = Cursor.ReadCode();
4860 RecordData Record;
4861 StringRef Blob;
4862 bool shouldContinue = false;
4863 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4864 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00004865 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004866 std::string Filename = Blob;
4867 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004868 shouldContinue = Listener.visitInputFile(
4869 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004870 break;
4871 }
4872 if (!shouldContinue)
4873 break;
4874 }
4875 break;
4876 }
4877
Richard Smithd4b230b2014-10-27 23:01:16 +00004878 case IMPORTS: {
4879 if (!NeedsImports)
4880 break;
4881
4882 unsigned Idx = 0, N = Record.size();
4883 while (Idx < N) {
4884 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00004885 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
4886 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004887 std::string Filename = ReadString(Record, Idx);
4888 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00004889 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004890 }
4891 break;
4892 }
4893
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004894 default:
4895 // No other validation to perform.
4896 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004897 }
4898 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004899
4900 // Look for module file extension blocks, if requested.
4901 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004902 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004903 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4904 bool DoneWithExtensionBlock = false;
4905 while (!DoneWithExtensionBlock) {
4906 llvm::BitstreamEntry Entry = Stream.advance();
4907
4908 switch (Entry.Kind) {
4909 case llvm::BitstreamEntry::SubBlock:
4910 if (Stream.SkipBlock())
4911 return true;
4912
4913 continue;
4914
4915 case llvm::BitstreamEntry::EndBlock:
4916 DoneWithExtensionBlock = true;
4917 continue;
4918
4919 case llvm::BitstreamEntry::Error:
4920 return true;
4921
4922 case llvm::BitstreamEntry::Record:
4923 break;
4924 }
4925
4926 Record.clear();
4927 StringRef Blob;
4928 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4929 switch (RecCode) {
4930 case EXTENSION_METADATA: {
4931 ModuleFileExtensionMetadata Metadata;
4932 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4933 return true;
4934
4935 Listener.readModuleFileExtension(Metadata);
4936 break;
4937 }
4938 }
4939 }
4940 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004941 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004942 }
4943
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004944 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4945 if (readUnhashedControlBlockImpl(
4946 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4947 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4948 ValidateDiagnosticOptions) != Success)
4949 return true;
4950
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004951 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004952}
4953
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004954bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4955 const PCHContainerReader &PCHContainerRdr,
4956 const LangOptions &LangOpts,
4957 const TargetOptions &TargetOpts,
4958 const PreprocessorOptions &PPOpts,
4959 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004960 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4961 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004962 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004963 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004964 validator,
4965 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004966}
4967
Ben Langmuir2c9af442014-04-10 17:57:43 +00004968ASTReader::ASTReadResult
4969ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 // Enter the submodule block.
4971 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4972 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004973 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 }
4975
4976 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4977 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004978 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004979 RecordData Record;
4980 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004981 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004982
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004983 switch (Entry.Kind) {
4984 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4985 case llvm::BitstreamEntry::Error:
4986 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004987 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004988 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004989 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004990 case llvm::BitstreamEntry::Record:
4991 // The interesting case.
4992 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004994
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004996 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004998 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4999
5000 if ((Kind == SUBMODULE_METADATA) != First) {
5001 Error("submodule metadata record should be at beginning of block");
5002 return Failure;
5003 }
5004 First = false;
5005
5006 // Submodule information is only valid if we have a current module.
5007 // FIXME: Should we error on these cases?
5008 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
5009 Kind != SUBMODULE_DEFINITION)
5010 continue;
5011
5012 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 default: // Default behavior: ignore.
5014 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005015
Richard Smith03478d92014-10-23 22:12:14 +00005016 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005017 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005019 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 }
Richard Smith03478d92014-10-23 22:12:14 +00005021
Chris Lattner0e6c9402013-01-20 02:38:54 +00005022 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005023 unsigned Idx = 0;
5024 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5025 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005026 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005027 bool IsFramework = Record[Idx++];
5028 bool IsExplicit = Record[Idx++];
5029 bool IsSystem = Record[Idx++];
5030 bool IsExternC = Record[Idx++];
5031 bool InferSubmodules = Record[Idx++];
5032 bool InferExplicitSubmodules = Record[Idx++];
5033 bool InferExportWildcard = Record[Idx++];
5034 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005035 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005036
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005037 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005038 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005040
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 // Retrieve this (sub)module from the module map, creating it if
5042 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005043 CurrentModule =
5044 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5045 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005046
5047 // FIXME: set the definition loc for CurrentModule, or call
5048 // ModMap.setInferredModuleAllowedBy()
5049
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5051 if (GlobalIndex >= SubmodulesLoaded.size() ||
5052 SubmodulesLoaded[GlobalIndex]) {
5053 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005054 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005056
Douglas Gregor7029ce12013-03-19 00:28:20 +00005057 if (!ParentModule) {
5058 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005059 // Don't emit module relocation error if we have -fno-validate-pch
5060 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5061 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005062 if (!Diags.isDiagnosticInFlight()) {
5063 Diag(diag::err_module_file_conflict)
5064 << CurrentModule->getTopLevelModuleName()
5065 << CurFile->getName()
5066 << F.File->getName();
5067 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005068 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005069 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005070 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005071
5072 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005073 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005074 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005075
Richard Smithdd8b5332017-09-04 05:37:53 +00005076 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005077 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005078 CurrentModule->IsFromModuleFile = true;
5079 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005080 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 CurrentModule->InferSubmodules = InferSubmodules;
5082 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5083 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005084 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005085 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 if (DeserializationListener)
5087 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005088
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005090
Richard Smith8a3e39a2016-03-28 21:31:09 +00005091 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005092 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005093 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005094 CurrentModule->UnresolvedConflicts.clear();
5095 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005096
5097 // The module is available unless it's missing a requirement; relevant
5098 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5099 // Missing headers that were present when the module was built do not
5100 // make it unavailable -- if we got this far, this must be an explicitly
5101 // imported module file.
5102 CurrentModule->Requirements.clear();
5103 CurrentModule->MissingHeaders.clear();
5104 CurrentModule->IsMissingRequirement =
5105 ParentModule && ParentModule->IsMissingRequirement;
5106 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 break;
5108 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005109
Guy Benyei11169dd2012-12-18 14:30:41 +00005110 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005111 std::string Filename = Blob;
5112 ResolveImportedPath(F, Filename);
5113 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005115 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5116 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005117 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5118 Error("mismatched umbrella headers in submodule");
5119 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 }
5121 }
5122 break;
5123 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005124
Richard Smith202210b2014-10-24 20:23:01 +00005125 case SUBMODULE_HEADER:
5126 case SUBMODULE_EXCLUDED_HEADER:
5127 case SUBMODULE_PRIVATE_HEADER:
5128 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005129 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5130 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005131 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005132
Richard Smith202210b2014-10-24 20:23:01 +00005133 case SUBMODULE_TEXTUAL_HEADER:
5134 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5135 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5136 // them here.
5137 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005138
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005139 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005140 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005142
5143 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005144 std::string Dirname = Blob;
5145 ResolveImportedPath(F, Dirname);
5146 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005148 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5149 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005150 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5151 Error("mismatched umbrella directories in submodule");
5152 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 }
5154 }
5155 break;
5156 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005157
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 F.BaseSubmoduleID = getTotalNumSubmodules();
5160 F.LocalNumSubmodules = Record[0];
5161 unsigned LocalBaseSubmoduleID = Record[1];
5162 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005163 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 // module.
5165 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005166
5167 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 // module.
5169 F.SubmoduleRemap.insertOrReplace(
5170 std::make_pair(LocalBaseSubmoduleID,
5171 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005172
Ben Langmuir52ca6782014-10-20 16:27:32 +00005173 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5174 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 break;
5176 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005177
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005178 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005179 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005180 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 Unresolved.File = &F;
5182 Unresolved.Mod = CurrentModule;
5183 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005184 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005186 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005187 }
5188 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005189
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005190 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005191 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005192 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005193 Unresolved.File = &F;
5194 Unresolved.Mod = CurrentModule;
5195 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005196 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005197 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005198 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005199 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005200
5201 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 // the parsed, unresolved exports around.
5203 CurrentModule->UnresolvedExports.clear();
5204 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005205
5206 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005207 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5208 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005210
5211 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005212 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005213 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005214 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005215 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005216
5217 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005218 CurrentModule->ConfigMacros.push_back(Blob.str());
5219 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005220
5221 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005222 UnresolvedModuleRef Unresolved;
5223 Unresolved.File = &F;
5224 Unresolved.Mod = CurrentModule;
5225 Unresolved.ID = Record[0];
5226 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5227 Unresolved.IsWildcard = false;
5228 Unresolved.String = Blob;
5229 UnresolvedModuleRefs.push_back(Unresolved);
5230 break;
5231 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005232
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005233 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005234 if (!ContextObj)
5235 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005236 SmallVector<uint32_t, 16> Inits;
5237 for (auto &ID : Record)
5238 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005239 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005240 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005242
5243 case SUBMODULE_EXPORT_AS:
5244 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005245 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005246 break;
5247 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 }
5249}
5250
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005251/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005252/// structure.
5253///
5254/// This routine parses the language options from the AST file and then gives
5255/// them to the AST listener if one is set.
5256///
5257/// \returns true if the listener deems the file unacceptable, false otherwise.
5258bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5259 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005260 ASTReaderListener &Listener,
5261 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005262 LangOptions LangOpts;
5263 unsigned Idx = 0;
5264#define LANGOPT(Name, Bits, Default, Description) \
5265 LangOpts.Name = Record[Idx++];
5266#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5267 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5268#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005269#define SANITIZER(NAME, ID) \
5270 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005271#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005272
Ben Langmuircd98cb72015-06-23 18:20:18 +00005273 for (unsigned N = Record[Idx++]; N; --N)
5274 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5275
Vedant Kumar48b4f762018-04-14 01:40:48 +00005276 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5278 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005279
Ben Langmuird4a667a2015-06-23 18:20:23 +00005280 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005281
5282 // Comment options.
5283 for (unsigned N = Record[Idx++]; N; --N) {
5284 LangOpts.CommentOpts.BlockCommandNames.push_back(
5285 ReadString(Record, Idx));
5286 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005287 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005288
Samuel Antaoee8fb302016-01-06 13:42:12 +00005289 // OpenMP offloading options.
5290 for (unsigned N = Record[Idx++]; N; --N) {
5291 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5292 }
5293
5294 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5295
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005296 return Listener.ReadLanguageOptions(LangOpts, Complain,
5297 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005298}
5299
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005300bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5301 ASTReaderListener &Listener,
5302 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 unsigned Idx = 0;
5304 TargetOptions TargetOpts;
5305 TargetOpts.Triple = ReadString(Record, Idx);
5306 TargetOpts.CPU = ReadString(Record, Idx);
5307 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 for (unsigned N = Record[Idx++]; N; --N) {
5309 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5310 }
5311 for (unsigned N = Record[Idx++]; N; --N) {
5312 TargetOpts.Features.push_back(ReadString(Record, Idx));
5313 }
5314
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005315 return Listener.ReadTargetOptions(TargetOpts, Complain,
5316 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005317}
5318
5319bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5320 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005321 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005323#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005324#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005325 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005326#include "clang/Basic/DiagnosticOptions.def"
5327
Richard Smith3be1cb22014-08-07 00:24:21 +00005328 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005329 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005330 for (unsigned N = Record[Idx++]; N; --N)
5331 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005332
5333 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5334}
5335
5336bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5337 ASTReaderListener &Listener) {
5338 FileSystemOptions FSOpts;
5339 unsigned Idx = 0;
5340 FSOpts.WorkingDir = ReadString(Record, Idx);
5341 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5342}
5343
5344bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5345 bool Complain,
5346 ASTReaderListener &Listener) {
5347 HeaderSearchOptions HSOpts;
5348 unsigned Idx = 0;
5349 HSOpts.Sysroot = ReadString(Record, Idx);
5350
5351 // Include entries.
5352 for (unsigned N = Record[Idx++]; N; --N) {
5353 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005354 frontend::IncludeDirGroup Group
5355 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005356 bool IsFramework = Record[Idx++];
5357 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005358 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5359 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 }
5361
5362 // System header prefixes.
5363 for (unsigned N = Record[Idx++]; N; --N) {
5364 std::string Prefix = ReadString(Record, Idx);
5365 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005366 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005367 }
5368
5369 HSOpts.ResourceDir = ReadString(Record, Idx);
5370 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005371 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005372 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005373 HSOpts.ImplicitModuleMaps = Record[Idx++];
5374 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 HSOpts.UseBuiltinIncludes = Record[Idx++];
5376 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5377 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5378 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005379 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005380
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005381 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5382 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005383}
5384
5385bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5386 bool Complain,
5387 ASTReaderListener &Listener,
5388 std::string &SuggestedPredefines) {
5389 PreprocessorOptions PPOpts;
5390 unsigned Idx = 0;
5391
5392 // Macro definitions/undefs
5393 for (unsigned N = Record[Idx++]; N; --N) {
5394 std::string Macro = ReadString(Record, Idx);
5395 bool IsUndef = Record[Idx++];
5396 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5397 }
5398
5399 // Includes
5400 for (unsigned N = Record[Idx++]; N; --N) {
5401 PPOpts.Includes.push_back(ReadString(Record, Idx));
5402 }
5403
5404 // Macro Includes
5405 for (unsigned N = Record[Idx++]; N; --N) {
5406 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5407 }
5408
5409 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005410 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005411 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 PPOpts.ObjCXXARCStandardLibrary =
5413 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5414 SuggestedPredefines.clear();
5415 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5416 SuggestedPredefines);
5417}
5418
5419std::pair<ModuleFile *, unsigned>
5420ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5421 GlobalPreprocessedEntityMapType::iterator
5422 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005423 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005424 "Corrupted global preprocessed entity map");
5425 ModuleFile *M = I->second;
5426 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5427 return std::make_pair(M, LocalIndex);
5428}
5429
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005430llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005431ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5432 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5433 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5434 Mod.NumPreprocessedEntities);
5435
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005436 return llvm::make_range(PreprocessingRecord::iterator(),
5437 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005438}
5439
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005440llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005441ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005442 return llvm::make_range(
5443 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5444 ModuleDeclIterator(this, &Mod,
5445 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005446}
5447
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005448SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5449 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5450 assert(I != GlobalSkippedRangeMap.end() &&
5451 "Corrupted global skipped range map");
5452 ModuleFile *M = I->second;
5453 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5454 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5455 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5456 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5457 TranslateSourceLocation(*M, RawRange.getEnd()));
5458 assert(Range.isValid());
5459 return Range;
5460}
5461
Guy Benyei11169dd2012-12-18 14:30:41 +00005462PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5463 PreprocessedEntityID PPID = Index+1;
5464 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5465 ModuleFile &M = *PPInfo.first;
5466 unsigned LocalIndex = PPInfo.second;
5467 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5468
Guy Benyei11169dd2012-12-18 14:30:41 +00005469 if (!PP.getPreprocessingRecord()) {
5470 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005471 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005472 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005473
5474 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005475 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5476
5477 llvm::BitstreamEntry Entry =
5478 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5479 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005480 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005481
Guy Benyei11169dd2012-12-18 14:30:41 +00005482 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005483 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5484 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005485 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005486 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005487 RecordData Record;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005488 PreprocessorDetailRecordTypes RecType =
5489 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5490 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005491 switch (RecType) {
5492 case PPD_MACRO_EXPANSION: {
5493 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005494 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005495 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005496 if (isBuiltin)
5497 Name = getLocalIdentifier(M, Record[1]);
5498 else {
Richard Smith66a81862015-05-04 02:25:31 +00005499 PreprocessedEntityID GlobalID =
5500 getGlobalPreprocessedEntityID(M, Record[1]);
5501 Def = cast<MacroDefinitionRecord>(
5502 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005503 }
5504
5505 MacroExpansion *ME;
5506 if (isBuiltin)
5507 ME = new (PPRec) MacroExpansion(Name, Range);
5508 else
5509 ME = new (PPRec) MacroExpansion(Def, Range);
5510
5511 return ME;
5512 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005513
Guy Benyei11169dd2012-12-18 14:30:41 +00005514 case PPD_MACRO_DEFINITION: {
5515 // Decode the identifier info and then check again; if the macro is
5516 // still defined and associated with the identifier,
5517 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005518 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005519
5520 if (DeserializationListener)
5521 DeserializationListener->MacroDefinitionRead(PPID, MD);
5522
5523 return MD;
5524 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005525
Guy Benyei11169dd2012-12-18 14:30:41 +00005526 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005527 const char *FullFileNameStart = Blob.data() + Record[0];
5528 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005529 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005530 if (!FullFileName.empty())
5531 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005532
Guy Benyei11169dd2012-12-18 14:30:41 +00005533 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005534 InclusionDirective::InclusionKind Kind
5535 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5536 InclusionDirective *ID
5537 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005538 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 Record[1], Record[3],
5540 File,
5541 Range);
5542 return ID;
5543 }
5544 }
5545
5546 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5547}
5548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005550/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005551///
5552/// \param SLocMapI points at a chunk of a module that contains no
5553/// preprocessed entities or the entities it contains are not the ones we are
5554/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005555PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5556 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5557 ++SLocMapI;
5558 for (GlobalSLocOffsetMapType::const_iterator
5559 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5560 ModuleFile &M = *SLocMapI->second;
5561 if (M.NumPreprocessedEntities)
5562 return M.BasePreprocessedEntityID;
5563 }
5564
5565 return getTotalNumPreprocessedEntities();
5566}
5567
5568namespace {
5569
Guy Benyei11169dd2012-12-18 14:30:41 +00005570struct PPEntityComp {
5571 const ASTReader &Reader;
5572 ModuleFile &M;
5573
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005574 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005575
5576 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5577 SourceLocation LHS = getLoc(L);
5578 SourceLocation RHS = getLoc(R);
5579 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5580 }
5581
5582 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5583 SourceLocation LHS = getLoc(L);
5584 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5585 }
5586
5587 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5588 SourceLocation RHS = getLoc(R);
5589 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5590 }
5591
5592 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005593 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005594 }
5595};
5596
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005597} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005598
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005599PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5600 bool EndsAfter) const {
5601 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005602 return getTotalNumPreprocessedEntities();
5603
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005604 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5605 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005606 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5607 "Corrupted global sloc offset map");
5608
5609 if (SLocMapI->second->NumPreprocessedEntities == 0)
5610 return findNextPreprocessedEntity(SLocMapI);
5611
5612 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005613
5614 using pp_iterator = const PPEntityOffset *;
5615
Guy Benyei11169dd2012-12-18 14:30:41 +00005616 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5617 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5618
5619 size_t Count = M.NumPreprocessedEntities;
5620 size_t Half;
5621 pp_iterator First = pp_begin;
5622 pp_iterator PPI;
5623
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005624 if (EndsAfter) {
5625 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005626 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005627 } else {
5628 // Do a binary search manually instead of using std::lower_bound because
5629 // The end locations of entities may be unordered (when a macro expansion
5630 // is inside another macro argument), but for this case it is not important
5631 // whether we get the first macro expansion or its containing macro.
5632 while (Count > 0) {
5633 Half = Count / 2;
5634 PPI = First;
5635 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005636 if (SourceMgr.isBeforeInTranslationUnit(
5637 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005638 First = PPI;
5639 ++First;
5640 Count = Count - Half - 1;
5641 } else
5642 Count = Half;
5643 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005644 }
5645
5646 if (PPI == pp_end)
5647 return findNextPreprocessedEntity(SLocMapI);
5648
5649 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5650}
5651
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005652/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00005653/// preprocessed entities that \arg Range encompasses.
5654std::pair<unsigned, unsigned>
5655 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5656 if (Range.isInvalid())
5657 return std::make_pair(0,0);
5658 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5659
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005660 PreprocessedEntityID BeginID =
5661 findPreprocessedEntity(Range.getBegin(), false);
5662 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005663 return std::make_pair(BeginID, EndID);
5664}
5665
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005666/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00005667/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005668Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005669 FileID FID) {
5670 if (FID.isInvalid())
5671 return false;
5672
5673 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5674 ModuleFile &M = *PPInfo.first;
5675 unsigned LocalIndex = PPInfo.second;
5676 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005677
Richard Smithcb34bd32016-03-27 07:28:06 +00005678 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005679 if (Loc.isInvalid())
5680 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005681
Guy Benyei11169dd2012-12-18 14:30:41 +00005682 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5683 return true;
5684 else
5685 return false;
5686}
5687
5688namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005689
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005690 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005692 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005693 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005694
Guy Benyei11169dd2012-12-18 14:30:41 +00005695 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005696 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005697
5698 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00005699 HeaderFileInfoLookupTable *Table
5700 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00005701 if (!Table)
5702 return false;
5703
5704 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005705 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005706 if (Pos == Table->end())
5707 return false;
5708
Richard Smithbdf2d932015-07-30 03:37:16 +00005709 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005710 return true;
5711 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005712
David Blaikie05785d12013-02-20 22:23:23 +00005713 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005714 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005715
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005716} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005717
5718HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005719 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005720 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005721 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005722 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005723
Guy Benyei11169dd2012-12-18 14:30:41 +00005724 return HeaderFileInfo();
5725}
5726
5727void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005728 using DiagState = DiagnosticsEngine::DiagState;
5729 SmallVector<DiagState *, 32> DiagStates;
5730
Vedant Kumar48b4f762018-04-14 01:40:48 +00005731 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005732 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005733 auto &Record = F.PragmaDiagMappings;
5734 if (Record.empty())
5735 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005736
Richard Smithd230de22017-01-26 01:01:01 +00005737 DiagStates.clear();
5738
5739 auto ReadDiagState =
5740 [&](const DiagState &BasedOn, SourceLocation Loc,
5741 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5742 unsigned BackrefID = Record[Idx++];
5743 if (BackrefID != 0)
5744 return DiagStates[BackrefID - 1];
5745
Guy Benyei11169dd2012-12-18 14:30:41 +00005746 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005747 Diag.DiagStates.push_back(BasedOn);
5748 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005749 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005750 unsigned Size = Record[Idx++];
5751 assert(Idx + Size * 2 <= Record.size() &&
5752 "Invalid data, not enough diag/map pairs");
5753 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005754 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005755 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005756 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005757 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5758 continue;
5759
5760 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5761
5762 // If this mapping was specified as a warning but the severity was
5763 // upgraded due to diagnostic settings, simulate the current diagnostic
5764 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005765 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5766 NewMapping.setSeverity(diag::Severity::Warning);
5767 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005768 }
5769
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005770 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005771 }
Richard Smithd230de22017-01-26 01:01:01 +00005772 return NewState;
5773 };
5774
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005775 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005776 DiagState *FirstState;
5777 if (F.Kind == MK_ImplicitModule) {
5778 // Implicitly-built modules are reused with different diagnostic
5779 // settings. Use the initial diagnostic state from Diag to simulate this
5780 // compilation's diagnostic settings.
5781 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5782 DiagStates.push_back(FirstState);
5783
5784 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005785 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005786 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005787 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005788 assert(Idx < Record.size() &&
5789 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005790 } else if (F.isModule()) {
5791 // For an explicit module, preserve the flags from the module build
5792 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5793 // -Wblah flags.
5794 unsigned Flags = Record[Idx++];
5795 DiagState Initial;
5796 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5797 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5798 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5799 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5800 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5801 Initial.ExtBehavior = (diag::Severity)Flags;
5802 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005803
Richard Smith6c2b5a82018-02-09 01:15:13 +00005804 assert(F.OriginalSourceFileID.isValid());
5805
Richard Smithe37391c2017-05-03 00:28:49 +00005806 // Set up the root buffer of the module to start with the initial
5807 // diagnostic state of the module itself, to cover files that contain no
5808 // explicit transitions (for which we did not serialize anything).
5809 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5810 .StateTransitions.push_back({FirstState, 0});
5811 } else {
5812 // For prefix ASTs, start with whatever the user configured on the
5813 // command line.
5814 Idx++; // Skip flags.
5815 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5816 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005817 }
Richard Smithd230de22017-01-26 01:01:01 +00005818
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005819 // Read the state transitions.
5820 unsigned NumLocations = Record[Idx++];
5821 while (NumLocations--) {
5822 assert(Idx < Record.size() &&
5823 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005824 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5825 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00005826 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00005827 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5828 unsigned Transitions = Record[Idx++];
5829
5830 // Note that we don't need to set up Parent/ParentOffset here, because
5831 // we won't be changing the diagnostic state within imported FileIDs
5832 // (other than perhaps appending to the main source file, which has no
5833 // parent).
5834 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5835 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5836 for (unsigned I = 0; I != Transitions; ++I) {
5837 unsigned Offset = Record[Idx++];
5838 auto *State =
5839 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5840 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005841 }
5842 }
Richard Smithd230de22017-01-26 01:01:01 +00005843
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005844 // Read the final state.
5845 assert(Idx < Record.size() &&
5846 "Invalid data, missing final pragma diagnostic state");
5847 SourceLocation CurStateLoc =
5848 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5849 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5850
5851 if (!F.isModule()) {
5852 Diag.DiagStatesByLoc.CurDiagState = CurState;
5853 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5854
5855 // Preserve the property that the imaginary root file describes the
5856 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005857 FileID NullFile;
5858 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005859 if (T.empty())
5860 T.push_back({CurState, 0});
5861 else
5862 T[0].State = CurState;
5863 }
5864
Richard Smithd230de22017-01-26 01:01:01 +00005865 // Don't try to read these mappings again.
5866 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 }
5868}
5869
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005870/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00005871ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5872 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5873 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5874 ModuleFile *M = I->second;
5875 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5876}
5877
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005878/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00005879///
5880/// The index is the type ID, shifted and minus the number of predefs. This
5881/// routine actually reads the record corresponding to the type at the given
5882/// location. It is a helper routine for GetType, which deals with reading type
5883/// IDs.
5884QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005885 assert(ContextObj && "reading type with no AST context");
5886 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005887 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005888 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005889
5890 // Keep track of where we are in the stream, then jump back there
5891 // after reading this type.
5892 SavedStreamPosition SavedPosition(DeclsCursor);
5893
5894 ReadingKindTracker ReadingKind(Read_Type, *this);
5895
5896 // Note that we are loading a type record.
5897 Deserializing AType(this);
5898
5899 unsigned Idx = 0;
5900 DeclsCursor.JumpToBit(Loc.Offset);
5901 RecordData Record;
5902 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005903 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005904 case TYPE_EXT_QUAL: {
5905 if (Record.size() != 2) {
5906 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005907 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005908 }
5909 QualType Base = readType(*Loc.F, Record, Idx);
5910 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5911 return Context.getQualifiedType(Base, Quals);
5912 }
5913
5914 case TYPE_COMPLEX: {
5915 if (Record.size() != 1) {
5916 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005917 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005918 }
5919 QualType ElemType = readType(*Loc.F, Record, Idx);
5920 return Context.getComplexType(ElemType);
5921 }
5922
5923 case TYPE_POINTER: {
5924 if (Record.size() != 1) {
5925 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005926 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005927 }
5928 QualType PointeeType = readType(*Loc.F, Record, Idx);
5929 return Context.getPointerType(PointeeType);
5930 }
5931
Reid Kleckner8a365022013-06-24 17:51:48 +00005932 case TYPE_DECAYED: {
5933 if (Record.size() != 1) {
5934 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005935 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00005936 }
5937 QualType OriginalType = readType(*Loc.F, Record, Idx);
5938 QualType DT = Context.getAdjustedParameterType(OriginalType);
5939 if (!isa<DecayedType>(DT))
5940 Error("Decayed type does not decay");
5941 return DT;
5942 }
5943
Reid Kleckner0503a872013-12-05 01:23:43 +00005944 case TYPE_ADJUSTED: {
5945 if (Record.size() != 2) {
5946 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005947 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00005948 }
5949 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5950 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5951 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5952 }
5953
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 case TYPE_BLOCK_POINTER: {
5955 if (Record.size() != 1) {
5956 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005957 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005958 }
5959 QualType PointeeType = readType(*Loc.F, Record, Idx);
5960 return Context.getBlockPointerType(PointeeType);
5961 }
5962
5963 case TYPE_LVALUE_REFERENCE: {
5964 if (Record.size() != 2) {
5965 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005966 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005967 }
5968 QualType PointeeType = readType(*Loc.F, Record, Idx);
5969 return Context.getLValueReferenceType(PointeeType, Record[1]);
5970 }
5971
5972 case TYPE_RVALUE_REFERENCE: {
5973 if (Record.size() != 1) {
5974 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005975 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 }
5977 QualType PointeeType = readType(*Loc.F, Record, Idx);
5978 return Context.getRValueReferenceType(PointeeType);
5979 }
5980
5981 case TYPE_MEMBER_POINTER: {
5982 if (Record.size() != 2) {
5983 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005984 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005985 }
5986 QualType PointeeType = readType(*Loc.F, Record, Idx);
5987 QualType ClassType = readType(*Loc.F, Record, Idx);
5988 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00005989 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005990
Guy Benyei11169dd2012-12-18 14:30:41 +00005991 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5992 }
5993
5994 case TYPE_CONSTANT_ARRAY: {
5995 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005996 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005997 unsigned IndexTypeQuals = Record[2];
5998 unsigned Idx = 3;
5999 llvm::APInt Size = ReadAPInt(Record, Idx);
6000 return Context.getConstantArrayType(ElementType, Size,
6001 ASM, IndexTypeQuals);
6002 }
6003
6004 case TYPE_INCOMPLETE_ARRAY: {
6005 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006006 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006007 unsigned IndexTypeQuals = Record[2];
6008 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
6009 }
6010
6011 case TYPE_VARIABLE_ARRAY: {
6012 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006013 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00006014 unsigned IndexTypeQuals = Record[2];
6015 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
6016 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
6017 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
6018 ASM, IndexTypeQuals,
6019 SourceRange(LBLoc, RBLoc));
6020 }
6021
6022 case TYPE_VECTOR: {
6023 if (Record.size() != 3) {
6024 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006025 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006026 }
6027
6028 QualType ElementType = readType(*Loc.F, Record, Idx);
6029 unsigned NumElements = Record[1];
6030 unsigned VecKind = Record[2];
6031 return Context.getVectorType(ElementType, NumElements,
6032 (VectorType::VectorKind)VecKind);
6033 }
6034
6035 case TYPE_EXT_VECTOR: {
6036 if (Record.size() != 3) {
6037 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006038 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006039 }
6040
6041 QualType ElementType = readType(*Loc.F, Record, Idx);
6042 unsigned NumElements = Record[1];
6043 return Context.getExtVectorType(ElementType, NumElements);
6044 }
6045
6046 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006047 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006048 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006049 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006050 }
6051 QualType ResultType = readType(*Loc.F, Record, Idx);
6052 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006053 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006054 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006055 return Context.getFunctionNoProtoType(ResultType, Info);
6056 }
6057
6058 case TYPE_FUNCTION_PROTO: {
6059 QualType ResultType = readType(*Loc.F, Record, Idx);
6060
6061 FunctionProtoType::ExtProtoInfo EPI;
6062 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6063 /*hasregparm*/ Record[2],
6064 /*regparm*/ Record[3],
6065 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006066 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006067 /*nocallersavedregs*/ Record[6],
6068 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006069
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006070 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006071
6072 EPI.Variadic = Record[Idx++];
6073 EPI.HasTrailingReturn = Record[Idx++];
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00006074 EPI.TypeQuals = Qualifiers::fromOpaqueValue(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006076 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006077 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006078
6079 unsigned NumParams = Record[Idx++];
6080 SmallVector<QualType, 16> ParamTypes;
6081 for (unsigned I = 0; I != NumParams; ++I)
6082 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6083
John McCall18afab72016-03-01 00:49:02 +00006084 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6085 if (Idx != Record.size()) {
6086 for (unsigned I = 0; I != NumParams; ++I)
6087 ExtParameterInfos.push_back(
6088 FunctionProtoType::ExtParameterInfo
6089 ::getFromOpaqueValue(Record[Idx++]));
6090 EPI.ExtParameterInfos = ExtParameterInfos.data();
6091 }
6092
6093 assert(Idx == Record.size());
6094
Jordan Rose5c382722013-03-08 21:51:21 +00006095 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006096 }
6097
6098 case TYPE_UNRESOLVED_USING: {
6099 unsigned Idx = 0;
6100 return Context.getTypeDeclType(
6101 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6102 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006103
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 case TYPE_TYPEDEF: {
6105 if (Record.size() != 2) {
6106 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006107 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006108 }
6109 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006110 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006111 QualType Canonical = readType(*Loc.F, Record, Idx);
6112 if (!Canonical.isNull())
6113 Canonical = Context.getCanonicalType(Canonical);
6114 return Context.getTypedefType(Decl, Canonical);
6115 }
6116
6117 case TYPE_TYPEOF_EXPR:
6118 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6119
6120 case TYPE_TYPEOF: {
6121 if (Record.size() != 1) {
6122 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006123 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006124 }
6125 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6126 return Context.getTypeOfType(UnderlyingType);
6127 }
6128
6129 case TYPE_DECLTYPE: {
6130 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6131 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6132 }
6133
6134 case TYPE_UNARY_TRANSFORM: {
6135 QualType BaseType = readType(*Loc.F, Record, Idx);
6136 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006137 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006138 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6139 }
6140
Richard Smith74aeef52013-04-26 16:15:35 +00006141 case TYPE_AUTO: {
6142 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006143 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smithb2997f52019-05-21 20:10:50 +00006144 bool IsDependent = false, IsPack = false;
6145 if (Deduced.isNull()) {
6146 IsDependent = Record[Idx] > 0;
6147 IsPack = Record[Idx] > 1;
6148 ++Idx;
6149 }
6150 return Context.getAutoType(Deduced, Keyword, IsDependent, IsPack);
Richard Smith74aeef52013-04-26 16:15:35 +00006151 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006152
Richard Smith600b5262017-01-26 20:40:47 +00006153 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6154 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6155 QualType Deduced = readType(*Loc.F, Record, Idx);
6156 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6157 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6158 IsDependent);
6159 }
6160
Guy Benyei11169dd2012-12-18 14:30:41 +00006161 case TYPE_RECORD: {
6162 if (Record.size() != 2) {
6163 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006164 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 }
6166 unsigned Idx = 0;
6167 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006168 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006169 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6170 QualType T = Context.getRecordType(RD);
6171 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6172 return T;
6173 }
6174
6175 case TYPE_ENUM: {
6176 if (Record.size() != 2) {
6177 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006178 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 }
6180 unsigned Idx = 0;
6181 bool IsDependent = Record[Idx++];
6182 QualType T
6183 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6184 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6185 return T;
6186 }
6187
6188 case TYPE_ATTRIBUTED: {
6189 if (Record.size() != 3) {
6190 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006191 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 }
6193 QualType modifiedType = readType(*Loc.F, Record, Idx);
6194 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006195 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006196 return Context.getAttributedType(kind, modifiedType, equivalentType);
6197 }
6198
6199 case TYPE_PAREN: {
6200 if (Record.size() != 1) {
6201 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006202 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006203 }
6204 QualType InnerType = readType(*Loc.F, Record, Idx);
6205 return Context.getParenType(InnerType);
6206 }
6207
Leonard Chanc72aaf62019-05-07 03:20:17 +00006208 case TYPE_MACRO_QUALIFIED: {
6209 if (Record.size() != 2) {
6210 Error("incorrect encoding of macro defined type");
6211 return QualType();
6212 }
6213 QualType UnderlyingTy = readType(*Loc.F, Record, Idx);
6214 IdentifierInfo *MacroII = GetIdentifierInfo(*Loc.F, Record, Idx);
6215 return Context.getMacroQualifiedType(UnderlyingTy, MacroII);
6216 }
6217
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 case TYPE_PACK_EXPANSION: {
6219 if (Record.size() != 2) {
6220 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006221 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006222 }
6223 QualType Pattern = readType(*Loc.F, Record, Idx);
6224 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006225 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006226 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006227 if (Record[1])
6228 NumExpansions = Record[1] - 1;
6229 return Context.getPackExpansionType(Pattern, NumExpansions);
6230 }
6231
6232 case TYPE_ELABORATED: {
6233 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006234 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6236 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006237 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6238 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 }
6240
6241 case TYPE_OBJC_INTERFACE: {
6242 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006243 ObjCInterfaceDecl *ItfD
6244 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006245 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6246 }
6247
Manman Rene6be26c2016-09-13 17:25:08 +00006248 case TYPE_OBJC_TYPE_PARAM: {
6249 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006250 ObjCTypeParamDecl *Decl
6251 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006252 unsigned NumProtos = Record[Idx++];
6253 SmallVector<ObjCProtocolDecl*, 4> Protos;
6254 for (unsigned I = 0; I != NumProtos; ++I)
6255 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6256 return Context.getObjCTypeParamType(Decl, Protos);
6257 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006258
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 case TYPE_OBJC_OBJECT: {
6260 unsigned Idx = 0;
6261 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006262 unsigned NumTypeArgs = Record[Idx++];
6263 SmallVector<QualType, 4> TypeArgs;
6264 for (unsigned I = 0; I != NumTypeArgs; ++I)
6265 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006266 unsigned NumProtos = Record[Idx++];
6267 SmallVector<ObjCProtocolDecl*, 4> Protos;
6268 for (unsigned I = 0; I != NumProtos; ++I)
6269 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006270 bool IsKindOf = Record[Idx++];
6271 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006272 }
6273
6274 case TYPE_OBJC_OBJECT_POINTER: {
6275 unsigned Idx = 0;
6276 QualType Pointee = readType(*Loc.F, Record, Idx);
6277 return Context.getObjCObjectPointerType(Pointee);
6278 }
6279
6280 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6281 unsigned Idx = 0;
6282 QualType Parm = readType(*Loc.F, Record, Idx);
6283 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006284 return Context.getSubstTemplateTypeParmType(
6285 cast<TemplateTypeParmType>(Parm),
6286 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006287 }
6288
6289 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6290 unsigned Idx = 0;
6291 QualType Parm = readType(*Loc.F, Record, Idx);
6292 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6293 return Context.getSubstTemplateTypeParmPackType(
6294 cast<TemplateTypeParmType>(Parm),
6295 ArgPack);
6296 }
6297
6298 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006299 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006300 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6301 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6302 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006303 const Type *T = nullptr;
6304 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6305 if (const Type *Existing = DI->getTypeForDecl()) {
6306 T = Existing;
6307 break;
6308 }
6309 }
6310 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006311 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006312 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6313 DI->setTypeForDecl(T);
6314 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006315 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 }
6317
6318 case TYPE_TEMPLATE_TYPE_PARM: {
6319 unsigned Idx = 0;
6320 unsigned Depth = Record[Idx++];
6321 unsigned Index = Record[Idx++];
6322 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006323 TemplateTypeParmDecl *D
6324 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6326 }
6327
6328 case TYPE_DEPENDENT_NAME: {
6329 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006330 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006331 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006332 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006333 QualType Canon = readType(*Loc.F, Record, Idx);
6334 if (!Canon.isNull())
6335 Canon = Context.getCanonicalType(Canon);
6336 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6337 }
6338
6339 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6340 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006341 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006343 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006344 unsigned NumArgs = Record[Idx++];
6345 SmallVector<TemplateArgument, 8> Args;
6346 Args.reserve(NumArgs);
6347 while (NumArgs--)
6348 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6349 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006350 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 }
6352
6353 case TYPE_DEPENDENT_SIZED_ARRAY: {
6354 unsigned Idx = 0;
6355
6356 // ArrayType
6357 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006358 ArrayType::ArraySizeModifier ASM
6359 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006360 unsigned IndexTypeQuals = Record[Idx++];
6361
6362 // DependentSizedArrayType
6363 Expr *NumElts = ReadExpr(*Loc.F);
6364 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6365
6366 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6367 IndexTypeQuals, Brackets);
6368 }
6369
6370 case TYPE_TEMPLATE_SPECIALIZATION: {
6371 unsigned Idx = 0;
6372 bool IsDependent = Record[Idx++];
6373 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6374 SmallVector<TemplateArgument, 8> Args;
6375 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6376 QualType Underlying = readType(*Loc.F, Record, Idx);
6377 QualType T;
6378 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006379 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006380 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006381 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6383 return T;
6384 }
6385
6386 case TYPE_ATOMIC: {
6387 if (Record.size() != 1) {
6388 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006389 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 }
6391 QualType ValueType = readType(*Loc.F, Record, Idx);
6392 return Context.getAtomicType(ValueType);
6393 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006394
Joey Goulye3c85de2016-12-01 11:30:49 +00006395 case TYPE_PIPE: {
6396 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006397 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006398 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006399 }
6400
6401 // Reading the pipe element type.
6402 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006403 unsigned ReadOnly = Record[1];
6404 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006405 }
6406
Erich Keanef702b022018-07-13 19:46:04 +00006407 case TYPE_DEPENDENT_SIZED_VECTOR: {
6408 unsigned Idx = 0;
6409 QualType ElementType = readType(*Loc.F, Record, Idx);
6410 Expr *SizeExpr = ReadExpr(*Loc.F);
6411 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6412 unsigned VecKind = Record[Idx];
6413
6414 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6415 (VectorType::VectorKind)VecKind);
6416 }
6417
Alex Lorenz00aee432017-03-22 10:04:48 +00006418 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6419 unsigned Idx = 0;
6420
6421 // DependentSizedExtVectorType
6422 QualType ElementType = readType(*Loc.F, Record, Idx);
6423 Expr *SizeExpr = ReadExpr(*Loc.F);
6424 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6425
6426 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6427 AttrLoc);
6428 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006429
6430 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6431 unsigned Idx = 0;
6432
6433 // DependentAddressSpaceType
6434 QualType PointeeType = readType(*Loc.F, Record, Idx);
6435 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6436 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6437
6438 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6439 AttrLoc);
6440 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 }
6442 llvm_unreachable("Invalid TypeCode!");
6443}
6444
Richard Smith564417a2014-03-20 21:47:22 +00006445void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6446 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006447 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006448 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006449 ExceptionSpecificationType EST =
6450 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006451 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006452 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006453 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006454 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006455 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006456 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006457 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006458 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006459 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6460 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006461 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006462 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006463 }
6464}
6465
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006466namespace clang {
6467
6468class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006469 ModuleFile *F;
6470 ASTReader *Reader;
6471 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006472 unsigned &Idx;
6473
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006474 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006475 return Reader->ReadSourceLocation(*F, Record, Idx);
6476 }
6477
6478 TypeSourceInfo *GetTypeSourceInfo() {
6479 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6480 }
6481
6482 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6483 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006484 }
6485
Richard Smithe43e2b32018-08-20 21:47:29 +00006486 Attr *ReadAttr() {
6487 return Reader->ReadAttr(*F, Record, Idx);
6488 }
6489
Guy Benyei11169dd2012-12-18 14:30:41 +00006490public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006491 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006492 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006493 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006494
6495 // We want compile-time assurance that we've enumerated all of
6496 // these, so unfortunately we have to declare them first, then
6497 // define them out-of-line.
6498#define ABSTRACT_TYPELOC(CLASS, PARENT)
6499#define TYPELOC(CLASS, PARENT) \
6500 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6501#include "clang/AST/TypeLocNodes.def"
6502
6503 void VisitFunctionTypeLoc(FunctionTypeLoc);
6504 void VisitArrayTypeLoc(ArrayTypeLoc);
6505};
6506
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006507} // namespace clang
6508
Guy Benyei11169dd2012-12-18 14:30:41 +00006509void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6510 // nothing to do
6511}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006512
Guy Benyei11169dd2012-12-18 14:30:41 +00006513void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006514 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006515 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006516 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6517 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6518 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6519 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006520 }
6521}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006522
Guy Benyei11169dd2012-12-18 14:30:41 +00006523void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006524 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006525}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006526
Guy Benyei11169dd2012-12-18 14:30:41 +00006527void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006528 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006529}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006530
Reid Kleckner8a365022013-06-24 17:51:48 +00006531void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6532 // nothing to do
6533}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006534
Reid Kleckner0503a872013-12-05 01:23:43 +00006535void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6536 // nothing to do
6537}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006538
Leonard Chanc72aaf62019-05-07 03:20:17 +00006539void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6540 TL.setExpansionLoc(ReadSourceLocation());
6541}
6542
Guy Benyei11169dd2012-12-18 14:30:41 +00006543void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006544 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006545}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006546
Guy Benyei11169dd2012-12-18 14:30:41 +00006547void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006548 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006549}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006550
Guy Benyei11169dd2012-12-18 14:30:41 +00006551void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006552 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006553}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006554
Guy Benyei11169dd2012-12-18 14:30:41 +00006555void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006556 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006557 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006558}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006559
Guy Benyei11169dd2012-12-18 14:30:41 +00006560void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006561 TL.setLBracketLoc(ReadSourceLocation());
6562 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006563 if (Record[Idx++])
6564 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006565 else
Craig Toppera13603a2014-05-22 05:54:18 +00006566 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006567}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006568
Guy Benyei11169dd2012-12-18 14:30:41 +00006569void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6570 VisitArrayTypeLoc(TL);
6571}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006572
Guy Benyei11169dd2012-12-18 14:30:41 +00006573void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6574 VisitArrayTypeLoc(TL);
6575}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006576
Guy Benyei11169dd2012-12-18 14:30:41 +00006577void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6578 VisitArrayTypeLoc(TL);
6579}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006580
Guy Benyei11169dd2012-12-18 14:30:41 +00006581void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6582 DependentSizedArrayTypeLoc TL) {
6583 VisitArrayTypeLoc(TL);
6584}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006585
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006586void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6587 DependentAddressSpaceTypeLoc TL) {
6588
6589 TL.setAttrNameLoc(ReadSourceLocation());
6590 SourceRange range;
6591 range.setBegin(ReadSourceLocation());
6592 range.setEnd(ReadSourceLocation());
6593 TL.setAttrOperandParensRange(range);
6594 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6595}
6596
Guy Benyei11169dd2012-12-18 14:30:41 +00006597void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6598 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006599 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006600}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006601
Guy Benyei11169dd2012-12-18 14:30:41 +00006602void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006603 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006604}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006605
Erich Keanef702b022018-07-13 19:46:04 +00006606void TypeLocReader::VisitDependentVectorTypeLoc(
6607 DependentVectorTypeLoc TL) {
6608 TL.setNameLoc(ReadSourceLocation());
6609}
6610
Guy Benyei11169dd2012-12-18 14:30:41 +00006611void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006612 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006613}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006614
Guy Benyei11169dd2012-12-18 14:30:41 +00006615void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006616 TL.setLocalRangeBegin(ReadSourceLocation());
6617 TL.setLParenLoc(ReadSourceLocation());
6618 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006619 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6620 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006621 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006622 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006623 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006624 }
6625}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006626
Guy Benyei11169dd2012-12-18 14:30:41 +00006627void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6628 VisitFunctionTypeLoc(TL);
6629}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006630
Guy Benyei11169dd2012-12-18 14:30:41 +00006631void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6632 VisitFunctionTypeLoc(TL);
6633}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006634
Guy Benyei11169dd2012-12-18 14:30:41 +00006635void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006636 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006637}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006638
Guy Benyei11169dd2012-12-18 14:30:41 +00006639void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006640 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006641}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006644 TL.setTypeofLoc(ReadSourceLocation());
6645 TL.setLParenLoc(ReadSourceLocation());
6646 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006647}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006648
Guy Benyei11169dd2012-12-18 14:30:41 +00006649void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006650 TL.setTypeofLoc(ReadSourceLocation());
6651 TL.setLParenLoc(ReadSourceLocation());
6652 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006653 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006654}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006655
Guy Benyei11169dd2012-12-18 14:30:41 +00006656void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006657 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006658}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006659
Guy Benyei11169dd2012-12-18 14:30:41 +00006660void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006661 TL.setKWLoc(ReadSourceLocation());
6662 TL.setLParenLoc(ReadSourceLocation());
6663 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006664 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006665}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006666
Guy Benyei11169dd2012-12-18 14:30:41 +00006667void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006668 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006669}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006670
Richard Smith600b5262017-01-26 20:40:47 +00006671void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6672 DeducedTemplateSpecializationTypeLoc TL) {
6673 TL.setTemplateNameLoc(ReadSourceLocation());
6674}
6675
Guy Benyei11169dd2012-12-18 14:30:41 +00006676void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006677 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006678}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006679
Guy Benyei11169dd2012-12-18 14:30:41 +00006680void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006681 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006682}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006683
Guy Benyei11169dd2012-12-18 14:30:41 +00006684void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006685 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006686}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006687
Guy Benyei11169dd2012-12-18 14:30:41 +00006688void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006689 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006690}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006691
Guy Benyei11169dd2012-12-18 14:30:41 +00006692void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6693 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006694 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006695}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006696
Guy Benyei11169dd2012-12-18 14:30:41 +00006697void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6698 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006699 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006700}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006701
Guy Benyei11169dd2012-12-18 14:30:41 +00006702void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6703 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006704 TL.setTemplateKeywordLoc(ReadSourceLocation());
6705 TL.setTemplateNameLoc(ReadSourceLocation());
6706 TL.setLAngleLoc(ReadSourceLocation());
6707 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006708 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006709 TL.setArgLocInfo(
6710 i,
6711 Reader->GetTemplateArgumentLocInfo(
6712 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006713}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006714
Guy Benyei11169dd2012-12-18 14:30:41 +00006715void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006716 TL.setLParenLoc(ReadSourceLocation());
6717 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006718}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006719
Guy Benyei11169dd2012-12-18 14:30:41 +00006720void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006721 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006722 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006723}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006724
Guy Benyei11169dd2012-12-18 14:30:41 +00006725void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006726 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006727}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006728
Guy Benyei11169dd2012-12-18 14:30:41 +00006729void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006730 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006731 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006732 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006733}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006734
Guy Benyei11169dd2012-12-18 14:30:41 +00006735void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6736 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006737 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006738 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006739 TL.setTemplateKeywordLoc(ReadSourceLocation());
6740 TL.setTemplateNameLoc(ReadSourceLocation());
6741 TL.setLAngleLoc(ReadSourceLocation());
6742 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006744 TL.setArgLocInfo(
6745 I,
6746 Reader->GetTemplateArgumentLocInfo(
6747 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006748}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006751 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006752}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006753
Guy Benyei11169dd2012-12-18 14:30:41 +00006754void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006755 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006756}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006757
Manman Rene6be26c2016-09-13 17:25:08 +00006758void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6759 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006760 TL.setProtocolLAngleLoc(ReadSourceLocation());
6761 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006762 }
6763 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006764 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006765}
6766
Guy Benyei11169dd2012-12-18 14:30:41 +00006767void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006768 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006769 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6770 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006771 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006772 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006773 TL.setProtocolLAngleLoc(ReadSourceLocation());
6774 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006775 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006776 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006777}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006778
Guy Benyei11169dd2012-12-18 14:30:41 +00006779void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006780 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006781}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006782
Guy Benyei11169dd2012-12-18 14:30:41 +00006783void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006784 TL.setKWLoc(ReadSourceLocation());
6785 TL.setLParenLoc(ReadSourceLocation());
6786 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006787}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006788
Xiuli Pan9c14e282016-01-09 12:53:17 +00006789void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006790 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006791}
Guy Benyei11169dd2012-12-18 14:30:41 +00006792
Richard Smithc23d7342018-06-29 20:46:25 +00006793void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
6794 unsigned &Idx, TypeLoc TL) {
6795 TypeLocReader TLR(F, *this, Record, Idx);
6796 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6797 TLR.Visit(TL);
6798}
6799
David L. Jonesbe1557a2016-12-21 00:17:49 +00006800TypeSourceInfo *
6801ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6802 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006803 QualType InfoTy = readType(F, Record, Idx);
6804 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006805 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006806
6807 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00006808 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006809 return TInfo;
6810}
6811
6812QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006813 assert(ContextObj && "reading type with no AST context");
6814 ASTContext &Context = *ContextObj;
6815
Guy Benyei11169dd2012-12-18 14:30:41 +00006816 unsigned FastQuals = ID & Qualifiers::FastMask;
6817 unsigned Index = ID >> Qualifiers::FastWidth;
6818
6819 if (Index < NUM_PREDEF_TYPE_IDS) {
6820 QualType T;
6821 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006822 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006823 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006824 case PREDEF_TYPE_VOID_ID:
6825 T = Context.VoidTy;
6826 break;
6827 case PREDEF_TYPE_BOOL_ID:
6828 T = Context.BoolTy;
6829 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006830 case PREDEF_TYPE_CHAR_U_ID:
6831 case PREDEF_TYPE_CHAR_S_ID:
6832 // FIXME: Check that the signedness of CharTy is correct!
6833 T = Context.CharTy;
6834 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006835 case PREDEF_TYPE_UCHAR_ID:
6836 T = Context.UnsignedCharTy;
6837 break;
6838 case PREDEF_TYPE_USHORT_ID:
6839 T = Context.UnsignedShortTy;
6840 break;
6841 case PREDEF_TYPE_UINT_ID:
6842 T = Context.UnsignedIntTy;
6843 break;
6844 case PREDEF_TYPE_ULONG_ID:
6845 T = Context.UnsignedLongTy;
6846 break;
6847 case PREDEF_TYPE_ULONGLONG_ID:
6848 T = Context.UnsignedLongLongTy;
6849 break;
6850 case PREDEF_TYPE_UINT128_ID:
6851 T = Context.UnsignedInt128Ty;
6852 break;
6853 case PREDEF_TYPE_SCHAR_ID:
6854 T = Context.SignedCharTy;
6855 break;
6856 case PREDEF_TYPE_WCHAR_ID:
6857 T = Context.WCharTy;
6858 break;
6859 case PREDEF_TYPE_SHORT_ID:
6860 T = Context.ShortTy;
6861 break;
6862 case PREDEF_TYPE_INT_ID:
6863 T = Context.IntTy;
6864 break;
6865 case PREDEF_TYPE_LONG_ID:
6866 T = Context.LongTy;
6867 break;
6868 case PREDEF_TYPE_LONGLONG_ID:
6869 T = Context.LongLongTy;
6870 break;
6871 case PREDEF_TYPE_INT128_ID:
6872 T = Context.Int128Ty;
6873 break;
6874 case PREDEF_TYPE_HALF_ID:
6875 T = Context.HalfTy;
6876 break;
6877 case PREDEF_TYPE_FLOAT_ID:
6878 T = Context.FloatTy;
6879 break;
6880 case PREDEF_TYPE_DOUBLE_ID:
6881 T = Context.DoubleTy;
6882 break;
6883 case PREDEF_TYPE_LONGDOUBLE_ID:
6884 T = Context.LongDoubleTy;
6885 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006886 case PREDEF_TYPE_SHORT_ACCUM_ID:
6887 T = Context.ShortAccumTy;
6888 break;
6889 case PREDEF_TYPE_ACCUM_ID:
6890 T = Context.AccumTy;
6891 break;
6892 case PREDEF_TYPE_LONG_ACCUM_ID:
6893 T = Context.LongAccumTy;
6894 break;
6895 case PREDEF_TYPE_USHORT_ACCUM_ID:
6896 T = Context.UnsignedShortAccumTy;
6897 break;
6898 case PREDEF_TYPE_UACCUM_ID:
6899 T = Context.UnsignedAccumTy;
6900 break;
6901 case PREDEF_TYPE_ULONG_ACCUM_ID:
6902 T = Context.UnsignedLongAccumTy;
6903 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006904 case PREDEF_TYPE_SHORT_FRACT_ID:
6905 T = Context.ShortFractTy;
6906 break;
6907 case PREDEF_TYPE_FRACT_ID:
6908 T = Context.FractTy;
6909 break;
6910 case PREDEF_TYPE_LONG_FRACT_ID:
6911 T = Context.LongFractTy;
6912 break;
6913 case PREDEF_TYPE_USHORT_FRACT_ID:
6914 T = Context.UnsignedShortFractTy;
6915 break;
6916 case PREDEF_TYPE_UFRACT_ID:
6917 T = Context.UnsignedFractTy;
6918 break;
6919 case PREDEF_TYPE_ULONG_FRACT_ID:
6920 T = Context.UnsignedLongFractTy;
6921 break;
6922 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6923 T = Context.SatShortAccumTy;
6924 break;
6925 case PREDEF_TYPE_SAT_ACCUM_ID:
6926 T = Context.SatAccumTy;
6927 break;
6928 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6929 T = Context.SatLongAccumTy;
6930 break;
6931 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6932 T = Context.SatUnsignedShortAccumTy;
6933 break;
6934 case PREDEF_TYPE_SAT_UACCUM_ID:
6935 T = Context.SatUnsignedAccumTy;
6936 break;
6937 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6938 T = Context.SatUnsignedLongAccumTy;
6939 break;
6940 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6941 T = Context.SatShortFractTy;
6942 break;
6943 case PREDEF_TYPE_SAT_FRACT_ID:
6944 T = Context.SatFractTy;
6945 break;
6946 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6947 T = Context.SatLongFractTy;
6948 break;
6949 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6950 T = Context.SatUnsignedShortFractTy;
6951 break;
6952 case PREDEF_TYPE_SAT_UFRACT_ID:
6953 T = Context.SatUnsignedFractTy;
6954 break;
6955 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6956 T = Context.SatUnsignedLongFractTy;
6957 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006958 case PREDEF_TYPE_FLOAT16_ID:
6959 T = Context.Float16Ty;
6960 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006961 case PREDEF_TYPE_FLOAT128_ID:
6962 T = Context.Float128Ty;
6963 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006964 case PREDEF_TYPE_OVERLOAD_ID:
6965 T = Context.OverloadTy;
6966 break;
6967 case PREDEF_TYPE_BOUND_MEMBER:
6968 T = Context.BoundMemberTy;
6969 break;
6970 case PREDEF_TYPE_PSEUDO_OBJECT:
6971 T = Context.PseudoObjectTy;
6972 break;
6973 case PREDEF_TYPE_DEPENDENT_ID:
6974 T = Context.DependentTy;
6975 break;
6976 case PREDEF_TYPE_UNKNOWN_ANY:
6977 T = Context.UnknownAnyTy;
6978 break;
6979 case PREDEF_TYPE_NULLPTR_ID:
6980 T = Context.NullPtrTy;
6981 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006982 case PREDEF_TYPE_CHAR8_ID:
6983 T = Context.Char8Ty;
6984 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006985 case PREDEF_TYPE_CHAR16_ID:
6986 T = Context.Char16Ty;
6987 break;
6988 case PREDEF_TYPE_CHAR32_ID:
6989 T = Context.Char32Ty;
6990 break;
6991 case PREDEF_TYPE_OBJC_ID:
6992 T = Context.ObjCBuiltinIdTy;
6993 break;
6994 case PREDEF_TYPE_OBJC_CLASS:
6995 T = Context.ObjCBuiltinClassTy;
6996 break;
6997 case PREDEF_TYPE_OBJC_SEL:
6998 T = Context.ObjCBuiltinSelTy;
6999 break;
Alexey Bader954ba212016-04-08 13:40:33 +00007000#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7001 case PREDEF_TYPE_##Id##_ID: \
7002 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00007003 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00007004#include "clang/Basic/OpenCLImageTypes.def"
Andrew Savonichev3fee3512018-11-08 11:25:41 +00007005#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7006 case PREDEF_TYPE_##Id##_ID: \
7007 T = Context.Id##Ty; \
7008 break;
7009#include "clang/Basic/OpenCLExtensionTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00007010 case PREDEF_TYPE_SAMPLER_ID:
7011 T = Context.OCLSamplerTy;
7012 break;
7013 case PREDEF_TYPE_EVENT_ID:
7014 T = Context.OCLEventTy;
7015 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007016 case PREDEF_TYPE_CLK_EVENT_ID:
7017 T = Context.OCLClkEventTy;
7018 break;
7019 case PREDEF_TYPE_QUEUE_ID:
7020 T = Context.OCLQueueTy;
7021 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00007022 case PREDEF_TYPE_RESERVE_ID_ID:
7023 T = Context.OCLReserveIDTy;
7024 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007025 case PREDEF_TYPE_AUTO_DEDUCT:
7026 T = Context.getAutoDeductType();
7027 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00007028 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
7029 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007031 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
7032 T = Context.ARCUnbridgedCastTy;
7033 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007034 case PREDEF_TYPE_BUILTIN_FN:
7035 T = Context.BuiltinFnTy;
7036 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00007037 case PREDEF_TYPE_OMP_ARRAY_SECTION:
7038 T = Context.OMPArraySectionTy;
7039 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00007040 }
7041
7042 assert(!T.isNull() && "Unknown predefined type");
7043 return T.withFastQualifiers(FastQuals);
7044 }
7045
7046 Index -= NUM_PREDEF_TYPE_IDS;
7047 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7048 if (TypesLoaded[Index].isNull()) {
7049 TypesLoaded[Index] = readTypeRecord(Index);
7050 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007051 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007052
7053 TypesLoaded[Index]->setFromAST();
7054 if (DeserializationListener)
7055 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7056 TypesLoaded[Index]);
7057 }
7058
7059 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7060}
7061
7062QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7063 return GetType(getGlobalTypeID(F, LocalID));
7064}
7065
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007066serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007067ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7068 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7069 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007070
Guy Benyei11169dd2012-12-18 14:30:41 +00007071 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7072 return LocalID;
7073
Richard Smith37a93df2017-02-18 00:32:02 +00007074 if (!F.ModuleOffsetMap.empty())
7075 ReadModuleOffsetMap(F);
7076
Guy Benyei11169dd2012-12-18 14:30:41 +00007077 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7078 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7079 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007080
Guy Benyei11169dd2012-12-18 14:30:41 +00007081 unsigned GlobalIndex = LocalIndex + I->second;
7082 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7083}
7084
7085TemplateArgumentLocInfo
7086ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7087 TemplateArgument::ArgKind Kind,
7088 const RecordData &Record,
7089 unsigned &Index) {
7090 switch (Kind) {
7091 case TemplateArgument::Expression:
7092 return ReadExpr(F);
7093 case TemplateArgument::Type:
7094 return GetTypeSourceInfo(F, Record, Index);
7095 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007096 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 Index);
7098 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7099 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7100 SourceLocation());
7101 }
7102 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007103 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 Index);
7105 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7106 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007107 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007108 EllipsisLoc);
7109 }
7110 case TemplateArgument::Null:
7111 case TemplateArgument::Integral:
7112 case TemplateArgument::Declaration:
7113 case TemplateArgument::NullPtr:
7114 case TemplateArgument::Pack:
7115 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007116 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007117 }
7118 llvm_unreachable("unexpected template argument loc");
7119}
7120
7121TemplateArgumentLoc
7122ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7123 const RecordData &Record, unsigned &Index) {
7124 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7125
7126 if (Arg.getKind() == TemplateArgument::Expression) {
7127 if (Record[Index++]) // bool InfoHasSameExpr.
7128 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7129 }
7130 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7131 Record, Index));
7132}
7133
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007134const ASTTemplateArgumentListInfo*
7135ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7136 const RecordData &Record,
7137 unsigned &Index) {
7138 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7139 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7140 unsigned NumArgsAsWritten = Record[Index++];
7141 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7142 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7143 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7144 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7145}
7146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7148 return GetDecl(ID);
7149}
7150
Richard Smith053f6c62014-05-16 23:01:30 +00007151void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007152 if (NumCurrentElementsDeserializing) {
7153 // We arrange to not care about the complete redeclaration chain while we're
7154 // deserializing. Just remember that the AST has marked this one as complete
7155 // but that it's not actually complete yet, so we know we still need to
7156 // complete it later.
7157 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7158 return;
7159 }
7160
Richard Smith053f6c62014-05-16 23:01:30 +00007161 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7162
Richard Smith053f6c62014-05-16 23:01:30 +00007163 // If this is a named declaration, complete it by looking it up
7164 // within its context.
7165 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007166 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007167 // all mergeable entities within it.
7168 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7169 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7170 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007171 if (!getContext().getLangOpts().CPlusPlus &&
7172 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007173 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007174 // the identifier instead. (For C++ modules, we don't store decls
7175 // in the serialized identifier table, so we do the lookup in the TU.)
7176 auto *II = Name.getAsIdentifierInfo();
7177 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007178 if (II->isOutOfDate())
7179 updateOutOfDateIdentifier(*II);
7180 } else
7181 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007182 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007183 // Find all declarations of this kind from the relevant context.
7184 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7185 auto *DC = cast<DeclContext>(DCDecl);
7186 SmallVector<Decl*, 8> Decls;
7187 FindExternalLexicalDecls(
7188 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7189 }
Richard Smith053f6c62014-05-16 23:01:30 +00007190 }
7191 }
Richard Smith50895422015-01-31 03:04:55 +00007192
7193 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7194 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7195 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7196 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7197 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7198 if (auto *Template = FD->getPrimaryTemplate())
7199 Template->LoadLazySpecializations();
7200 }
Richard Smith053f6c62014-05-16 23:01:30 +00007201}
7202
Richard Smithc2bb8182015-03-24 06:36:48 +00007203CXXCtorInitializer **
7204ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7205 RecordLocation Loc = getLocalBitOffset(Offset);
7206 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7207 SavedStreamPosition SavedPosition(Cursor);
7208 Cursor.JumpToBit(Loc.Offset);
7209 ReadingKindTracker ReadingKind(Read_Decl, *this);
7210
7211 RecordData Record;
7212 unsigned Code = Cursor.ReadCode();
7213 unsigned RecCode = Cursor.readRecord(Code, Record);
7214 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7215 Error("malformed AST file: missing C++ ctor initializers");
7216 return nullptr;
7217 }
7218
7219 unsigned Idx = 0;
7220 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7221}
7222
Guy Benyei11169dd2012-12-18 14:30:41 +00007223CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007224 assert(ContextObj && "reading base specifiers with no AST context");
7225 ASTContext &Context = *ContextObj;
7226
Guy Benyei11169dd2012-12-18 14:30:41 +00007227 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007228 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007229 SavedStreamPosition SavedPosition(Cursor);
7230 Cursor.JumpToBit(Loc.Offset);
7231 ReadingKindTracker ReadingKind(Read_Decl, *this);
7232 RecordData Record;
7233 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007234 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007235 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007236 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007237 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007238 }
7239
7240 unsigned Idx = 0;
7241 unsigned NumBases = Record[Idx++];
7242 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007243 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 for (unsigned I = 0; I != NumBases; ++I)
7245 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7246 return Bases;
7247}
7248
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007249serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007250ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7251 if (LocalID < NUM_PREDEF_DECL_IDS)
7252 return LocalID;
7253
Richard Smith37a93df2017-02-18 00:32:02 +00007254 if (!F.ModuleOffsetMap.empty())
7255 ReadModuleOffsetMap(F);
7256
Guy Benyei11169dd2012-12-18 14:30:41 +00007257 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7258 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7259 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007260
Guy Benyei11169dd2012-12-18 14:30:41 +00007261 return LocalID + I->second;
7262}
7263
7264bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7265 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007266 // Predefined decls aren't from any module.
7267 if (ID < NUM_PREDEF_DECL_IDS)
7268 return false;
7269
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007270 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007271 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007272}
7273
Douglas Gregor9f782892013-01-21 15:25:38 +00007274ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007276 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007277 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7278 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7279 return I->second;
7280}
7281
7282SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7283 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007284 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007285
Guy Benyei11169dd2012-12-18 14:30:41 +00007286 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7287
7288 if (Index > DeclsLoaded.size()) {
7289 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007290 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007291 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007292
Guy Benyei11169dd2012-12-18 14:30:41 +00007293 if (Decl *D = DeclsLoaded[Index])
7294 return D->getLocation();
7295
Richard Smithcb34bd32016-03-27 07:28:06 +00007296 SourceLocation Loc;
7297 DeclCursorForID(ID, Loc);
7298 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007299}
7300
Richard Smithfe620d22015-03-05 23:24:12 +00007301static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7302 switch (ID) {
7303 case PREDEF_DECL_NULL_ID:
7304 return nullptr;
7305
7306 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7307 return Context.getTranslationUnitDecl();
7308
7309 case PREDEF_DECL_OBJC_ID_ID:
7310 return Context.getObjCIdDecl();
7311
7312 case PREDEF_DECL_OBJC_SEL_ID:
7313 return Context.getObjCSelDecl();
7314
7315 case PREDEF_DECL_OBJC_CLASS_ID:
7316 return Context.getObjCClassDecl();
7317
7318 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7319 return Context.getObjCProtocolDecl();
7320
7321 case PREDEF_DECL_INT_128_ID:
7322 return Context.getInt128Decl();
7323
7324 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7325 return Context.getUInt128Decl();
7326
7327 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7328 return Context.getObjCInstanceTypeDecl();
7329
7330 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7331 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007332
Richard Smith9b88a4c2015-07-27 05:40:23 +00007333 case PREDEF_DECL_VA_LIST_TAG:
7334 return Context.getVaListTagDecl();
7335
Charles Davisc7d5c942015-09-17 20:55:33 +00007336 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7337 return Context.getBuiltinMSVaListDecl();
7338
Richard Smithf19e1272015-03-07 00:04:49 +00007339 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7340 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007341
7342 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7343 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007344
7345 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7346 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007347
7348 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7349 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007350
7351 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7352 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007353 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007354 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007355}
7356
Richard Smithcd45dbc2014-04-19 03:48:30 +00007357Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007358 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007359 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007360 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007361 if (D) {
7362 // Track that we have merged the declaration with ID \p ID into the
7363 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007364 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007365 if (Merged.empty())
7366 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007367 }
Richard Smithfe620d22015-03-05 23:24:12 +00007368 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007369 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007370
Guy Benyei11169dd2012-12-18 14:30:41 +00007371 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7372
7373 if (Index >= DeclsLoaded.size()) {
7374 assert(0 && "declaration ID out-of-range for AST file");
7375 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007376 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007378
7379 return DeclsLoaded[Index];
7380}
7381
7382Decl *ASTReader::GetDecl(DeclID ID) {
7383 if (ID < NUM_PREDEF_DECL_IDS)
7384 return GetExistingDecl(ID);
7385
7386 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7387
7388 if (Index >= DeclsLoaded.size()) {
7389 assert(0 && "declaration ID out-of-range for AST file");
7390 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007391 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007392 }
7393
Guy Benyei11169dd2012-12-18 14:30:41 +00007394 if (!DeclsLoaded[Index]) {
7395 ReadDeclRecord(ID);
7396 if (DeserializationListener)
7397 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7398 }
7399
7400 return DeclsLoaded[Index];
7401}
7402
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007403DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007404 DeclID GlobalID) {
7405 if (GlobalID < NUM_PREDEF_DECL_IDS)
7406 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007407
Guy Benyei11169dd2012-12-18 14:30:41 +00007408 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7409 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7410 ModuleFile *Owner = I->second;
7411
7412 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7413 = M.GlobalToLocalDeclIDs.find(Owner);
7414 if (Pos == M.GlobalToLocalDeclIDs.end())
7415 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007416
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 return GlobalID - Owner->BaseDeclID + Pos->second;
7418}
7419
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007420serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 const RecordData &Record,
7422 unsigned &Idx) {
7423 if (Idx >= Record.size()) {
7424 Error("Corrupted AST file");
7425 return 0;
7426 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007427
Guy Benyei11169dd2012-12-18 14:30:41 +00007428 return getGlobalDeclID(F, Record[Idx++]);
7429}
7430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007431/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007432///
7433/// This operation will read a new statement from the external
7434/// source each time it is called, and is meant to be used via a
7435/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7436Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7437 // Switch case IDs are per Decl.
7438 ClearSwitchCaseIDs();
7439
7440 // Offset here is a global offset across the entire chain.
7441 RecordLocation Loc = getLocalBitOffset(Offset);
7442 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007443 assert(NumCurrentElementsDeserializing == 0 &&
7444 "should not be called while already deserializing");
7445 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 return ReadStmtFromStream(*Loc.F);
7447}
7448
Richard Smith3cb15722015-08-05 22:41:45 +00007449void ASTReader::FindExternalLexicalDecls(
7450 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7451 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007452 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7453
Richard Smith9ccdd932015-08-06 22:14:12 +00007454 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007455 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7456 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7457 auto K = (Decl::Kind)+LexicalDecls[I];
7458 if (!IsKindWeWant(K))
7459 continue;
7460
7461 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7462
7463 // Don't add predefined declarations to the lexical context more
7464 // than once.
7465 if (ID < NUM_PREDEF_DECL_IDS) {
7466 if (PredefsVisited[ID])
7467 continue;
7468
7469 PredefsVisited[ID] = true;
7470 }
7471
7472 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007473 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007474 if (!DC->isDeclInLexicalTraversal(D))
7475 Decls.push_back(D);
7476 }
7477 }
7478 };
7479
7480 if (isa<TranslationUnitDecl>(DC)) {
7481 for (auto Lexical : TULexicalDecls)
7482 Visit(Lexical.first, Lexical.second);
7483 } else {
7484 auto I = LexicalDecls.find(DC);
7485 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007486 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007487 }
7488
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007490}
7491
7492namespace {
7493
7494class DeclIDComp {
7495 ASTReader &Reader;
7496 ModuleFile &Mod;
7497
7498public:
7499 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7500
7501 bool operator()(LocalDeclID L, LocalDeclID R) const {
7502 SourceLocation LHS = getLocation(L);
7503 SourceLocation RHS = getLocation(R);
7504 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7505 }
7506
7507 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7508 SourceLocation RHS = getLocation(R);
7509 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7510 }
7511
7512 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7513 SourceLocation LHS = getLocation(L);
7514 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7515 }
7516
7517 SourceLocation getLocation(LocalDeclID ID) const {
7518 return Reader.getSourceManager().getFileLoc(
7519 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7520 }
7521};
7522
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007523} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007524
7525void ASTReader::FindFileRegionDecls(FileID File,
7526 unsigned Offset, unsigned Length,
7527 SmallVectorImpl<Decl *> &Decls) {
7528 SourceManager &SM = getSourceManager();
7529
7530 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7531 if (I == FileDeclIDs.end())
7532 return;
7533
7534 FileDeclsInfo &DInfo = I->second;
7535 if (DInfo.Decls.empty())
7536 return;
7537
7538 SourceLocation
7539 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7540 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7541
7542 DeclIDComp DIDComp(*this, *DInfo.Mod);
7543 ArrayRef<serialization::LocalDeclID>::iterator
7544 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7545 BeginLoc, DIDComp);
7546 if (BeginIt != DInfo.Decls.begin())
7547 --BeginIt;
7548
7549 // If we are pointing at a top-level decl inside an objc container, we need
7550 // to backtrack until we find it otherwise we will fail to report that the
7551 // region overlaps with an objc container.
7552 while (BeginIt != DInfo.Decls.begin() &&
7553 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7554 ->isTopLevelDeclInObjCContainer())
7555 --BeginIt;
7556
7557 ArrayRef<serialization::LocalDeclID>::iterator
7558 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7559 EndLoc, DIDComp);
7560 if (EndIt != DInfo.Decls.end())
7561 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007562
Guy Benyei11169dd2012-12-18 14:30:41 +00007563 for (ArrayRef<serialization::LocalDeclID>::iterator
7564 DIt = BeginIt; DIt != EndIt; ++DIt)
7565 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7566}
7567
Richard Smith9ce12e32013-02-07 03:30:24 +00007568bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007569ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7570 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007571 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007572 "DeclContext has no visible decls in storage");
7573 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007574 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007575
Richard Smithd88a7f12015-09-01 20:35:42 +00007576 auto It = Lookups.find(DC);
7577 if (It == Lookups.end())
7578 return false;
7579
Richard Smith8c913ec2014-08-14 02:21:01 +00007580 Deserializing LookupResults(this);
7581
Richard Smithd88a7f12015-09-01 20:35:42 +00007582 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007583 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007584 for (DeclID ID : It->second.Table.find(Name)) {
7585 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007586 if (ND->getDeclName() == Name)
7587 Decls.push_back(ND);
7588 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007589
Guy Benyei11169dd2012-12-18 14:30:41 +00007590 ++NumVisibleDeclContextsRead;
7591 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007592 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007593}
7594
Guy Benyei11169dd2012-12-18 14:30:41 +00007595void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7596 if (!DC->hasExternalVisibleStorage())
7597 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007598
7599 auto It = Lookups.find(DC);
7600 assert(It != Lookups.end() &&
7601 "have external visible storage but no lookup tables");
7602
Craig Topper79be4cd2013-07-05 04:33:53 +00007603 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007604
Vedant Kumar48b4f762018-04-14 01:40:48 +00007605 for (DeclID ID : It->second.Table.findAll()) {
7606 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007607 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007608 }
7609
Guy Benyei11169dd2012-12-18 14:30:41 +00007610 ++NumVisibleDeclContextsRead;
7611
Vedant Kumar48b4f762018-04-14 01:40:48 +00007612 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7613 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7614 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007615 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7616}
7617
Richard Smithd88a7f12015-09-01 20:35:42 +00007618const serialization::reader::DeclContextLookupTable *
7619ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7620 auto I = Lookups.find(Primary);
7621 return I == Lookups.end() ? nullptr : &I->second;
7622}
7623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007624/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007625/// before receiving the implementation, and codegen depends on this.
7626/// We simulate this by deserializing and passing to consumer the methods of the
7627/// implementation before passing the deserialized implementation decl.
7628static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7629 ASTConsumer *Consumer) {
7630 assert(ImplD && Consumer);
7631
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007632 for (auto *I : ImplD->methods())
7633 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007634
7635 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7636}
7637
Guy Benyei11169dd2012-12-18 14:30:41 +00007638void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007639 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007640 PassObjCImplDeclToConsumer(ImplD, Consumer);
7641 else
7642 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7643}
7644
7645void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7646 this->Consumer = Consumer;
7647
Richard Smith9e2341d2015-03-23 03:25:59 +00007648 if (Consumer)
7649 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007650
7651 if (DeserializationListener)
7652 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007653}
7654
7655void ASTReader::PrintStats() {
7656 std::fprintf(stderr, "*** AST File Statistics:\n");
7657
7658 unsigned NumTypesLoaded
7659 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7660 QualType());
7661 unsigned NumDeclsLoaded
7662 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007663 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007664 unsigned NumIdentifiersLoaded
7665 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7666 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007667 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007668 unsigned NumMacrosLoaded
7669 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7670 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007671 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007672 unsigned NumSelectorsLoaded
7673 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7674 SelectorsLoaded.end(),
7675 Selector());
7676
7677 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7678 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7679 NumSLocEntriesRead, TotalNumSLocEntries,
7680 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7681 if (!TypesLoaded.empty())
7682 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7683 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7684 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7685 if (!DeclsLoaded.empty())
7686 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7687 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7688 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7689 if (!IdentifiersLoaded.empty())
7690 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7691 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7692 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7693 if (!MacrosLoaded.empty())
7694 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7695 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7696 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7697 if (!SelectorsLoaded.empty())
7698 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7699 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7700 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7701 if (TotalNumStatements)
7702 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7703 NumStatementsRead, TotalNumStatements,
7704 ((float)NumStatementsRead/TotalNumStatements * 100));
7705 if (TotalNumMacros)
7706 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7707 NumMacrosRead, TotalNumMacros,
7708 ((float)NumMacrosRead/TotalNumMacros * 100));
7709 if (TotalLexicalDeclContexts)
7710 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7711 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7712 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7713 * 100));
7714 if (TotalVisibleDeclContexts)
7715 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7716 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7717 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7718 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007719 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007720 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7721 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7722 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7723 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007724 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007725 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7726 NumMethodPoolHits, NumMethodPoolLookups,
7727 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007728 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007729 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7730 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7731 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7732 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007733 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007734 std::fprintf(stderr,
7735 " %u / %u identifier table lookups succeeded (%f%%)\n",
7736 NumIdentifierLookupHits, NumIdentifierLookups,
7737 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007738
Douglas Gregore060e572013-01-25 01:03:03 +00007739 if (GlobalIndex) {
7740 std::fprintf(stderr, "\n");
7741 GlobalIndex->printStats();
7742 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007743
Guy Benyei11169dd2012-12-18 14:30:41 +00007744 std::fprintf(stderr, "\n");
7745 dump();
7746 std::fprintf(stderr, "\n");
7747}
7748
7749template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007750LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007751dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007752 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007753 InitialCapacity> &Map) {
7754 if (Map.begin() == Map.end())
7755 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007756
Vedant Kumar48b4f762018-04-14 01:40:48 +00007757 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7758
Guy Benyei11169dd2012-12-18 14:30:41 +00007759 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007760 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7761 I != IEnd; ++I) {
7762 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7763 << "\n";
7764 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007765}
7766
Yaron Kerencdae9412016-01-29 19:38:18 +00007767LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7769 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7770 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7771 dumpModuleIDMap("Global type map", GlobalTypeMap);
7772 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7773 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7774 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7775 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7776 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007777 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007778 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007779
Guy Benyei11169dd2012-12-18 14:30:41 +00007780 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007781 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007782 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007783}
7784
7785/// Return the amount of memory used by memory buffers, breaking down
7786/// by heap-backed versus mmap'ed memory.
7787void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007788 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007789 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 size_t bytes = buf->getBufferSize();
7791 switch (buf->getBufferKind()) {
7792 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7793 sizes.malloc_bytes += bytes;
7794 break;
7795 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7796 sizes.mmap_bytes += bytes;
7797 break;
7798 }
7799 }
7800 }
7801}
7802
7803void ASTReader::InitializeSema(Sema &S) {
7804 SemaObj = &S;
7805 S.addExternalSource(this);
7806
7807 // Makes sure any declarations that were deserialized "too early"
7808 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007809 for (uint64_t ID : PreloadedDeclIDs) {
7810 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007811 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007812 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007813 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007814
Richard Smith3d8e97e2013-10-18 06:54:39 +00007815 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007816 if (!FPPragmaOptions.empty()) {
7817 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007818 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 }
7820
Yaxun Liu5b746652016-12-18 05:18:55 +00007821 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7822 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7823 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007824
7825 UpdateSema();
7826}
7827
7828void ASTReader::UpdateSema() {
7829 assert(SemaObj && "no Sema to update");
7830
7831 // Load the offsets of the declarations that Sema references.
7832 // They will be lazily deserialized when needed.
7833 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007834 assert(SemaDeclRefs.size() % 3 == 0);
7835 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007836 if (!SemaObj->StdNamespace)
7837 SemaObj->StdNamespace = SemaDeclRefs[I];
7838 if (!SemaObj->StdBadAlloc)
7839 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007840 if (!SemaObj->StdAlignValT)
7841 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007842 }
7843 SemaDeclRefs.clear();
7844 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007845
Nico Weber779355f2016-03-02 23:22:00 +00007846 // Update the state of pragmas. Use the same API as if we had encountered the
7847 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007848 if(OptimizeOffPragmaLocation.isValid())
7849 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007850 if (PragmaMSStructState != -1)
7851 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007852 if (PointersToMembersPragmaLocation.isValid()) {
7853 SemaObj->ActOnPragmaMSPointersToMembers(
7854 (LangOptions::PragmaMSPointersToMembersKind)
7855 PragmaMSPointersToMembersState,
7856 PointersToMembersPragmaLocation);
7857 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007858 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007859
7860 if (PragmaPackCurrentValue) {
7861 // The bottom of the stack might have a default value. It must be adjusted
7862 // to the current value to ensure that the packing state is preserved after
7863 // popping entries that were included/imported from a PCH/module.
7864 bool DropFirst = false;
7865 if (!PragmaPackStack.empty() &&
7866 PragmaPackStack.front().Location.isInvalid()) {
7867 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7868 "Expected a default alignment value");
7869 SemaObj->PackStack.Stack.emplace_back(
7870 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007871 SemaObj->PackStack.CurrentPragmaLocation,
7872 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007873 DropFirst = true;
7874 }
7875 for (const auto &Entry :
7876 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7877 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007878 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007879 if (PragmaPackCurrentLocation.isInvalid()) {
7880 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7881 "Expected a default alignment value");
7882 // Keep the current values.
7883 } else {
7884 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7885 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7886 }
7887 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007888}
7889
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007890IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007891 // Note that we are loading an identifier.
7892 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007893
Douglas Gregor7211ac12013-01-25 23:32:03 +00007894 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007895 NumIdentifierLookups,
7896 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007897
7898 // We don't need to do identifier table lookups in C++ modules (we preload
7899 // all interesting declarations, and don't need to use the scope for name
7900 // lookups). Perform the lookup in PCH files, though, since we don't build
7901 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007902 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007903 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007904 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007905 break;
7906 } else {
7907 // If there is a global index, look there first to determine which modules
7908 // provably do not have any results for this identifier.
7909 GlobalModuleIndex::HitSet Hits;
7910 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7911 if (!loadGlobalIndex()) {
7912 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7913 HitsPtr = &Hits;
7914 }
7915 }
7916
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007917 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007918 }
7919
Guy Benyei11169dd2012-12-18 14:30:41 +00007920 IdentifierInfo *II = Visitor.getIdentifierInfo();
7921 markIdentifierUpToDate(II);
7922 return II;
7923}
7924
7925namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007926
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007927 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007928 /// identifiers stored within a set of AST files.
7929 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007930 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 const ASTReader &Reader;
7932
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007933 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007934 /// the AST reader.
7935 unsigned Index;
7936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007937 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007938 /// of the current AST file.
7939 ASTIdentifierLookupTable::key_iterator Current;
7940
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007941 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007942 /// the current AST file.
7943 ASTIdentifierLookupTable::key_iterator End;
7944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007945 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007946 bool SkipModules;
7947
Guy Benyei11169dd2012-12-18 14:30:41 +00007948 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007949 explicit ASTIdentifierIterator(const ASTReader &Reader,
7950 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007951
Craig Topper3e89dfe2014-03-13 02:13:41 +00007952 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007953 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007954
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007955} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007956
Ben Langmuir537c5b52016-05-04 00:53:13 +00007957ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7958 bool SkipModules)
7959 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007960}
7961
7962StringRef ASTIdentifierIterator::Next() {
7963 while (Current == End) {
7964 // If we have exhausted all of our AST files, we're done.
7965 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007966 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007967
7968 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007969 ModuleFile &F = Reader.ModuleMgr[Index];
7970 if (SkipModules && F.isModule())
7971 continue;
7972
Vedant Kumar48b4f762018-04-14 01:40:48 +00007973 ASTIdentifierLookupTable *IdTable =
7974 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007975 Current = IdTable->key_begin();
7976 End = IdTable->key_end();
7977 }
7978
7979 // We have any identifiers remaining in the current AST file; return
7980 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007981 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007982 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007983 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007984}
7985
Ben Langmuir537c5b52016-05-04 00:53:13 +00007986namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007987
Ben Langmuir537c5b52016-05-04 00:53:13 +00007988/// A utility for appending two IdentifierIterators.
7989class ChainedIdentifierIterator : public IdentifierIterator {
7990 std::unique_ptr<IdentifierIterator> Current;
7991 std::unique_ptr<IdentifierIterator> Queued;
7992
7993public:
7994 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7995 std::unique_ptr<IdentifierIterator> Second)
7996 : Current(std::move(First)), Queued(std::move(Second)) {}
7997
7998 StringRef Next() override {
7999 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008000 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00008001
8002 StringRef result = Current->Next();
8003 if (!result.empty())
8004 return result;
8005
8006 // Try the queued iterator, which may itself be empty.
8007 Current.reset();
8008 std::swap(Current, Queued);
8009 return Next();
8010 }
8011};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008012
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008013} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00008014
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008015IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00008016 if (!loadGlobalIndex()) {
8017 std::unique_ptr<IdentifierIterator> ReaderIter(
8018 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
8019 std::unique_ptr<IdentifierIterator> ModulesIter(
8020 GlobalIndex->createIdentifierIterator());
8021 return new ChainedIdentifierIterator(std::move(ReaderIter),
8022 std::move(ModulesIter));
8023 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00008024
Guy Benyei11169dd2012-12-18 14:30:41 +00008025 return new ASTIdentifierIterator(*this);
8026}
8027
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008028namespace clang {
8029namespace serialization {
8030
Guy Benyei11169dd2012-12-18 14:30:41 +00008031 class ReadMethodPoolVisitor {
8032 ASTReader &Reader;
8033 Selector Sel;
8034 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008035 unsigned InstanceBits = 0;
8036 unsigned FactoryBits = 0;
8037 bool InstanceHasMoreThanOneDecl = false;
8038 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008039 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
8040 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008041
8042 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00008043 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008045 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008046
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008047 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 if (!M.SelectorLookupTable)
8049 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008050
Guy Benyei11169dd2012-12-18 14:30:41 +00008051 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008052 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 return true;
8054
Richard Smithbdf2d932015-07-30 03:37:16 +00008055 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008056 ASTSelectorLookupTable *PoolTable
8057 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008058 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008059 if (Pos == PoolTable->end())
8060 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008061
Richard Smithbdf2d932015-07-30 03:37:16 +00008062 ++Reader.NumMethodPoolTableHits;
8063 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 // FIXME: Not quite happy with the statistics here. We probably should
8065 // disable this tracking when called via LoadSelector.
8066 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008067 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008068 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008069 if (Reader.DeserializationListener)
8070 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008071
Richard Smithbdf2d932015-07-30 03:37:16 +00008072 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8073 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8074 InstanceBits = Data.InstanceBits;
8075 FactoryBits = Data.FactoryBits;
8076 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8077 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 return true;
8079 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008080
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008081 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008082 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8083 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008084 }
8085
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008086 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008087 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008088 return FactoryMethods;
8089 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008090
8091 unsigned getInstanceBits() const { return InstanceBits; }
8092 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008093
Nico Weberff4b35e2014-12-27 22:14:15 +00008094 bool instanceHasMoreThanOneDecl() const {
8095 return InstanceHasMoreThanOneDecl;
8096 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008097
Nico Weberff4b35e2014-12-27 22:14:15 +00008098 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008099 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008100
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008101} // namespace serialization
8102} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008103
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008104/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008105static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8106 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008107 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8108 S.addMethodToGlobalList(&List, Methods[I]);
8109 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008110}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008111
Guy Benyei11169dd2012-12-18 14:30:41 +00008112void ASTReader::ReadMethodPool(Selector Sel) {
8113 // Get the selector generation and update it to the current generation.
8114 unsigned &Generation = SelectorGeneration[Sel];
8115 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008116 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008117 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008118
Guy Benyei11169dd2012-12-18 14:30:41 +00008119 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008120 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008122 ModuleMgr.visit(Visitor);
8123
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008125 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008127
8128 ++NumMethodPoolHits;
8129
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 if (!getSema())
8131 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008132
Guy Benyei11169dd2012-12-18 14:30:41 +00008133 Sema &S = *getSema();
8134 Sema::GlobalMethodPool::iterator Pos
8135 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008136
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008137 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008138 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008139 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008140 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008141
8142 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8143 // when building a module we keep every method individually and may need to
8144 // update hasMoreThanOneDecl as we add the methods.
8145 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8146 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008147}
8148
Manman Rena0f31a02016-04-29 19:04:05 +00008149void ASTReader::updateOutOfDateSelector(Selector Sel) {
8150 if (SelectorOutOfDate[Sel])
8151 ReadMethodPool(Sel);
8152}
8153
Guy Benyei11169dd2012-12-18 14:30:41 +00008154void ASTReader::ReadKnownNamespaces(
8155 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8156 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008157
Vedant Kumar48b4f762018-04-14 01:40:48 +00008158 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8159 if (NamespaceDecl *Namespace
8160 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008163}
8164
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008165void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008166 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008167 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008168 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008169 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008170 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008171 Undefined.insert(std::make_pair(D, Loc));
8172 }
8173}
Nick Lewycky8334af82013-01-26 00:35:08 +00008174
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008175void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8176 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8177 Exprs) {
8178 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008179 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008180 uint64_t Count = DelayedDeleteExprs[Idx++];
8181 for (uint64_t C = 0; C < Count; ++C) {
8182 SourceLocation DeleteLoc =
8183 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8184 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8185 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8186 }
8187 }
8188}
8189
Guy Benyei11169dd2012-12-18 14:30:41 +00008190void ASTReader::ReadTentativeDefinitions(
8191 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008192 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8193 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 if (Var)
8195 TentativeDefs.push_back(Var);
8196 }
8197 TentativeDefinitions.clear();
8198}
8199
8200void ASTReader::ReadUnusedFileScopedDecls(
8201 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008202 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8203 DeclaratorDecl *D
8204 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 if (D)
8206 Decls.push_back(D);
8207 }
8208 UnusedFileScopedDecls.clear();
8209}
8210
8211void ASTReader::ReadDelegatingConstructors(
8212 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008213 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8214 CXXConstructorDecl *D
8215 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008216 if (D)
8217 Decls.push_back(D);
8218 }
8219 DelegatingCtorDecls.clear();
8220}
8221
8222void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008223 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8224 TypedefNameDecl *D
8225 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 if (D)
8227 Decls.push_back(D);
8228 }
8229 ExtVectorDecls.clear();
8230}
8231
Nico Weber72889432014-09-06 01:25:55 +00008232void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8233 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008234 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8235 ++I) {
8236 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8237 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008238 if (D)
8239 Decls.insert(D);
8240 }
8241 UnusedLocalTypedefNameCandidates.clear();
8242}
8243
Guy Benyei11169dd2012-12-18 14:30:41 +00008244void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008245 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008246 if (ReferencedSelectorsData.empty())
8247 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008248
Guy Benyei11169dd2012-12-18 14:30:41 +00008249 // If there are @selector references added them to its pool. This is for
8250 // implementation of -Wselector.
8251 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8252 unsigned I = 0;
8253 while (I < DataSize) {
8254 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8255 SourceLocation SelLoc
8256 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8257 Sels.push_back(std::make_pair(Sel, SelLoc));
8258 }
8259 ReferencedSelectorsData.clear();
8260}
8261
8262void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008263 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008264 if (WeakUndeclaredIdentifiers.empty())
8265 return;
8266
8267 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008268 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008270 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008271 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8272 SourceLocation Loc
8273 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8274 bool Used = WeakUndeclaredIdentifiers[I++];
8275 WeakInfo WI(AliasId, Loc);
8276 WI.setUsed(Used);
8277 WeakIDs.push_back(std::make_pair(WeakId, WI));
8278 }
8279 WeakUndeclaredIdentifiers.clear();
8280}
8281
8282void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8283 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8284 ExternalVTableUse VT;
8285 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8286 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8287 VT.DefinitionRequired = VTableUses[Idx++];
8288 VTables.push_back(VT);
8289 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008290
Guy Benyei11169dd2012-12-18 14:30:41 +00008291 VTableUses.clear();
8292}
8293
8294void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008295 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008296 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008297 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008298 SourceLocation Loc
8299 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8300
8301 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008302 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008303 PendingInstantiations.clear();
8304}
8305
Richard Smithe40f2ba2013-08-07 21:41:30 +00008306void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008307 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8308 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008309 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8310 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008311 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008312
Justin Lebar28f09c52016-10-10 16:26:08 +00008313 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008314 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8315
8316 ModuleFile *F = getOwningModuleFile(LT->D);
8317 assert(F && "No module");
8318
8319 unsigned TokN = LateParsedTemplates[Idx++];
8320 LT->Toks.reserve(TokN);
8321 for (unsigned T = 0; T < TokN; ++T)
8322 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8323
Justin Lebar28f09c52016-10-10 16:26:08 +00008324 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008325 }
8326
8327 LateParsedTemplates.clear();
8328}
8329
Guy Benyei11169dd2012-12-18 14:30:41 +00008330void ASTReader::LoadSelector(Selector Sel) {
8331 // It would be complicated to avoid reading the methods anyway. So don't.
8332 ReadMethodPool(Sel);
8333}
8334
8335void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8336 assert(ID && "Non-zero identifier ID required");
8337 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8338 IdentifiersLoaded[ID - 1] = II;
8339 if (DeserializationListener)
8340 DeserializationListener->IdentifierRead(ID, II);
8341}
8342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008343/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008344/// identifier.
8345///
8346/// If the AST reader is currently in a state where the given declaration IDs
8347/// cannot safely be resolved, they are queued until it is safe to resolve
8348/// them.
8349///
8350/// \param II an IdentifierInfo that refers to one or more globally-visible
8351/// declarations.
8352///
8353/// \param DeclIDs the set of declaration IDs with the name @p II that are
8354/// visible at global scope.
8355///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008356/// \param Decls if non-null, this vector will be populated with the set of
8357/// deserialized declarations. These declarations will not be pushed into
8358/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008359void
8360ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8361 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008362 SmallVectorImpl<Decl *> *Decls) {
8363 if (NumCurrentElementsDeserializing && !Decls) {
8364 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 return;
8366 }
8367
Vedant Kumar48b4f762018-04-14 01:40:48 +00008368 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008369 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 // Queue this declaration so that it will be added to the
8371 // translation unit scope and identifier's declaration chain
8372 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008373 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008374 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008375 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008376
Vedant Kumar48b4f762018-04-14 01:40:48 +00008377 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008378
8379 // If we're simply supposed to record the declarations, do so now.
8380 if (Decls) {
8381 Decls->push_back(D);
8382 continue;
8383 }
8384
8385 // Introduce this declaration into the translation-unit scope
8386 // and add it to the declaration chain for this identifier, so
8387 // that (unqualified) name lookup will find it.
8388 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008389 }
8390}
8391
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008392IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008393 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008394 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008395
8396 if (IdentifiersLoaded.empty()) {
8397 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008398 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008399 }
8400
8401 ID -= 1;
8402 if (!IdentifiersLoaded[ID]) {
8403 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8404 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8405 ModuleFile *M = I->second;
8406 unsigned Index = ID - M->BaseIdentifierID;
8407 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8408
8409 // All of the strings in the AST file are preceded by a 16-bit length.
8410 // Extract that 16-bit length to avoid having to execute strlen().
8411 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8412 // unsigned integers. This is important to avoid integer overflow when
8413 // we cast them to 'unsigned'.
8414 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8415 unsigned StrLen = (((unsigned) StrLenPtr[0])
8416 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008417 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8418 IdentifiersLoaded[ID] = &II;
8419 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008420 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008421 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008422 }
8423
8424 return IdentifiersLoaded[ID];
8425}
8426
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008427IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8428 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008429}
8430
8431IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8432 if (LocalID < NUM_PREDEF_IDENT_IDS)
8433 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008434
Richard Smith37a93df2017-02-18 00:32:02 +00008435 if (!M.ModuleOffsetMap.empty())
8436 ReadModuleOffsetMap(M);
8437
Guy Benyei11169dd2012-12-18 14:30:41 +00008438 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8439 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008440 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008441 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008442
Guy Benyei11169dd2012-12-18 14:30:41 +00008443 return LocalID + I->second;
8444}
8445
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008446MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008447 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008448 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008449
8450 if (MacrosLoaded.empty()) {
8451 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008452 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 }
8454
8455 ID -= NUM_PREDEF_MACRO_IDS;
8456 if (!MacrosLoaded[ID]) {
8457 GlobalMacroMapType::iterator I
8458 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8459 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8460 ModuleFile *M = I->second;
8461 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008462 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008463
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008464 if (DeserializationListener)
8465 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8466 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008467 }
8468
8469 return MacrosLoaded[ID];
8470}
8471
8472MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8473 if (LocalID < NUM_PREDEF_MACRO_IDS)
8474 return LocalID;
8475
Richard Smith37a93df2017-02-18 00:32:02 +00008476 if (!M.ModuleOffsetMap.empty())
8477 ReadModuleOffsetMap(M);
8478
Guy Benyei11169dd2012-12-18 14:30:41 +00008479 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8480 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8481 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8482
8483 return LocalID + I->second;
8484}
8485
8486serialization::SubmoduleID
8487ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8488 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8489 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008490
Richard Smith37a93df2017-02-18 00:32:02 +00008491 if (!M.ModuleOffsetMap.empty())
8492 ReadModuleOffsetMap(M);
8493
Guy Benyei11169dd2012-12-18 14:30:41 +00008494 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8495 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008496 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008497 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008498
Guy Benyei11169dd2012-12-18 14:30:41 +00008499 return LocalID + I->second;
8500}
8501
8502Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8503 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8504 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008505 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008506 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008507
Guy Benyei11169dd2012-12-18 14:30:41 +00008508 if (GlobalID > SubmodulesLoaded.size()) {
8509 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008510 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008511 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008512
Guy Benyei11169dd2012-12-18 14:30:41 +00008513 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8514}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008515
8516Module *ASTReader::getModule(unsigned ID) {
8517 return getSubmodule(ID);
8518}
8519
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008520bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8521 ModuleFile *MF = getOwningModuleFile(D);
8522 return MF && MF->PCHHasObjectFile;
8523}
8524
Richard Smithd88a7f12015-09-01 20:35:42 +00008525ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8526 if (ID & 1) {
8527 // It's a module, look it up by submodule ID.
8528 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8529 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8530 } else {
8531 // It's a prefix (preamble, PCH, ...). Look it up by index.
8532 unsigned IndexFromEnd = ID >> 1;
8533 assert(IndexFromEnd && "got reference to unknown module file");
8534 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8535 }
8536}
8537
8538unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8539 if (!F)
8540 return 1;
8541
8542 // For a file representing a module, use the submodule ID of the top-level
8543 // module as the file ID. For any other kind of file, the number of such
8544 // files loaded beforehand will be the same on reload.
8545 // FIXME: Is this true even if we have an explicit module file and a PCH?
8546 if (F->isModule())
8547 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8548
8549 auto PCHModules = getModuleManager().pch_modules();
Fangrui Song75e74e02019-03-31 08:48:19 +00008550 auto I = llvm::find(PCHModules, F);
Richard Smithd88a7f12015-09-01 20:35:42 +00008551 assert(I != PCHModules.end() && "emitting reference to unknown file");
8552 return (I - PCHModules.end()) << 1;
8553}
8554
Adrian Prantl15bcf702015-06-30 17:39:43 +00008555llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8556ASTReader::getSourceDescriptor(unsigned ID) {
8557 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008558 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008559
8560 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008561 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008562 const auto &PCHChain = ModuleMgr.pch_modules();
8563 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008564 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008565 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008566 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8567 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8568 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008569 }
8570 return None;
8571}
8572
David Blaikie1ac9c982017-04-11 21:13:37 +00008573ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008574 auto I = DefinitionSource.find(FD);
8575 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008576 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008577 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008578}
8579
Guy Benyei11169dd2012-12-18 14:30:41 +00008580Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8581 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8582}
8583
8584Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8585 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008586 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008587
8588 if (ID > SelectorsLoaded.size()) {
8589 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008590 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 }
8592
Craig Toppera13603a2014-05-22 05:54:18 +00008593 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008594 // Load this selector from the selector table.
8595 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8596 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8597 ModuleFile &M = *I->second;
8598 ASTSelectorLookupTrait Trait(*this, M);
8599 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8600 SelectorsLoaded[ID - 1] =
8601 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8602 if (DeserializationListener)
8603 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8604 }
8605
8606 return SelectorsLoaded[ID - 1];
8607}
8608
8609Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8610 return DecodeSelector(ID);
8611}
8612
8613uint32_t ASTReader::GetNumExternalSelectors() {
8614 // ID 0 (the null selector) is considered an external selector.
8615 return getTotalNumSelectors() + 1;
8616}
8617
8618serialization::SelectorID
8619ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8620 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8621 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008622
Richard Smith37a93df2017-02-18 00:32:02 +00008623 if (!M.ModuleOffsetMap.empty())
8624 ReadModuleOffsetMap(M);
8625
Guy Benyei11169dd2012-12-18 14:30:41 +00008626 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8627 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008628 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008629 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008630
Guy Benyei11169dd2012-12-18 14:30:41 +00008631 return LocalID + I->second;
8632}
8633
8634DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008635ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008637 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008638 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008639 switch (Kind) {
8640 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008641 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008642
8643 case DeclarationName::ObjCZeroArgSelector:
8644 case DeclarationName::ObjCOneArgSelector:
8645 case DeclarationName::ObjCMultiArgSelector:
8646 return DeclarationName(ReadSelector(F, Record, Idx));
8647
8648 case DeclarationName::CXXConstructorName:
8649 return Context.DeclarationNames.getCXXConstructorName(
8650 Context.getCanonicalType(readType(F, Record, Idx)));
8651
8652 case DeclarationName::CXXDestructorName:
8653 return Context.DeclarationNames.getCXXDestructorName(
8654 Context.getCanonicalType(readType(F, Record, Idx)));
8655
Richard Smith35845152017-02-07 01:37:30 +00008656 case DeclarationName::CXXDeductionGuideName:
8657 return Context.DeclarationNames.getCXXDeductionGuideName(
8658 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8659
Guy Benyei11169dd2012-12-18 14:30:41 +00008660 case DeclarationName::CXXConversionFunctionName:
8661 return Context.DeclarationNames.getCXXConversionFunctionName(
8662 Context.getCanonicalType(readType(F, Record, Idx)));
8663
8664 case DeclarationName::CXXOperatorName:
8665 return Context.DeclarationNames.getCXXOperatorName(
8666 (OverloadedOperatorKind)Record[Idx++]);
8667
8668 case DeclarationName::CXXLiteralOperatorName:
8669 return Context.DeclarationNames.getCXXLiteralOperatorName(
8670 GetIdentifierInfo(F, Record, Idx));
8671
8672 case DeclarationName::CXXUsingDirective:
8673 return DeclarationName::getUsingDirectiveName();
8674 }
8675
8676 llvm_unreachable("Invalid NameKind!");
8677}
8678
8679void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8680 DeclarationNameLoc &DNLoc,
8681 DeclarationName Name,
8682 const RecordData &Record, unsigned &Idx) {
8683 switch (Name.getNameKind()) {
8684 case DeclarationName::CXXConstructorName:
8685 case DeclarationName::CXXDestructorName:
8686 case DeclarationName::CXXConversionFunctionName:
8687 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8688 break;
8689
8690 case DeclarationName::CXXOperatorName:
8691 DNLoc.CXXOperatorName.BeginOpNameLoc
8692 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8693 DNLoc.CXXOperatorName.EndOpNameLoc
8694 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8695 break;
8696
8697 case DeclarationName::CXXLiteralOperatorName:
8698 DNLoc.CXXLiteralOperatorName.OpNameLoc
8699 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8700 break;
8701
8702 case DeclarationName::Identifier:
8703 case DeclarationName::ObjCZeroArgSelector:
8704 case DeclarationName::ObjCOneArgSelector:
8705 case DeclarationName::ObjCMultiArgSelector:
8706 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008707 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008708 break;
8709 }
8710}
8711
8712void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8713 DeclarationNameInfo &NameInfo,
8714 const RecordData &Record, unsigned &Idx) {
8715 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8716 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8717 DeclarationNameLoc DNLoc;
8718 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8719 NameInfo.setInfo(DNLoc);
8720}
8721
8722void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8723 const RecordData &Record, unsigned &Idx) {
8724 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8725 unsigned NumTPLists = Record[Idx++];
8726 Info.NumTemplParamLists = NumTPLists;
8727 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008728 Info.TemplParamLists =
8729 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008730 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8732 }
8733}
8734
8735TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008736ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008737 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008738 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008739 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 switch (Kind) {
8741 case TemplateName::Template:
8742 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8743
8744 case TemplateName::OverloadedTemplate: {
8745 unsigned size = Record[Idx++];
8746 UnresolvedSet<8> Decls;
8747 while (size--)
8748 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8749
8750 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8751 }
8752
Richard Smithb23c5e82019-05-09 03:31:27 +00008753 case TemplateName::AssumedTemplate: {
8754 DeclarationName Name = ReadDeclarationName(F, Record, Idx);
8755 return Context.getAssumedTemplateName(Name);
8756 }
8757
Guy Benyei11169dd2012-12-18 14:30:41 +00008758 case TemplateName::QualifiedTemplate: {
8759 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8760 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008761 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008762 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8763 }
8764
8765 case TemplateName::DependentTemplate: {
8766 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8767 if (Record[Idx++]) // isIdentifier
8768 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008769 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008770 Idx));
8771 return Context.getDependentTemplateName(NNS,
8772 (OverloadedOperatorKind)Record[Idx++]);
8773 }
8774
8775 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008776 TemplateTemplateParmDecl *param
8777 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8778 if (!param) return TemplateName();
8779 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8780 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00008781 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008782
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008784 TemplateTemplateParmDecl *Param
8785 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008786 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008787 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008788
Guy Benyei11169dd2012-12-18 14:30:41 +00008789 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8790 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008791 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008792
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8794 }
8795 }
8796
8797 llvm_unreachable("Unhandled template name kind!");
8798}
8799
Richard Smith2bb3c342015-08-09 01:05:31 +00008800TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8801 const RecordData &Record,
8802 unsigned &Idx,
8803 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008804 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008805 if (Canonicalize) {
8806 // The caller wants a canonical template argument. Sometimes the AST only
8807 // wants template arguments in canonical form (particularly as the template
8808 // argument lists of template specializations) so ensure we preserve that
8809 // canonical form across serialization.
8810 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8811 return Context.getCanonicalTemplateArgument(Arg);
8812 }
8813
Vedant Kumar48b4f762018-04-14 01:40:48 +00008814 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008815 switch (Kind) {
8816 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00008817 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00008818 case TemplateArgument::Type:
8819 return TemplateArgument(readType(F, Record, Idx));
8820 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008821 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008822 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008823 }
8824 case TemplateArgument::NullPtr:
8825 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8826 case TemplateArgument::Integral: {
8827 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8828 QualType T = readType(F, Record, Idx);
8829 return TemplateArgument(Context, Value, T);
8830 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008831 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008832 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8833 case TemplateArgument::TemplateExpansion: {
8834 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008835 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008836 if (unsigned NumExpansions = Record[Idx++])
8837 NumTemplateExpansions = NumExpansions - 1;
8838 return TemplateArgument(Name, NumTemplateExpansions);
8839 }
8840 case TemplateArgument::Expression:
8841 return TemplateArgument(ReadExpr(F));
8842 case TemplateArgument::Pack: {
8843 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008844 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00008845 for (unsigned I = 0; I != NumArgs; ++I)
8846 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008847 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008848 }
8849 }
8850
8851 llvm_unreachable("Unhandled template argument kind!");
8852}
8853
8854TemplateParameterList *
8855ASTReader::ReadTemplateParameterList(ModuleFile &F,
8856 const RecordData &Record, unsigned &Idx) {
8857 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8858 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8859 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8860
8861 unsigned NumParams = Record[Idx++];
8862 SmallVector<NamedDecl *, 16> Params;
8863 Params.reserve(NumParams);
8864 while (NumParams--)
8865 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8866
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008867 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008868 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8869 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008870 return TemplateParams;
8871}
8872
8873void
8874ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008875ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008876 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008877 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008878 unsigned NumTemplateArgs = Record[Idx++];
8879 TemplArgs.reserve(NumTemplateArgs);
8880 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008881 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008882}
8883
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008884/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008885void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008886 const RecordData &Record, unsigned &Idx) {
8887 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008888 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008889 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008890 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008891 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008892 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008893 }
8894}
8895
8896CXXBaseSpecifier
8897ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8898 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008899 bool isVirtual = static_cast<bool>(Record[Idx++]);
8900 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8901 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8902 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008903 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8904 SourceRange Range = ReadSourceRange(F, Record, Idx);
8905 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008906 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008907 EllipsisLoc);
8908 Result.setInheritConstructors(inheritConstructors);
8909 return Result;
8910}
8911
Richard Smithc2bb8182015-03-24 06:36:48 +00008912CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008913ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8914 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008915 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008916 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008917 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008918 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008919 for (unsigned i = 0; i != NumInitializers; ++i) {
8920 TypeSourceInfo *TInfo = nullptr;
8921 bool IsBaseVirtual = false;
8922 FieldDecl *Member = nullptr;
8923 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008924
Vedant Kumar48b4f762018-04-14 01:40:48 +00008925 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008926 switch (Type) {
8927 case CTOR_INITIALIZER_BASE:
8928 TInfo = GetTypeSourceInfo(F, Record, Idx);
8929 IsBaseVirtual = Record[Idx++];
8930 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008931
Richard Smithc2bb8182015-03-24 06:36:48 +00008932 case CTOR_INITIALIZER_DELEGATING:
8933 TInfo = GetTypeSourceInfo(F, Record, Idx);
8934 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008935
Richard Smithc2bb8182015-03-24 06:36:48 +00008936 case CTOR_INITIALIZER_MEMBER:
8937 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8938 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008939
Richard Smithc2bb8182015-03-24 06:36:48 +00008940 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8941 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8942 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008943 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008944
8945 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8946 Expr *Init = ReadExpr(F);
8947 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8948 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008949
8950 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008951 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008952 BOMInit = new (Context)
8953 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8954 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008955 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008956 BOMInit = new (Context)
8957 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008958 else if (Member)
8959 BOMInit = new (Context)
8960 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8961 Init, RParenLoc);
8962 else
8963 BOMInit = new (Context)
8964 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8965 LParenLoc, Init, RParenLoc);
8966
Richard Smith418ed822016-12-14 19:45:03 +00008967 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008968 unsigned SourceOrder = Record[Idx++];
8969 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008970 }
8971
Richard Smithc2bb8182015-03-24 06:36:48 +00008972 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008973 }
8974
Richard Smithc2bb8182015-03-24 06:36:48 +00008975 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008976}
8977
8978NestedNameSpecifier *
8979ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8980 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008981 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008982 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008983 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008984 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008985 NestedNameSpecifier::SpecifierKind Kind
8986 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008987 switch (Kind) {
8988 case NestedNameSpecifier::Identifier: {
8989 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8990 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8991 break;
8992 }
8993
8994 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008995 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008996 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8997 break;
8998 }
8999
9000 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009001 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009002 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
9003 break;
9004 }
9005
9006 case NestedNameSpecifier::TypeSpec:
9007 case NestedNameSpecifier::TypeSpecWithTemplate: {
9008 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
9009 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00009010 return nullptr;
9011
Guy Benyei11169dd2012-12-18 14:30:41 +00009012 bool Template = Record[Idx++];
9013 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
9014 break;
9015 }
9016
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009017 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00009018 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
9019 // No associated value, and there can't be a prefix.
9020 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00009021
9022 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009023 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009024 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
9025 break;
9026 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009027 }
9028 Prev = NNS;
9029 }
9030 return NNS;
9031}
9032
9033NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009034ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009035 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009036 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009037 unsigned N = Record[Idx++];
9038 NestedNameSpecifierLocBuilder Builder;
9039 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009040 NestedNameSpecifier::SpecifierKind Kind
9041 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009042 switch (Kind) {
9043 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009044 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009045 SourceRange Range = ReadSourceRange(F, Record, Idx);
9046 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
9047 break;
9048 }
9049
9050 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009051 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009052 SourceRange Range = ReadSourceRange(F, Record, Idx);
9053 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9054 break;
9055 }
9056
9057 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009058 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009059 SourceRange Range = ReadSourceRange(F, Record, Idx);
9060 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9061 break;
9062 }
9063
9064 case NestedNameSpecifier::TypeSpec:
9065 case NestedNameSpecifier::TypeSpecWithTemplate: {
9066 bool Template = Record[Idx++];
9067 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9068 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009069 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009070 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9071
9072 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009073 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009074 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9075 T->getTypeLoc(), ColonColonLoc);
9076 break;
9077 }
9078
9079 case NestedNameSpecifier::Global: {
9080 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9081 Builder.MakeGlobal(Context, ColonColonLoc);
9082 break;
9083 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009084
9085 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009086 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009087 SourceRange Range = ReadSourceRange(F, Record, Idx);
9088 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9089 break;
9090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009091 }
9092 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009093
Guy Benyei11169dd2012-12-18 14:30:41 +00009094 return Builder.getWithLocInContext(Context);
9095}
9096
9097SourceRange
9098ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9099 unsigned &Idx) {
9100 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9101 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9102 return SourceRange(beg, end);
9103}
9104
Gauthier Harnisch83c7b612019-06-15 10:24:47 +00009105static FixedPointSemantics
9106ReadFixedPointSemantics(const SmallVectorImpl<uint64_t> &Record,
9107 unsigned &Idx) {
9108 unsigned Width = Record[Idx++];
9109 unsigned Scale = Record[Idx++];
9110 uint64_t Tmp = Record[Idx++];
9111 bool IsSigned = Tmp & 0x1;
9112 bool IsSaturated = Tmp & 0x2;
9113 bool HasUnsignedPadding = Tmp & 0x4;
9114 return FixedPointSemantics(Width, Scale, IsSigned, IsSaturated,
9115 HasUnsignedPadding);
9116}
9117
9118APValue ASTReader::ReadAPValue(const RecordData &Record, unsigned &Idx) {
9119 unsigned Kind = Record[Idx++];
9120 switch (Kind) {
9121 case APValue::None:
9122 return APValue();
9123 case APValue::Indeterminate:
9124 return APValue::IndeterminateValue();
9125 case APValue::Int:
9126 return APValue(ReadAPSInt(Record, Idx));
9127 case APValue::Float: {
9128 const llvm::fltSemantics &FloatSema = llvm::APFloatBase::EnumToSemantics(
9129 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9130 return APValue(ReadAPFloat(Record, FloatSema, Idx));
9131 }
9132 case APValue::FixedPoint: {
9133 FixedPointSemantics FPSema = ReadFixedPointSemantics(Record, Idx);
9134 return APValue(APFixedPoint(ReadAPInt(Record, Idx), FPSema));
9135 }
9136 case APValue::ComplexInt: {
9137 llvm::APSInt First = ReadAPSInt(Record, Idx);
9138 return APValue(std::move(First), ReadAPSInt(Record, Idx));
9139 }
9140 case APValue::ComplexFloat: {
9141 const llvm::fltSemantics &FloatSema1 = llvm::APFloatBase::EnumToSemantics(
9142 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9143 llvm::APFloat First = ReadAPFloat(Record, FloatSema1, Idx);
9144 const llvm::fltSemantics &FloatSema2 = llvm::APFloatBase::EnumToSemantics(
9145 static_cast<llvm::APFloatBase::Semantics>(Record[Idx++]));
9146 return APValue(std::move(First), ReadAPFloat(Record, FloatSema2, Idx));
9147 }
9148 case APValue::LValue:
9149 case APValue::Vector:
9150 case APValue::Array:
9151 case APValue::Struct:
9152 case APValue::Union:
9153 case APValue::MemberPointer:
9154 case APValue::AddrLabelDiff:
9155 // TODO : Handle all these APValue::ValueKind.
9156 return APValue();
9157 }
9158 llvm_unreachable("Invalid APValue::ValueKind");
9159}
9160
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009161/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009162llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9163 unsigned BitWidth = Record[Idx++];
9164 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9165 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9166 Idx += NumWords;
9167 return Result;
9168}
9169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009170/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009171llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9172 bool isUnsigned = Record[Idx++];
9173 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9174}
9175
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009176/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009177llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9178 const llvm::fltSemantics &Sem,
9179 unsigned &Idx) {
9180 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009181}
9182
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009183// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009184std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9185 unsigned Len = Record[Idx++];
9186 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9187 Idx += Len;
9188 return Result;
9189}
9190
Richard Smith7ed1bc92014-12-05 22:42:13 +00009191std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9192 unsigned &Idx) {
9193 std::string Filename = ReadString(Record, Idx);
9194 ResolveImportedPath(F, Filename);
9195 return Filename;
9196}
9197
Duncan P. N. Exon Smith0a2be462019-03-09 17:44:01 +00009198std::string ASTReader::ReadPath(StringRef BaseDirectory,
9199 const RecordData &Record, unsigned &Idx) {
9200 std::string Filename = ReadString(Record, Idx);
9201 if (!BaseDirectory.empty())
9202 ResolveImportedPath(Filename, BaseDirectory);
9203 return Filename;
9204}
9205
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009206VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009207 unsigned &Idx) {
9208 unsigned Major = Record[Idx++];
9209 unsigned Minor = Record[Idx++];
9210 unsigned Subminor = Record[Idx++];
9211 if (Minor == 0)
9212 return VersionTuple(Major);
9213 if (Subminor == 0)
9214 return VersionTuple(Major, Minor - 1);
9215 return VersionTuple(Major, Minor - 1, Subminor - 1);
9216}
9217
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009218CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009219 const RecordData &Record,
9220 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009221 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009222 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009223}
9224
Richard Smith37a93df2017-02-18 00:32:02 +00009225DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009226 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009227}
9228
Richard Smith37a93df2017-02-18 00:32:02 +00009229DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009230 return Diags.Report(Loc, DiagID);
9231}
9232
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009233/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009234/// preprocessor.
9235IdentifierTable &ASTReader::getIdentifierTable() {
9236 return PP.getIdentifierTable();
9237}
9238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009239/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009240/// statement.
9241void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009242 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009243 "Already have a SwitchCase with this ID");
9244 (*CurrSwitchCaseStmts)[ID] = SC;
9245}
9246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009247/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009248SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009249 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009250 return (*CurrSwitchCaseStmts)[ID];
9251}
9252
9253void ASTReader::ClearSwitchCaseIDs() {
9254 CurrSwitchCaseStmts->clear();
9255}
9256
9257void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009258 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009259 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009260 for (SmallVectorImpl<std::pair<BitstreamCursor,
9261 serialization::ModuleFile *>>::iterator
9262 I = CommentsCursors.begin(),
9263 E = CommentsCursors.end();
9264 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009265 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009266 BitstreamCursor &Cursor = I->first;
9267 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009268 SavedStreamPosition SavedPosition(Cursor);
9269
9270 RecordData Record;
9271 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009272 llvm::BitstreamEntry Entry =
9273 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009274
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009275 switch (Entry.Kind) {
9276 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9277 case llvm::BitstreamEntry::Error:
9278 Error("malformed block record in AST file");
9279 return;
9280 case llvm::BitstreamEntry::EndBlock:
9281 goto NextCursor;
9282 case llvm::BitstreamEntry::Record:
9283 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009284 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009285 }
9286
9287 // Read a record.
9288 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009289 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009290 case COMMENTS_RAW_COMMENT: {
9291 unsigned Idx = 0;
9292 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009293 RawComment::CommentKind Kind =
9294 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009295 bool IsTrailingComment = Record[Idx++];
9296 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009297 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009298 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009299 break;
9300 }
9301 }
9302 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009303 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009304 // De-serialized SourceLocations get negative FileIDs for other modules,
9305 // potentially invalidating the original order. Sort it again.
Fangrui Song55fab262018-09-26 22:16:28 +00009306 llvm::sort(Comments, BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009307 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009308 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009309}
9310
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009311void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9312 bool IncludeSystem, bool Complain,
9313 llvm::function_ref<void(const serialization::InputFile &IF,
9314 bool isSystem)> Visitor) {
9315 unsigned NumUserInputs = MF.NumUserInputFiles;
9316 unsigned NumInputs = MF.InputFilesLoaded.size();
9317 assert(NumUserInputs <= NumInputs);
9318 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9319 for (unsigned I = 0; I < N; ++I) {
9320 bool IsSystem = I >= NumUserInputs;
9321 InputFile IF = getInputFile(MF, I+1, Complain);
9322 Visitor(IF, IsSystem);
9323 }
9324}
9325
Richard Smithf3f84612017-06-29 02:19:42 +00009326void ASTReader::visitTopLevelModuleMaps(
9327 serialization::ModuleFile &MF,
9328 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9329 unsigned NumInputs = MF.InputFilesLoaded.size();
9330 for (unsigned I = 0; I < NumInputs; ++I) {
9331 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9332 if (IFI.TopLevelModuleMap)
9333 // FIXME: This unnecessarily re-reads the InputFileInfo.
9334 if (auto *FE = getInputFile(MF, I + 1).getFile())
9335 Visitor(FE);
9336 }
9337}
9338
Richard Smithcd45dbc2014-04-19 03:48:30 +00009339std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9340 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009341 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009342 return M->getFullModuleName();
9343
9344 // Otherwise, use the name of the top-level module the decl is within.
9345 if (ModuleFile *M = getOwningModuleFile(D))
9346 return M->ModuleName;
9347
9348 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009349 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009350}
9351
Guy Benyei11169dd2012-12-18 14:30:41 +00009352void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009353 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009354 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009355 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009356 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009357 // If any identifiers with corresponding top-level declarations have
9358 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009359 using TopLevelDeclsMap =
9360 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009361 TopLevelDeclsMap TopLevelDecls;
9362
Guy Benyei11169dd2012-12-18 14:30:41 +00009363 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009364 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009365 SmallVector<uint32_t, 4> DeclIDs =
9366 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009367 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009368
9369 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009370 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009371
Richard Smitha62d1982018-08-03 01:00:01 +00009372 // Load each function type that we deferred loading because it was a
9373 // deduced type that might refer to a local type declared within itself.
9374 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9375 auto *FD = PendingFunctionTypes[I].first;
9376 FD->setType(GetType(PendingFunctionTypes[I].second));
9377
9378 // If we gave a function a deduced return type, remember that we need to
9379 // propagate that along the redeclaration chain.
9380 auto *DT = FD->getReturnType()->getContainedDeducedType();
9381 if (DT && DT->isDeduced())
9382 PendingDeducedTypeUpdates.insert(
9383 {FD->getCanonicalDecl(), FD->getReturnType()});
9384 }
9385 PendingFunctionTypes.clear();
9386
Richard Smith851072e2014-05-19 20:59:20 +00009387 // For each decl chain that we wanted to complete while deserializing, mark
9388 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009389 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9390 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9391 }
Richard Smith851072e2014-05-19 20:59:20 +00009392 PendingIncompleteDeclChains.clear();
9393
Guy Benyei11169dd2012-12-18 14:30:41 +00009394 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009395 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009396 loadPendingDeclChain(PendingDeclChains[I].first,
9397 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009398 PendingDeclChains.clear();
9399
Douglas Gregor6168bd22013-02-18 15:53:43 +00009400 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009401 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9402 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9403 IdentifierInfo *II = TLD->first;
9404 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9405 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009406 }
9407 }
9408
Guy Benyei11169dd2012-12-18 14:30:41 +00009409 // Load any pending macro definitions.
9410 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009411 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9412 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9413 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9414 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009415 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009416 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009417 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009418 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009419 resolvePendingMacro(II, Info);
9420 }
9421 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009422 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009423 ++IDIdx) {
9424 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009425 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009426 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009427 }
9428 }
9429 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009430
9431 // Wire up the DeclContexts for Decls that we delayed setting until
9432 // recursive loading is completed.
9433 while (!PendingDeclContextInfos.empty()) {
9434 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9435 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009436 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9437 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009438 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9439 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009440
Richard Smithd1c46742014-04-30 02:24:17 +00009441 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009442 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009443 auto Update = PendingUpdateRecords.pop_back_val();
9444 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009445 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009446 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009447 }
Richard Smith8a639892015-01-24 01:07:20 +00009448
9449 // At this point, all update records for loaded decls are in place, so any
9450 // fake class definitions should have become real.
9451 assert(PendingFakeDefinitionData.empty() &&
9452 "faked up a class definition but never saw the real one");
9453
Guy Benyei11169dd2012-12-18 14:30:41 +00009454 // If we deserialized any C++ or Objective-C class definitions, any
9455 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009456 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009457 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009458 for (Decl *D : PendingDefinitions) {
9459 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9460 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009461 // Make sure that the TagType points at the definition.
9462 const_cast<TagType*>(TagT)->decl = TD;
9463 }
Richard Smith8ce51082015-03-11 01:44:51 +00009464
Vedant Kumar48b4f762018-04-14 01:40:48 +00009465 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009466 for (auto *R = getMostRecentExistingDecl(RD); R;
9467 R = R->getPreviousDecl()) {
9468 assert((R == D) ==
9469 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009470 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009471 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009472 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009473 }
9474
9475 continue;
9476 }
Richard Smith8ce51082015-03-11 01:44:51 +00009477
Vedant Kumar48b4f762018-04-14 01:40:48 +00009478 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009479 // Make sure that the ObjCInterfaceType points at the definition.
9480 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9481 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009482
9483 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9484 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9485
Guy Benyei11169dd2012-12-18 14:30:41 +00009486 continue;
9487 }
Richard Smith8ce51082015-03-11 01:44:51 +00009488
Vedant Kumar48b4f762018-04-14 01:40:48 +00009489 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009490 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9491 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9492
Guy Benyei11169dd2012-12-18 14:30:41 +00009493 continue;
9494 }
Richard Smith8ce51082015-03-11 01:44:51 +00009495
Vedant Kumar48b4f762018-04-14 01:40:48 +00009496 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009497 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9498 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009499 }
9500 PendingDefinitions.clear();
9501
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009502 // Load the bodies of any functions or methods we've encountered. We do
9503 // this now (delayed) so that we can be sure that the declaration chains
9504 // have been fully wired up (hasBody relies on this).
9505 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009506 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9507 PBEnd = PendingBodies.end();
9508 PB != PBEnd; ++PB) {
9509 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009510 // For a function defined inline within a class template, force the
9511 // canonical definition to be the one inside the canonical definition of
9512 // the template. This ensures that we instantiate from a correct view
9513 // of the template.
9514 //
9515 // Sadly we can't do this more generally: we can't be sure that all
9516 // copies of an arbitrary class definition will have the same members
9517 // defined (eg, some member functions may not be instantiated, and some
9518 // special members may or may not have been implicitly defined).
9519 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9520 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9521 continue;
9522
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009523 // FIXME: Check for =delete/=default?
9524 // FIXME: Complain about ODR violations here?
9525 const FunctionDecl *Defn = nullptr;
9526 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009527 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009528 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009529 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009530 mergeDefinitionVisibility(NonConstDefn, FD);
9531
9532 if (!FD->isLateTemplateParsed() &&
9533 !NonConstDefn->isLateTemplateParsed() &&
9534 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009535 if (!isa<CXXMethodDecl>(FD)) {
9536 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9537 } else if (FD->getLexicalParent()->isFileContext() &&
9538 NonConstDefn->getLexicalParent()->isFileContext()) {
9539 // Only diagnose out-of-line method definitions. If they are
9540 // in class definitions, then an error will be generated when
9541 // processing the class bodies.
9542 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9543 }
Richard Trieue6caa262017-12-23 00:41:01 +00009544 }
9545 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009546 continue;
9547 }
9548
Vedant Kumar48b4f762018-04-14 01:40:48 +00009549 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009550 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009551 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009552 }
9553 PendingBodies.clear();
9554
Richard Smith42413142015-05-15 20:05:43 +00009555 // Do some cleanup.
9556 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9557 getContext().deduplicateMergedDefinitonsFor(ND);
9558 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009559}
9560
9561void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009562 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009563 PendingFunctionOdrMergeFailures.empty() &&
9564 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009565 return;
9566
Richard Smitha0ce9c42014-07-29 23:23:27 +00009567 // Trigger the import of the full definition of each class that had any
9568 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009569 // These updates may in turn find and diagnose some ODR failures, so take
9570 // ownership of the set first.
9571 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9572 PendingOdrMergeFailures.clear();
9573 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009574 Merge.first->buildLookup();
9575 Merge.first->decls_begin();
9576 Merge.first->bases_begin();
9577 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009578 for (auto &RecordPair : Merge.second) {
9579 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009580 RD->decls_begin();
9581 RD->bases_begin();
9582 RD->vbases_begin();
9583 }
9584 }
9585
Richard Trieue6caa262017-12-23 00:41:01 +00009586 // Trigger the import of functions.
9587 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9588 PendingFunctionOdrMergeFailures.clear();
9589 for (auto &Merge : FunctionOdrMergeFailures) {
9590 Merge.first->buildLookup();
9591 Merge.first->decls_begin();
9592 Merge.first->getBody();
9593 for (auto &FD : Merge.second) {
9594 FD->buildLookup();
9595 FD->decls_begin();
9596 FD->getBody();
9597 }
9598 }
9599
Richard Trieuab4d7302018-07-25 22:52:05 +00009600 // Trigger the import of enums.
9601 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9602 PendingEnumOdrMergeFailures.clear();
9603 for (auto &Merge : EnumOdrMergeFailures) {
9604 Merge.first->decls_begin();
9605 for (auto &Enum : Merge.second) {
9606 Enum->decls_begin();
9607 }
9608 }
9609
Richard Smitha0ce9c42014-07-29 23:23:27 +00009610 // For each declaration from a merged context, check that the canonical
9611 // definition of that context also contains a declaration of the same
9612 // entity.
9613 //
9614 // Caution: this loop does things that might invalidate iterators into
9615 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9616 while (!PendingOdrMergeChecks.empty()) {
9617 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9618
9619 // FIXME: Skip over implicit declarations for now. This matters for things
9620 // like implicitly-declared special member functions. This isn't entirely
9621 // correct; we can end up with multiple unmerged declarations of the same
9622 // implicit entity.
9623 if (D->isImplicit())
9624 continue;
9625
9626 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009627
9628 bool Found = false;
9629 const Decl *DCanon = D->getCanonicalDecl();
9630
Richard Smith01bdb7a2014-08-28 05:44:07 +00009631 for (auto RI : D->redecls()) {
9632 if (RI->getLexicalDeclContext() == CanonDef) {
9633 Found = true;
9634 break;
9635 }
9636 }
9637 if (Found)
9638 continue;
9639
Richard Smith0f4e2c42015-08-06 04:23:48 +00009640 // Quick check failed, time to do the slow thing. Note, we can't just
9641 // look up the name of D in CanonDef here, because the member that is
9642 // in CanonDef might not be found by name lookup (it might have been
9643 // replaced by a more recent declaration in the lookup table), and we
9644 // can't necessarily find it in the redeclaration chain because it might
9645 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009646 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009647 for (auto *CanonMember : CanonDef->decls()) {
9648 if (CanonMember->getCanonicalDecl() == DCanon) {
9649 // This can happen if the declaration is merely mergeable and not
9650 // actually redeclarable (we looked for redeclarations earlier).
9651 //
9652 // FIXME: We should be able to detect this more efficiently, without
9653 // pulling in all of the members of CanonDef.
9654 Found = true;
9655 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009656 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009657 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9658 if (ND->getDeclName() == D->getDeclName())
9659 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009660 }
9661
9662 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009663 // The AST doesn't like TagDecls becoming invalid after they've been
9664 // completed. We only really need to mark FieldDecls as invalid here.
9665 if (!isa<TagDecl>(D))
9666 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009667
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009668 // Ensure we don't accidentally recursively enter deserialization while
9669 // we're producing our diagnostic.
9670 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009671
9672 std::string CanonDefModule =
9673 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9674 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9675 << D << getOwningModuleNameForDiagnostic(D)
9676 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9677
9678 if (Candidates.empty())
9679 Diag(cast<Decl>(CanonDef)->getLocation(),
9680 diag::note_module_odr_violation_no_possible_decls) << D;
9681 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009682 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9683 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009684 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009685 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009686 }
9687
9688 DiagnosedOdrMergeFailures.insert(CanonDef);
9689 }
9690 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009691
Richard Trieuab4d7302018-07-25 22:52:05 +00009692 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9693 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009694 return;
9695
9696 // Ensure we don't accidentally recursively enter deserialization while
9697 // we're producing our diagnostics.
9698 Deserializing RecursionGuard(this);
9699
Richard Trieue6caa262017-12-23 00:41:01 +00009700 // Common code for hashing helpers.
9701 ODRHash Hash;
9702 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9703 Hash.clear();
9704 Hash.AddQualType(Ty);
9705 return Hash.CalculateHash();
9706 };
9707
9708 auto ComputeODRHash = [&Hash](const Stmt *S) {
9709 assert(S);
9710 Hash.clear();
9711 Hash.AddStmt(S);
9712 return Hash.CalculateHash();
9713 };
9714
9715 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9716 assert(D);
9717 Hash.clear();
9718 Hash.AddSubDecl(D);
9719 return Hash.CalculateHash();
9720 };
9721
Richard Trieu7282d322018-04-25 00:31:15 +00009722 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9723 Hash.clear();
9724 Hash.AddTemplateArgument(TA);
9725 return Hash.CalculateHash();
9726 };
9727
Richard Trieu9359e8f2018-05-30 01:12:26 +00009728 auto ComputeTemplateParameterListODRHash =
9729 [&Hash](const TemplateParameterList *TPL) {
9730 assert(TPL);
9731 Hash.clear();
9732 Hash.AddTemplateParameterList(TPL);
9733 return Hash.CalculateHash();
9734 };
9735
Richard Smithcd45dbc2014-04-19 03:48:30 +00009736 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009737 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009738 // If we've already pointed out a specific problem with this class, don't
9739 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009740 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009741 continue;
9742
9743 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009744 CXXRecordDecl *FirstRecord = Merge.first;
9745 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009746 for (auto &RecordPair : Merge.second) {
9747 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009748 // Multiple different declarations got merged together; tell the user
9749 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009750 if (FirstRecord == SecondRecord)
9751 continue;
9752
9753 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009754
9755 auto *FirstDD = FirstRecord->DefinitionData;
9756 auto *SecondDD = RecordPair.second;
9757
9758 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9759
9760 // Diagnostics from DefinitionData are emitted here.
9761 if (FirstDD != SecondDD) {
9762 enum ODRDefinitionDataDifference {
9763 NumBases,
9764 NumVBases,
9765 BaseType,
9766 BaseVirtual,
9767 BaseAccess,
9768 };
9769 auto ODRDiagError = [FirstRecord, &FirstModule,
9770 this](SourceLocation Loc, SourceRange Range,
9771 ODRDefinitionDataDifference DiffType) {
9772 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9773 << FirstRecord << FirstModule.empty() << FirstModule << Range
9774 << DiffType;
9775 };
9776 auto ODRDiagNote = [&SecondModule,
9777 this](SourceLocation Loc, SourceRange Range,
9778 ODRDefinitionDataDifference DiffType) {
9779 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9780 << SecondModule << Range << DiffType;
9781 };
9782
Richard Trieue13eabe2017-09-30 02:19:17 +00009783 unsigned FirstNumBases = FirstDD->NumBases;
9784 unsigned FirstNumVBases = FirstDD->NumVBases;
9785 unsigned SecondNumBases = SecondDD->NumBases;
9786 unsigned SecondNumVBases = SecondDD->NumVBases;
9787
9788 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9789 unsigned NumBases = DD->NumBases;
9790 if (NumBases == 0) return SourceRange();
9791 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009792 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009793 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +00009794 };
9795
9796 if (FirstNumBases != SecondNumBases) {
9797 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9798 NumBases)
9799 << FirstNumBases;
9800 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9801 NumBases)
9802 << SecondNumBases;
9803 Diagnosed = true;
9804 break;
9805 }
9806
9807 if (FirstNumVBases != SecondNumVBases) {
9808 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9809 NumVBases)
9810 << FirstNumVBases;
9811 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9812 NumVBases)
9813 << SecondNumVBases;
9814 Diagnosed = true;
9815 break;
9816 }
9817
9818 auto FirstBases = FirstDD->bases();
9819 auto SecondBases = SecondDD->bases();
9820 unsigned i = 0;
9821 for (i = 0; i < FirstNumBases; ++i) {
9822 auto FirstBase = FirstBases[i];
9823 auto SecondBase = SecondBases[i];
9824 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9825 ComputeQualTypeODRHash(SecondBase.getType())) {
9826 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9827 BaseType)
9828 << (i + 1) << FirstBase.getType();
9829 ODRDiagNote(SecondRecord->getLocation(),
9830 SecondBase.getSourceRange(), BaseType)
9831 << (i + 1) << SecondBase.getType();
9832 break;
9833 }
9834
9835 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9836 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9837 BaseVirtual)
9838 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9839 ODRDiagNote(SecondRecord->getLocation(),
9840 SecondBase.getSourceRange(), BaseVirtual)
9841 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9842 break;
9843 }
9844
9845 if (FirstBase.getAccessSpecifierAsWritten() !=
9846 SecondBase.getAccessSpecifierAsWritten()) {
9847 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9848 BaseAccess)
9849 << (i + 1) << FirstBase.getType()
9850 << (int)FirstBase.getAccessSpecifierAsWritten();
9851 ODRDiagNote(SecondRecord->getLocation(),
9852 SecondBase.getSourceRange(), BaseAccess)
9853 << (i + 1) << SecondBase.getType()
9854 << (int)SecondBase.getAccessSpecifierAsWritten();
9855 break;
9856 }
9857 }
9858
9859 if (i != FirstNumBases) {
9860 Diagnosed = true;
9861 break;
9862 }
9863 }
9864
Richard Trieue7f7ed22017-02-22 01:11:25 +00009865 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009866
9867 const ClassTemplateDecl *FirstTemplate =
9868 FirstRecord->getDescribedClassTemplate();
9869 const ClassTemplateDecl *SecondTemplate =
9870 SecondRecord->getDescribedClassTemplate();
9871
9872 assert(!FirstTemplate == !SecondTemplate &&
9873 "Both pointers should be null or non-null");
9874
9875 enum ODRTemplateDifference {
9876 ParamEmptyName,
9877 ParamName,
9878 ParamSingleDefaultArgument,
9879 ParamDifferentDefaultArgument,
9880 };
9881
9882 if (FirstTemplate && SecondTemplate) {
9883 DeclHashes FirstTemplateHashes;
9884 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009885
9886 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009887 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9888 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009889 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009890 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009891 }
9892 };
9893
9894 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9895 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9896
9897 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9898 "Number of template parameters should be equal.");
9899
9900 auto FirstIt = FirstTemplateHashes.begin();
9901 auto FirstEnd = FirstTemplateHashes.end();
9902 auto SecondIt = SecondTemplateHashes.begin();
9903 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9904 if (FirstIt->second == SecondIt->second)
9905 continue;
9906
9907 auto ODRDiagError = [FirstRecord, &FirstModule,
9908 this](SourceLocation Loc, SourceRange Range,
9909 ODRTemplateDifference DiffType) {
9910 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9911 << FirstRecord << FirstModule.empty() << FirstModule << Range
9912 << DiffType;
9913 };
9914 auto ODRDiagNote = [&SecondModule,
9915 this](SourceLocation Loc, SourceRange Range,
9916 ODRTemplateDifference DiffType) {
9917 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9918 << SecondModule << Range << DiffType;
9919 };
9920
Vedant Kumar48b4f762018-04-14 01:40:48 +00009921 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9922 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009923
9924 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9925 "Parameter Decl's should be the same kind.");
9926
9927 DeclarationName FirstName = FirstDecl->getDeclName();
9928 DeclarationName SecondName = SecondDecl->getDeclName();
9929
9930 if (FirstName != SecondName) {
9931 const bool FirstNameEmpty =
9932 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9933 const bool SecondNameEmpty =
9934 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9935 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9936 "Both template parameters cannot be unnamed.");
9937 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9938 FirstNameEmpty ? ParamEmptyName : ParamName)
9939 << FirstName;
9940 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9941 SecondNameEmpty ? ParamEmptyName : ParamName)
9942 << SecondName;
9943 break;
9944 }
9945
9946 switch (FirstDecl->getKind()) {
9947 default:
9948 llvm_unreachable("Invalid template parameter type.");
9949 case Decl::TemplateTypeParm: {
9950 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9951 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9952 const bool HasFirstDefaultArgument =
9953 FirstParam->hasDefaultArgument() &&
9954 !FirstParam->defaultArgumentWasInherited();
9955 const bool HasSecondDefaultArgument =
9956 SecondParam->hasDefaultArgument() &&
9957 !SecondParam->defaultArgumentWasInherited();
9958
9959 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9960 ODRDiagError(FirstDecl->getLocation(),
9961 FirstDecl->getSourceRange(),
9962 ParamSingleDefaultArgument)
9963 << HasFirstDefaultArgument;
9964 ODRDiagNote(SecondDecl->getLocation(),
9965 SecondDecl->getSourceRange(),
9966 ParamSingleDefaultArgument)
9967 << HasSecondDefaultArgument;
9968 break;
9969 }
9970
9971 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9972 "Expecting default arguments.");
9973
9974 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9975 ParamDifferentDefaultArgument);
9976 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9977 ParamDifferentDefaultArgument);
9978
9979 break;
9980 }
9981 case Decl::NonTypeTemplateParm: {
9982 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9983 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9984 const bool HasFirstDefaultArgument =
9985 FirstParam->hasDefaultArgument() &&
9986 !FirstParam->defaultArgumentWasInherited();
9987 const bool HasSecondDefaultArgument =
9988 SecondParam->hasDefaultArgument() &&
9989 !SecondParam->defaultArgumentWasInherited();
9990
9991 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9992 ODRDiagError(FirstDecl->getLocation(),
9993 FirstDecl->getSourceRange(),
9994 ParamSingleDefaultArgument)
9995 << HasFirstDefaultArgument;
9996 ODRDiagNote(SecondDecl->getLocation(),
9997 SecondDecl->getSourceRange(),
9998 ParamSingleDefaultArgument)
9999 << HasSecondDefaultArgument;
10000 break;
10001 }
10002
10003 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10004 "Expecting default arguments.");
10005
10006 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10007 ParamDifferentDefaultArgument);
10008 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10009 ParamDifferentDefaultArgument);
10010
10011 break;
10012 }
10013 case Decl::TemplateTemplateParm: {
10014 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
10015 const auto *SecondParam =
10016 cast<TemplateTemplateParmDecl>(SecondDecl);
10017 const bool HasFirstDefaultArgument =
10018 FirstParam->hasDefaultArgument() &&
10019 !FirstParam->defaultArgumentWasInherited();
10020 const bool HasSecondDefaultArgument =
10021 SecondParam->hasDefaultArgument() &&
10022 !SecondParam->defaultArgumentWasInherited();
10023
10024 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10025 ODRDiagError(FirstDecl->getLocation(),
10026 FirstDecl->getSourceRange(),
10027 ParamSingleDefaultArgument)
10028 << HasFirstDefaultArgument;
10029 ODRDiagNote(SecondDecl->getLocation(),
10030 SecondDecl->getSourceRange(),
10031 ParamSingleDefaultArgument)
10032 << HasSecondDefaultArgument;
10033 break;
10034 }
10035
10036 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
10037 "Expecting default arguments.");
10038
10039 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
10040 ParamDifferentDefaultArgument);
10041 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
10042 ParamDifferentDefaultArgument);
10043
10044 break;
10045 }
10046 }
10047
10048 break;
10049 }
10050
10051 if (FirstIt != FirstEnd) {
10052 Diagnosed = true;
10053 break;
10054 }
10055 }
10056
Richard Trieue7f7ed22017-02-22 01:11:25 +000010057 DeclHashes FirstHashes;
10058 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010059
Richard Trieue6caa262017-12-23 00:41:01 +000010060 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
10061 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010062 for (auto *D : Record->decls()) {
10063 // Due to decl merging, the first CXXRecordDecl is the parent of
10064 // Decls in both records.
10065 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
10066 continue;
Richard Trieue6caa262017-12-23 00:41:01 +000010067 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +000010068 }
10069 };
10070 PopulateHashes(FirstHashes, FirstRecord);
10071 PopulateHashes(SecondHashes, SecondRecord);
10072
10073 // Used with err_module_odr_violation_mismatch_decl and
10074 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +000010075 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +000010076 enum {
10077 EndOfClass,
10078 PublicSpecifer,
10079 PrivateSpecifer,
10080 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +000010081 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +000010082 Field,
Richard Trieu48143742017-02-28 21:24:38 +000010083 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +000010084 TypeAlias,
10085 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010086 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010087 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010088 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +000010089 Other
10090 } FirstDiffType = Other,
10091 SecondDiffType = Other;
10092
10093 auto DifferenceSelector = [](Decl *D) {
10094 assert(D && "valid Decl required");
10095 switch (D->getKind()) {
10096 default:
10097 return Other;
10098 case Decl::AccessSpec:
10099 switch (D->getAccess()) {
10100 case AS_public:
10101 return PublicSpecifer;
10102 case AS_private:
10103 return PrivateSpecifer;
10104 case AS_protected:
10105 return ProtectedSpecifer;
10106 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010107 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010108 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +000010109 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +000010110 case Decl::StaticAssert:
10111 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010112 case Decl::Field:
10113 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010114 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010115 case Decl::CXXConstructor:
10116 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010117 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010118 case Decl::TypeAlias:
10119 return TypeAlias;
10120 case Decl::Typedef:
10121 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010122 case Decl::Var:
10123 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010124 case Decl::Friend:
10125 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010126 case Decl::FunctionTemplate:
10127 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010128 }
10129 };
10130
10131 Decl *FirstDecl = nullptr;
10132 Decl *SecondDecl = nullptr;
10133 auto FirstIt = FirstHashes.begin();
10134 auto SecondIt = SecondHashes.begin();
10135
10136 // If there is a diagnoseable difference, FirstDiffType and
10137 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10138 // filled in if not EndOfClass.
10139 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010140 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10141 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010142 ++FirstIt;
10143 ++SecondIt;
10144 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010145 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010146
Richard Trieue7f7ed22017-02-22 01:11:25 +000010147 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10148 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10149
10150 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10151 SecondDiffType =
10152 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10153
10154 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010155 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010156
10157 if (FirstDiffType == Other || SecondDiffType == Other) {
10158 // Reaching this point means an unexpected Decl was encountered
10159 // or no difference was detected. This causes a generic error
10160 // message to be emitted.
10161 Diag(FirstRecord->getLocation(),
10162 diag::err_module_odr_violation_different_definitions)
10163 << FirstRecord << FirstModule.empty() << FirstModule;
10164
Richard Trieuca48d362017-06-21 01:43:13 +000010165 if (FirstDecl) {
10166 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10167 << FirstRecord << FirstDecl->getSourceRange();
10168 }
10169
Richard Trieue7f7ed22017-02-22 01:11:25 +000010170 Diag(SecondRecord->getLocation(),
10171 diag::note_module_odr_violation_different_definitions)
10172 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010173
10174 if (SecondDecl) {
10175 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10176 << SecondDecl->getSourceRange();
10177 }
10178
Richard Trieue7f7ed22017-02-22 01:11:25 +000010179 Diagnosed = true;
10180 break;
10181 }
10182
10183 if (FirstDiffType != SecondDiffType) {
10184 SourceLocation FirstLoc;
10185 SourceRange FirstRange;
10186 if (FirstDiffType == EndOfClass) {
10187 FirstLoc = FirstRecord->getBraceRange().getEnd();
10188 } else {
10189 FirstLoc = FirstIt->first->getLocation();
10190 FirstRange = FirstIt->first->getSourceRange();
10191 }
10192 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10193 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10194 << FirstDiffType;
10195
10196 SourceLocation SecondLoc;
10197 SourceRange SecondRange;
10198 if (SecondDiffType == EndOfClass) {
10199 SecondLoc = SecondRecord->getBraceRange().getEnd();
10200 } else {
10201 SecondLoc = SecondDecl->getLocation();
10202 SecondRange = SecondDecl->getSourceRange();
10203 }
10204 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10205 << SecondModule << SecondRange << SecondDiffType;
10206 Diagnosed = true;
10207 break;
10208 }
10209
Richard Trieu639d7b62017-02-22 22:22:42 +000010210 assert(FirstDiffType == SecondDiffType);
10211
10212 // Used with err_module_odr_violation_mismatch_decl_diff and
10213 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010214 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010215 StaticAssertCondition,
10216 StaticAssertMessage,
10217 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010218 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010219 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010220 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010221 FieldDifferentWidthBitField,
10222 FieldSingleMutable,
10223 FieldSingleInitializer,
10224 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010225 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010226 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010227 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010228 MethodVirtual,
10229 MethodStatic,
10230 MethodVolatile,
10231 MethodConst,
10232 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010233 MethodNumberParameters,
10234 MethodParameterType,
10235 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010236 MethodParameterSingleDefaultArgument,
10237 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010238 MethodNoTemplateArguments,
10239 MethodDifferentNumberTemplateArguments,
10240 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010241 MethodSingleBody,
10242 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010243 TypedefName,
10244 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010245 VarName,
10246 VarType,
10247 VarSingleInitializer,
10248 VarDifferentInitializer,
10249 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010250 FriendTypeFunction,
10251 FriendType,
10252 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010253 FunctionTemplateDifferentNumberParameters,
10254 FunctionTemplateParameterDifferentKind,
10255 FunctionTemplateParameterName,
10256 FunctionTemplateParameterSingleDefaultArgument,
10257 FunctionTemplateParameterDifferentDefaultArgument,
10258 FunctionTemplateParameterDifferentType,
10259 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010260 };
10261
10262 // These lambdas have the common portions of the ODR diagnostics. This
10263 // has the same return as Diag(), so addition parameters can be passed
10264 // in with operator<<
10265 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10266 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10267 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10268 << FirstRecord << FirstModule.empty() << FirstModule << Range
10269 << DiffType;
10270 };
10271 auto ODRDiagNote = [&SecondModule, this](
10272 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10273 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10274 << SecondModule << Range << DiffType;
10275 };
10276
Richard Trieu639d7b62017-02-22 22:22:42 +000010277 switch (FirstDiffType) {
10278 case Other:
10279 case EndOfClass:
10280 case PublicSpecifer:
10281 case PrivateSpecifer:
10282 case ProtectedSpecifer:
10283 llvm_unreachable("Invalid diff type");
10284
10285 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010286 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10287 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010288
10289 Expr *FirstExpr = FirstSA->getAssertExpr();
10290 Expr *SecondExpr = SecondSA->getAssertExpr();
10291 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10292 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10293 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010294 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010295 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010296 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10297 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010298 Diagnosed = true;
10299 break;
10300 }
10301
10302 StringLiteral *FirstStr = FirstSA->getMessage();
10303 StringLiteral *SecondStr = SecondSA->getMessage();
10304 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10305 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10306 SourceLocation FirstLoc, SecondLoc;
10307 SourceRange FirstRange, SecondRange;
10308 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010309 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010310 FirstRange = FirstStr->getSourceRange();
10311 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010312 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010313 FirstRange = FirstSA->getSourceRange();
10314 }
10315 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010316 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010317 SecondRange = SecondStr->getSourceRange();
10318 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010319 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010320 SecondRange = SecondSA->getSourceRange();
10321 }
10322 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10323 << (FirstStr == nullptr);
10324 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10325 << (SecondStr == nullptr);
10326 Diagnosed = true;
10327 break;
10328 }
10329
10330 if (FirstStr && SecondStr &&
10331 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010332 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010333 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010334 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010335 StaticAssertMessage);
10336 Diagnosed = true;
10337 break;
10338 }
10339 break;
10340 }
Richard Trieud0786092017-02-23 00:23:01 +000010341 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010342 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10343 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010344 IdentifierInfo *FirstII = FirstField->getIdentifier();
10345 IdentifierInfo *SecondII = SecondField->getIdentifier();
10346 if (FirstII->getName() != SecondII->getName()) {
10347 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10348 FieldName)
10349 << FirstII;
10350 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10351 FieldName)
10352 << SecondII;
10353
10354 Diagnosed = true;
10355 break;
10356 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010357
Richard Smithdbafb6c2017-06-29 23:23:46 +000010358 assert(getContext().hasSameType(FirstField->getType(),
10359 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010360
10361 QualType FirstType = FirstField->getType();
10362 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010363 if (ComputeQualTypeODRHash(FirstType) !=
10364 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010365 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10366 FieldTypeName)
10367 << FirstII << FirstType;
10368 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10369 FieldTypeName)
10370 << SecondII << SecondType;
10371
10372 Diagnosed = true;
10373 break;
10374 }
10375
Richard Trieu93772fc2017-02-24 20:59:28 +000010376 const bool IsFirstBitField = FirstField->isBitField();
10377 const bool IsSecondBitField = SecondField->isBitField();
10378 if (IsFirstBitField != IsSecondBitField) {
10379 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10380 FieldSingleBitField)
10381 << FirstII << IsFirstBitField;
10382 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10383 FieldSingleBitField)
10384 << SecondII << IsSecondBitField;
10385 Diagnosed = true;
10386 break;
10387 }
10388
10389 if (IsFirstBitField && IsSecondBitField) {
10390 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10391 FieldDifferentWidthBitField)
10392 << FirstII << FirstField->getBitWidth()->getSourceRange();
10393 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10394 FieldDifferentWidthBitField)
10395 << SecondII << SecondField->getBitWidth()->getSourceRange();
10396 Diagnosed = true;
10397 break;
10398 }
10399
Richard Trieu8d543e22017-02-24 23:35:37 +000010400 const bool IsFirstMutable = FirstField->isMutable();
10401 const bool IsSecondMutable = SecondField->isMutable();
10402 if (IsFirstMutable != IsSecondMutable) {
10403 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10404 FieldSingleMutable)
10405 << FirstII << IsFirstMutable;
10406 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10407 FieldSingleMutable)
10408 << SecondII << IsSecondMutable;
10409 Diagnosed = true;
10410 break;
10411 }
10412
10413 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10414 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10415 if ((!FirstInitializer && SecondInitializer) ||
10416 (FirstInitializer && !SecondInitializer)) {
10417 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10418 FieldSingleInitializer)
10419 << FirstII << (FirstInitializer != nullptr);
10420 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10421 FieldSingleInitializer)
10422 << SecondII << (SecondInitializer != nullptr);
10423 Diagnosed = true;
10424 break;
10425 }
10426
10427 if (FirstInitializer && SecondInitializer) {
10428 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10429 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10430 if (FirstInitHash != SecondInitHash) {
10431 ODRDiagError(FirstField->getLocation(),
10432 FirstField->getSourceRange(),
10433 FieldDifferentInitializers)
10434 << FirstII << FirstInitializer->getSourceRange();
10435 ODRDiagNote(SecondField->getLocation(),
10436 SecondField->getSourceRange(),
10437 FieldDifferentInitializers)
10438 << SecondII << SecondInitializer->getSourceRange();
10439 Diagnosed = true;
10440 break;
10441 }
10442 }
10443
Richard Trieud0786092017-02-23 00:23:01 +000010444 break;
10445 }
Richard Trieu48143742017-02-28 21:24:38 +000010446 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010447 enum {
10448 DiagMethod,
10449 DiagConstructor,
10450 DiagDestructor,
10451 } FirstMethodType,
10452 SecondMethodType;
10453 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10454 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10455 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10456 return DiagMethod;
10457 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010458 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10459 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010460 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10461 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010462 auto FirstName = FirstMethod->getDeclName();
10463 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010464 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010465 ODRDiagError(FirstMethod->getLocation(),
10466 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010467 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010468 ODRDiagNote(SecondMethod->getLocation(),
10469 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010470 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010471
10472 Diagnosed = true;
10473 break;
10474 }
10475
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010476 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10477 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010478 if (FirstDeleted != SecondDeleted) {
10479 ODRDiagError(FirstMethod->getLocation(),
10480 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010481 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010482
10483 ODRDiagNote(SecondMethod->getLocation(),
10484 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010485 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010486 Diagnosed = true;
10487 break;
10488 }
10489
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010490 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10491 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10492 if (FirstDefaulted != SecondDefaulted) {
10493 ODRDiagError(FirstMethod->getLocation(),
10494 FirstMethod->getSourceRange(), MethodDefaulted)
10495 << FirstMethodType << FirstName << FirstDefaulted;
10496
10497 ODRDiagNote(SecondMethod->getLocation(),
10498 SecondMethod->getSourceRange(), MethodDefaulted)
10499 << SecondMethodType << SecondName << SecondDefaulted;
10500 Diagnosed = true;
10501 break;
10502 }
10503
Richard Trieu583e2c12017-03-04 00:08:58 +000010504 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10505 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10506 const bool FirstPure = FirstMethod->isPure();
10507 const bool SecondPure = SecondMethod->isPure();
10508 if ((FirstVirtual || SecondVirtual) &&
10509 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10510 ODRDiagError(FirstMethod->getLocation(),
10511 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010512 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010513 ODRDiagNote(SecondMethod->getLocation(),
10514 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010515 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010516 Diagnosed = true;
10517 break;
10518 }
10519
10520 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10521 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10522 // class needs to be checked instead.
10523 const auto FirstStorage = FirstMethod->getStorageClass();
10524 const auto SecondStorage = SecondMethod->getStorageClass();
10525 const bool FirstStatic = FirstStorage == SC_Static;
10526 const bool SecondStatic = SecondStorage == SC_Static;
10527 if (FirstStatic != SecondStatic) {
10528 ODRDiagError(FirstMethod->getLocation(),
10529 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010530 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010531 ODRDiagNote(SecondMethod->getLocation(),
10532 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010533 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010534 Diagnosed = true;
10535 break;
10536 }
10537
10538 const bool FirstVolatile = FirstMethod->isVolatile();
10539 const bool SecondVolatile = SecondMethod->isVolatile();
10540 if (FirstVolatile != SecondVolatile) {
10541 ODRDiagError(FirstMethod->getLocation(),
10542 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010543 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010544 ODRDiagNote(SecondMethod->getLocation(),
10545 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010546 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010547 Diagnosed = true;
10548 break;
10549 }
10550
10551 const bool FirstConst = FirstMethod->isConst();
10552 const bool SecondConst = SecondMethod->isConst();
10553 if (FirstConst != SecondConst) {
10554 ODRDiagError(FirstMethod->getLocation(),
10555 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010556 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010557 ODRDiagNote(SecondMethod->getLocation(),
10558 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010559 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010560 Diagnosed = true;
10561 break;
10562 }
10563
10564 const bool FirstInline = FirstMethod->isInlineSpecified();
10565 const bool SecondInline = SecondMethod->isInlineSpecified();
10566 if (FirstInline != SecondInline) {
10567 ODRDiagError(FirstMethod->getLocation(),
10568 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010569 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010570 ODRDiagNote(SecondMethod->getLocation(),
10571 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010572 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010573 Diagnosed = true;
10574 break;
10575 }
10576
Richard Trieu02552272017-05-02 23:58:52 +000010577 const unsigned FirstNumParameters = FirstMethod->param_size();
10578 const unsigned SecondNumParameters = SecondMethod->param_size();
10579 if (FirstNumParameters != SecondNumParameters) {
10580 ODRDiagError(FirstMethod->getLocation(),
10581 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010582 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010583 ODRDiagNote(SecondMethod->getLocation(),
10584 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010585 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010586 Diagnosed = true;
10587 break;
10588 }
10589
10590 // Need this status boolean to know when break out of the switch.
10591 bool ParameterMismatch = false;
10592 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10593 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10594 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10595
10596 QualType FirstParamType = FirstParam->getType();
10597 QualType SecondParamType = SecondParam->getType();
10598 if (FirstParamType != SecondParamType &&
10599 ComputeQualTypeODRHash(FirstParamType) !=
10600 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010601 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010602 FirstParamType->getAs<DecayedType>()) {
10603 ODRDiagError(FirstMethod->getLocation(),
10604 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010605 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10606 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010607 } else {
10608 ODRDiagError(FirstMethod->getLocation(),
10609 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010610 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10611 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010612 }
10613
Vedant Kumar48b4f762018-04-14 01:40:48 +000010614 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010615 SecondParamType->getAs<DecayedType>()) {
10616 ODRDiagNote(SecondMethod->getLocation(),
10617 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010618 << SecondMethodType << SecondName << (I + 1)
10619 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010620 << ParamDecayedType->getOriginalType();
10621 } else {
10622 ODRDiagNote(SecondMethod->getLocation(),
10623 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010624 << SecondMethodType << SecondName << (I + 1)
10625 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010626 }
10627 ParameterMismatch = true;
10628 break;
10629 }
10630
10631 DeclarationName FirstParamName = FirstParam->getDeclName();
10632 DeclarationName SecondParamName = SecondParam->getDeclName();
10633 if (FirstParamName != SecondParamName) {
10634 ODRDiagError(FirstMethod->getLocation(),
10635 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010636 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010637 ODRDiagNote(SecondMethod->getLocation(),
10638 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010639 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010640 ParameterMismatch = true;
10641 break;
10642 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010643
10644 const Expr *FirstInit = FirstParam->getInit();
10645 const Expr *SecondInit = SecondParam->getInit();
10646 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10647 ODRDiagError(FirstMethod->getLocation(),
10648 FirstMethod->getSourceRange(),
10649 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010650 << FirstMethodType << FirstName << (I + 1)
10651 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010652 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10653 ODRDiagNote(SecondMethod->getLocation(),
10654 SecondMethod->getSourceRange(),
10655 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010656 << SecondMethodType << SecondName << (I + 1)
10657 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010658 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10659 ParameterMismatch = true;
10660 break;
10661 }
10662
10663 if (FirstInit && SecondInit &&
10664 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10665 ODRDiagError(FirstMethod->getLocation(),
10666 FirstMethod->getSourceRange(),
10667 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010668 << FirstMethodType << FirstName << (I + 1)
10669 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010670 ODRDiagNote(SecondMethod->getLocation(),
10671 SecondMethod->getSourceRange(),
10672 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010673 << SecondMethodType << SecondName << (I + 1)
10674 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010675 ParameterMismatch = true;
10676 break;
10677
10678 }
Richard Trieu02552272017-05-02 23:58:52 +000010679 }
10680
10681 if (ParameterMismatch) {
10682 Diagnosed = true;
10683 break;
10684 }
10685
Richard Trieu7282d322018-04-25 00:31:15 +000010686 const auto *FirstTemplateArgs =
10687 FirstMethod->getTemplateSpecializationArgs();
10688 const auto *SecondTemplateArgs =
10689 SecondMethod->getTemplateSpecializationArgs();
10690
10691 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10692 (!FirstTemplateArgs && SecondTemplateArgs)) {
10693 ODRDiagError(FirstMethod->getLocation(),
10694 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10695 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10696 ODRDiagNote(SecondMethod->getLocation(),
10697 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10698 << SecondMethodType << SecondName
10699 << (SecondTemplateArgs != nullptr);
10700
10701 Diagnosed = true;
10702 break;
10703 }
10704
10705 if (FirstTemplateArgs && SecondTemplateArgs) {
10706 // Remove pack expansions from argument list.
10707 auto ExpandTemplateArgumentList =
10708 [](const TemplateArgumentList *TAL) {
10709 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10710 for (const TemplateArgument &TA : TAL->asArray()) {
10711 if (TA.getKind() != TemplateArgument::Pack) {
10712 ExpandedList.push_back(&TA);
10713 continue;
10714 }
10715 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10716 ExpandedList.push_back(&PackTA);
10717 }
10718 }
10719 return ExpandedList;
10720 };
10721 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10722 ExpandTemplateArgumentList(FirstTemplateArgs);
10723 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10724 ExpandTemplateArgumentList(SecondTemplateArgs);
10725
10726 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10727 ODRDiagError(FirstMethod->getLocation(),
10728 FirstMethod->getSourceRange(),
10729 MethodDifferentNumberTemplateArguments)
10730 << FirstMethodType << FirstName
10731 << (unsigned)FirstExpandedList.size();
10732 ODRDiagNote(SecondMethod->getLocation(),
10733 SecondMethod->getSourceRange(),
10734 MethodDifferentNumberTemplateArguments)
10735 << SecondMethodType << SecondName
10736 << (unsigned)SecondExpandedList.size();
10737
10738 Diagnosed = true;
10739 break;
10740 }
10741
10742 bool TemplateArgumentMismatch = false;
10743 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10744 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10745 &SecondTA = *SecondExpandedList[i];
10746 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10747 ComputeTemplateArgumentODRHash(SecondTA)) {
10748 continue;
10749 }
10750
10751 ODRDiagError(FirstMethod->getLocation(),
10752 FirstMethod->getSourceRange(),
10753 MethodDifferentTemplateArgument)
10754 << FirstMethodType << FirstName << FirstTA << i + 1;
10755 ODRDiagNote(SecondMethod->getLocation(),
10756 SecondMethod->getSourceRange(),
10757 MethodDifferentTemplateArgument)
10758 << SecondMethodType << SecondName << SecondTA << i + 1;
10759
10760 TemplateArgumentMismatch = true;
10761 break;
10762 }
10763
10764 if (TemplateArgumentMismatch) {
10765 Diagnosed = true;
10766 break;
10767 }
10768 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010769
10770 // Compute the hash of the method as if it has no body.
10771 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10772 Hash.clear();
10773 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10774 return Hash.CalculateHash();
10775 };
10776
10777 // Compare the hash generated to the hash stored. A difference means
10778 // that a body was present in the original source. Due to merging,
10779 // the stardard way of detecting a body will not work.
10780 const bool HasFirstBody =
10781 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10782 const bool HasSecondBody =
10783 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10784
10785 if (HasFirstBody != HasSecondBody) {
10786 ODRDiagError(FirstMethod->getLocation(),
10787 FirstMethod->getSourceRange(), MethodSingleBody)
10788 << FirstMethodType << FirstName << HasFirstBody;
10789 ODRDiagNote(SecondMethod->getLocation(),
10790 SecondMethod->getSourceRange(), MethodSingleBody)
10791 << SecondMethodType << SecondName << HasSecondBody;
10792 Diagnosed = true;
10793 break;
10794 }
10795
10796 if (HasFirstBody && HasSecondBody) {
10797 ODRDiagError(FirstMethod->getLocation(),
10798 FirstMethod->getSourceRange(), MethodDifferentBody)
10799 << FirstMethodType << FirstName;
10800 ODRDiagNote(SecondMethod->getLocation(),
10801 SecondMethod->getSourceRange(), MethodDifferentBody)
10802 << SecondMethodType << SecondName;
10803 Diagnosed = true;
10804 break;
10805 }
10806
Richard Trieu48143742017-02-28 21:24:38 +000010807 break;
10808 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010809 case TypeAlias:
10810 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010811 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10812 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010813 auto FirstName = FirstTD->getDeclName();
10814 auto SecondName = SecondTD->getDeclName();
10815 if (FirstName != SecondName) {
10816 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10817 TypedefName)
10818 << (FirstDiffType == TypeAlias) << FirstName;
10819 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10820 TypedefName)
10821 << (FirstDiffType == TypeAlias) << SecondName;
10822 Diagnosed = true;
10823 break;
10824 }
10825
10826 QualType FirstType = FirstTD->getUnderlyingType();
10827 QualType SecondType = SecondTD->getUnderlyingType();
10828 if (ComputeQualTypeODRHash(FirstType) !=
10829 ComputeQualTypeODRHash(SecondType)) {
10830 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10831 TypedefType)
10832 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10833 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10834 TypedefType)
10835 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10836 Diagnosed = true;
10837 break;
10838 }
10839 break;
10840 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010841 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010842 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10843 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010844 auto FirstName = FirstVD->getDeclName();
10845 auto SecondName = SecondVD->getDeclName();
10846 if (FirstName != SecondName) {
10847 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10848 VarName)
10849 << FirstName;
10850 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10851 VarName)
10852 << SecondName;
10853 Diagnosed = true;
10854 break;
10855 }
10856
10857 QualType FirstType = FirstVD->getType();
10858 QualType SecondType = SecondVD->getType();
10859 if (ComputeQualTypeODRHash(FirstType) !=
10860 ComputeQualTypeODRHash(SecondType)) {
10861 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10862 VarType)
10863 << FirstName << FirstType;
10864 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10865 VarType)
10866 << SecondName << SecondType;
10867 Diagnosed = true;
10868 break;
10869 }
10870
10871 const Expr *FirstInit = FirstVD->getInit();
10872 const Expr *SecondInit = SecondVD->getInit();
10873 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10874 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10875 VarSingleInitializer)
10876 << FirstName << (FirstInit == nullptr)
10877 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10878 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10879 VarSingleInitializer)
10880 << SecondName << (SecondInit == nullptr)
10881 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10882 Diagnosed = true;
10883 break;
10884 }
10885
10886 if (FirstInit && SecondInit &&
10887 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10888 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10889 VarDifferentInitializer)
10890 << FirstName << FirstInit->getSourceRange();
10891 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10892 VarDifferentInitializer)
10893 << SecondName << SecondInit->getSourceRange();
10894 Diagnosed = true;
10895 break;
10896 }
10897
10898 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10899 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10900 if (FirstIsConstexpr != SecondIsConstexpr) {
10901 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10902 VarConstexpr)
10903 << FirstName << FirstIsConstexpr;
10904 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10905 VarConstexpr)
10906 << SecondName << SecondIsConstexpr;
10907 Diagnosed = true;
10908 break;
10909 }
10910 break;
10911 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010912 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010913 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10914 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010915
10916 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10917 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10918
10919 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10920 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10921
10922 if (FirstND && SecondND) {
10923 ODRDiagError(FirstFriend->getFriendLoc(),
10924 FirstFriend->getSourceRange(), FriendFunction)
10925 << FirstND;
10926 ODRDiagNote(SecondFriend->getFriendLoc(),
10927 SecondFriend->getSourceRange(), FriendFunction)
10928 << SecondND;
10929
10930 Diagnosed = true;
10931 break;
10932 }
10933
10934 if (FirstTSI && SecondTSI) {
10935 QualType FirstFriendType = FirstTSI->getType();
10936 QualType SecondFriendType = SecondTSI->getType();
10937 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10938 ComputeQualTypeODRHash(SecondFriendType));
10939 ODRDiagError(FirstFriend->getFriendLoc(),
10940 FirstFriend->getSourceRange(), FriendType)
10941 << FirstFriendType;
10942 ODRDiagNote(SecondFriend->getFriendLoc(),
10943 SecondFriend->getSourceRange(), FriendType)
10944 << SecondFriendType;
10945 Diagnosed = true;
10946 break;
10947 }
10948
10949 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10950 FriendTypeFunction)
10951 << (FirstTSI == nullptr);
10952 ODRDiagNote(SecondFriend->getFriendLoc(),
10953 SecondFriend->getSourceRange(), FriendTypeFunction)
10954 << (SecondTSI == nullptr);
10955
10956 Diagnosed = true;
10957 break;
10958 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010959 case FunctionTemplate: {
10960 FunctionTemplateDecl *FirstTemplate =
10961 cast<FunctionTemplateDecl>(FirstDecl);
10962 FunctionTemplateDecl *SecondTemplate =
10963 cast<FunctionTemplateDecl>(SecondDecl);
10964
10965 TemplateParameterList *FirstTPL =
10966 FirstTemplate->getTemplateParameters();
10967 TemplateParameterList *SecondTPL =
10968 SecondTemplate->getTemplateParameters();
10969
10970 if (FirstTPL->size() != SecondTPL->size()) {
10971 ODRDiagError(FirstTemplate->getLocation(),
10972 FirstTemplate->getSourceRange(),
10973 FunctionTemplateDifferentNumberParameters)
10974 << FirstTemplate << FirstTPL->size();
10975 ODRDiagNote(SecondTemplate->getLocation(),
10976 SecondTemplate->getSourceRange(),
10977 FunctionTemplateDifferentNumberParameters)
10978 << SecondTemplate << SecondTPL->size();
10979
10980 Diagnosed = true;
10981 break;
10982 }
10983
10984 bool ParameterMismatch = false;
10985 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10986 NamedDecl *FirstParam = FirstTPL->getParam(i);
10987 NamedDecl *SecondParam = SecondTPL->getParam(i);
10988
10989 if (FirstParam->getKind() != SecondParam->getKind()) {
10990 enum {
10991 TemplateTypeParameter,
10992 NonTypeTemplateParameter,
10993 TemplateTemplateParameter,
10994 };
10995 auto GetParamType = [](NamedDecl *D) {
10996 switch (D->getKind()) {
10997 default:
10998 llvm_unreachable("Unexpected template parameter type");
10999 case Decl::TemplateTypeParm:
11000 return TemplateTypeParameter;
11001 case Decl::NonTypeTemplateParm:
11002 return NonTypeTemplateParameter;
11003 case Decl::TemplateTemplateParm:
11004 return TemplateTemplateParameter;
11005 }
11006 };
11007
11008 ODRDiagError(FirstTemplate->getLocation(),
11009 FirstTemplate->getSourceRange(),
11010 FunctionTemplateParameterDifferentKind)
11011 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
11012 ODRDiagNote(SecondTemplate->getLocation(),
11013 SecondTemplate->getSourceRange(),
11014 FunctionTemplateParameterDifferentKind)
11015 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
11016
11017 ParameterMismatch = true;
11018 break;
11019 }
11020
11021 if (FirstParam->getName() != SecondParam->getName()) {
11022 ODRDiagError(FirstTemplate->getLocation(),
11023 FirstTemplate->getSourceRange(),
11024 FunctionTemplateParameterName)
11025 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
11026 << FirstParam;
11027 ODRDiagNote(SecondTemplate->getLocation(),
11028 SecondTemplate->getSourceRange(),
11029 FunctionTemplateParameterName)
11030 << SecondTemplate << (i + 1)
11031 << (bool)SecondParam->getIdentifier() << SecondParam;
11032 ParameterMismatch = true;
11033 break;
11034 }
11035
11036 if (isa<TemplateTypeParmDecl>(FirstParam) &&
11037 isa<TemplateTypeParmDecl>(SecondParam)) {
11038 TemplateTypeParmDecl *FirstTTPD =
11039 cast<TemplateTypeParmDecl>(FirstParam);
11040 TemplateTypeParmDecl *SecondTTPD =
11041 cast<TemplateTypeParmDecl>(SecondParam);
11042 bool HasFirstDefaultArgument =
11043 FirstTTPD->hasDefaultArgument() &&
11044 !FirstTTPD->defaultArgumentWasInherited();
11045 bool HasSecondDefaultArgument =
11046 SecondTTPD->hasDefaultArgument() &&
11047 !SecondTTPD->defaultArgumentWasInherited();
11048 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11049 ODRDiagError(FirstTemplate->getLocation(),
11050 FirstTemplate->getSourceRange(),
11051 FunctionTemplateParameterSingleDefaultArgument)
11052 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11053 ODRDiagNote(SecondTemplate->getLocation(),
11054 SecondTemplate->getSourceRange(),
11055 FunctionTemplateParameterSingleDefaultArgument)
11056 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11057 ParameterMismatch = true;
11058 break;
11059 }
11060
11061 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11062 QualType FirstType = FirstTTPD->getDefaultArgument();
11063 QualType SecondType = SecondTTPD->getDefaultArgument();
11064 if (ComputeQualTypeODRHash(FirstType) !=
11065 ComputeQualTypeODRHash(SecondType)) {
11066 ODRDiagError(FirstTemplate->getLocation(),
11067 FirstTemplate->getSourceRange(),
11068 FunctionTemplateParameterDifferentDefaultArgument)
11069 << FirstTemplate << (i + 1) << FirstType;
11070 ODRDiagNote(SecondTemplate->getLocation(),
11071 SecondTemplate->getSourceRange(),
11072 FunctionTemplateParameterDifferentDefaultArgument)
11073 << SecondTemplate << (i + 1) << SecondType;
11074 ParameterMismatch = true;
11075 break;
11076 }
11077 }
11078
11079 if (FirstTTPD->isParameterPack() !=
11080 SecondTTPD->isParameterPack()) {
11081 ODRDiagError(FirstTemplate->getLocation(),
11082 FirstTemplate->getSourceRange(),
11083 FunctionTemplatePackParameter)
11084 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11085 ODRDiagNote(SecondTemplate->getLocation(),
11086 SecondTemplate->getSourceRange(),
11087 FunctionTemplatePackParameter)
11088 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11089 ParameterMismatch = true;
11090 break;
11091 }
11092 }
11093
11094 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
11095 isa<TemplateTemplateParmDecl>(SecondParam)) {
11096 TemplateTemplateParmDecl *FirstTTPD =
11097 cast<TemplateTemplateParmDecl>(FirstParam);
11098 TemplateTemplateParmDecl *SecondTTPD =
11099 cast<TemplateTemplateParmDecl>(SecondParam);
11100
11101 TemplateParameterList *FirstTPL =
11102 FirstTTPD->getTemplateParameters();
11103 TemplateParameterList *SecondTPL =
11104 SecondTTPD->getTemplateParameters();
11105
11106 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
11107 ComputeTemplateParameterListODRHash(SecondTPL)) {
11108 ODRDiagError(FirstTemplate->getLocation(),
11109 FirstTemplate->getSourceRange(),
11110 FunctionTemplateParameterDifferentType)
11111 << FirstTemplate << (i + 1);
11112 ODRDiagNote(SecondTemplate->getLocation(),
11113 SecondTemplate->getSourceRange(),
11114 FunctionTemplateParameterDifferentType)
11115 << SecondTemplate << (i + 1);
11116 ParameterMismatch = true;
11117 break;
11118 }
11119
11120 bool HasFirstDefaultArgument =
11121 FirstTTPD->hasDefaultArgument() &&
11122 !FirstTTPD->defaultArgumentWasInherited();
11123 bool HasSecondDefaultArgument =
11124 SecondTTPD->hasDefaultArgument() &&
11125 !SecondTTPD->defaultArgumentWasInherited();
11126 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11127 ODRDiagError(FirstTemplate->getLocation(),
11128 FirstTemplate->getSourceRange(),
11129 FunctionTemplateParameterSingleDefaultArgument)
11130 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11131 ODRDiagNote(SecondTemplate->getLocation(),
11132 SecondTemplate->getSourceRange(),
11133 FunctionTemplateParameterSingleDefaultArgument)
11134 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11135 ParameterMismatch = true;
11136 break;
11137 }
11138
11139 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11140 TemplateArgument FirstTA =
11141 FirstTTPD->getDefaultArgument().getArgument();
11142 TemplateArgument SecondTA =
11143 SecondTTPD->getDefaultArgument().getArgument();
11144 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11145 ComputeTemplateArgumentODRHash(SecondTA)) {
11146 ODRDiagError(FirstTemplate->getLocation(),
11147 FirstTemplate->getSourceRange(),
11148 FunctionTemplateParameterDifferentDefaultArgument)
11149 << FirstTemplate << (i + 1) << FirstTA;
11150 ODRDiagNote(SecondTemplate->getLocation(),
11151 SecondTemplate->getSourceRange(),
11152 FunctionTemplateParameterDifferentDefaultArgument)
11153 << SecondTemplate << (i + 1) << SecondTA;
11154 ParameterMismatch = true;
11155 break;
11156 }
11157 }
11158
11159 if (FirstTTPD->isParameterPack() !=
11160 SecondTTPD->isParameterPack()) {
11161 ODRDiagError(FirstTemplate->getLocation(),
11162 FirstTemplate->getSourceRange(),
11163 FunctionTemplatePackParameter)
11164 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11165 ODRDiagNote(SecondTemplate->getLocation(),
11166 SecondTemplate->getSourceRange(),
11167 FunctionTemplatePackParameter)
11168 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11169 ParameterMismatch = true;
11170 break;
11171 }
11172 }
11173
11174 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11175 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11176 NonTypeTemplateParmDecl *FirstNTTPD =
11177 cast<NonTypeTemplateParmDecl>(FirstParam);
11178 NonTypeTemplateParmDecl *SecondNTTPD =
11179 cast<NonTypeTemplateParmDecl>(SecondParam);
11180
11181 QualType FirstType = FirstNTTPD->getType();
11182 QualType SecondType = SecondNTTPD->getType();
11183 if (ComputeQualTypeODRHash(FirstType) !=
11184 ComputeQualTypeODRHash(SecondType)) {
11185 ODRDiagError(FirstTemplate->getLocation(),
11186 FirstTemplate->getSourceRange(),
11187 FunctionTemplateParameterDifferentType)
11188 << FirstTemplate << (i + 1);
11189 ODRDiagNote(SecondTemplate->getLocation(),
11190 SecondTemplate->getSourceRange(),
11191 FunctionTemplateParameterDifferentType)
11192 << SecondTemplate << (i + 1);
11193 ParameterMismatch = true;
11194 break;
11195 }
11196
11197 bool HasFirstDefaultArgument =
11198 FirstNTTPD->hasDefaultArgument() &&
11199 !FirstNTTPD->defaultArgumentWasInherited();
11200 bool HasSecondDefaultArgument =
11201 SecondNTTPD->hasDefaultArgument() &&
11202 !SecondNTTPD->defaultArgumentWasInherited();
11203 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11204 ODRDiagError(FirstTemplate->getLocation(),
11205 FirstTemplate->getSourceRange(),
11206 FunctionTemplateParameterSingleDefaultArgument)
11207 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11208 ODRDiagNote(SecondTemplate->getLocation(),
11209 SecondTemplate->getSourceRange(),
11210 FunctionTemplateParameterSingleDefaultArgument)
11211 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11212 ParameterMismatch = true;
11213 break;
11214 }
11215
11216 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11217 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11218 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11219 if (ComputeODRHash(FirstDefaultArgument) !=
11220 ComputeODRHash(SecondDefaultArgument)) {
11221 ODRDiagError(FirstTemplate->getLocation(),
11222 FirstTemplate->getSourceRange(),
11223 FunctionTemplateParameterDifferentDefaultArgument)
11224 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11225 ODRDiagNote(SecondTemplate->getLocation(),
11226 SecondTemplate->getSourceRange(),
11227 FunctionTemplateParameterDifferentDefaultArgument)
11228 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11229 ParameterMismatch = true;
11230 break;
11231 }
11232 }
11233
11234 if (FirstNTTPD->isParameterPack() !=
11235 SecondNTTPD->isParameterPack()) {
11236 ODRDiagError(FirstTemplate->getLocation(),
11237 FirstTemplate->getSourceRange(),
11238 FunctionTemplatePackParameter)
11239 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11240 ODRDiagNote(SecondTemplate->getLocation(),
11241 SecondTemplate->getSourceRange(),
11242 FunctionTemplatePackParameter)
11243 << SecondTemplate << (i + 1)
11244 << SecondNTTPD->isParameterPack();
11245 ParameterMismatch = true;
11246 break;
11247 }
11248 }
11249 }
11250
11251 if (ParameterMismatch) {
11252 Diagnosed = true;
11253 break;
11254 }
11255
11256 break;
11257 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011258 }
11259
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011260 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011261 continue;
11262
Richard Trieu708859a2017-06-08 00:56:21 +000011263 Diag(FirstDecl->getLocation(),
11264 diag::err_module_odr_violation_mismatch_decl_unknown)
11265 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11266 << FirstDecl->getSourceRange();
11267 Diag(SecondDecl->getLocation(),
11268 diag::note_module_odr_violation_mismatch_decl_unknown)
11269 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011270 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011271 }
11272
11273 if (!Diagnosed) {
11274 // All definitions are updates to the same declaration. This happens if a
11275 // module instantiates the declaration of a class template specialization
11276 // and two or more other modules instantiate its definition.
11277 //
11278 // FIXME: Indicate which modules had instantiations of this definition.
11279 // FIXME: How can this even happen?
11280 Diag(Merge.first->getLocation(),
11281 diag::err_module_odr_violation_different_instantiations)
11282 << Merge.first;
11283 }
11284 }
Richard Trieue6caa262017-12-23 00:41:01 +000011285
11286 // Issue ODR failures diagnostics for functions.
11287 for (auto &Merge : FunctionOdrMergeFailures) {
11288 enum ODRFunctionDifference {
11289 ReturnType,
11290 ParameterName,
11291 ParameterType,
11292 ParameterSingleDefaultArgument,
11293 ParameterDifferentDefaultArgument,
11294 FunctionBody,
11295 };
11296
11297 FunctionDecl *FirstFunction = Merge.first;
11298 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11299
11300 bool Diagnosed = false;
11301 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011302
Richard Trieue6caa262017-12-23 00:41:01 +000011303 if (FirstFunction == SecondFunction)
11304 continue;
11305
11306 std::string SecondModule =
11307 getOwningModuleNameForDiagnostic(SecondFunction);
11308
11309 auto ODRDiagError = [FirstFunction, &FirstModule,
11310 this](SourceLocation Loc, SourceRange Range,
11311 ODRFunctionDifference DiffType) {
11312 return Diag(Loc, diag::err_module_odr_violation_function)
11313 << FirstFunction << FirstModule.empty() << FirstModule << Range
11314 << DiffType;
11315 };
11316 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11317 SourceRange Range,
11318 ODRFunctionDifference DiffType) {
11319 return Diag(Loc, diag::note_module_odr_violation_function)
11320 << SecondModule << Range << DiffType;
11321 };
11322
11323 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11324 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11325 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11326 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11327 << FirstFunction->getReturnType();
11328 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11329 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11330 << SecondFunction->getReturnType();
11331 Diagnosed = true;
11332 break;
11333 }
11334
11335 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11336 "Merged functions with different number of parameters");
11337
11338 auto ParamSize = FirstFunction->param_size();
11339 bool ParameterMismatch = false;
11340 for (unsigned I = 0; I < ParamSize; ++I) {
11341 auto *FirstParam = FirstFunction->getParamDecl(I);
11342 auto *SecondParam = SecondFunction->getParamDecl(I);
11343
11344 assert(getContext().hasSameType(FirstParam->getType(),
11345 SecondParam->getType()) &&
11346 "Merged function has different parameter types.");
11347
11348 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11349 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11350 ParameterName)
11351 << I + 1 << FirstParam->getDeclName();
11352 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11353 ParameterName)
11354 << I + 1 << SecondParam->getDeclName();
11355 ParameterMismatch = true;
11356 break;
11357 };
11358
11359 QualType FirstParamType = FirstParam->getType();
11360 QualType SecondParamType = SecondParam->getType();
11361 if (FirstParamType != SecondParamType &&
11362 ComputeQualTypeODRHash(FirstParamType) !=
11363 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011364 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011365 FirstParamType->getAs<DecayedType>()) {
11366 ODRDiagError(FirstParam->getLocation(),
11367 FirstParam->getSourceRange(), ParameterType)
11368 << (I + 1) << FirstParamType << true
11369 << ParamDecayedType->getOriginalType();
11370 } else {
11371 ODRDiagError(FirstParam->getLocation(),
11372 FirstParam->getSourceRange(), ParameterType)
11373 << (I + 1) << FirstParamType << false;
11374 }
11375
Vedant Kumar48b4f762018-04-14 01:40:48 +000011376 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011377 SecondParamType->getAs<DecayedType>()) {
11378 ODRDiagNote(SecondParam->getLocation(),
11379 SecondParam->getSourceRange(), ParameterType)
11380 << (I + 1) << SecondParamType << true
11381 << ParamDecayedType->getOriginalType();
11382 } else {
11383 ODRDiagNote(SecondParam->getLocation(),
11384 SecondParam->getSourceRange(), ParameterType)
11385 << (I + 1) << SecondParamType << false;
11386 }
11387 ParameterMismatch = true;
11388 break;
11389 }
11390
11391 const Expr *FirstInit = FirstParam->getInit();
11392 const Expr *SecondInit = SecondParam->getInit();
11393 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11394 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11395 ParameterSingleDefaultArgument)
11396 << (I + 1) << (FirstInit == nullptr)
11397 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11398 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11399 ParameterSingleDefaultArgument)
11400 << (I + 1) << (SecondInit == nullptr)
11401 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11402 ParameterMismatch = true;
11403 break;
11404 }
11405
11406 if (FirstInit && SecondInit &&
11407 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11408 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11409 ParameterDifferentDefaultArgument)
11410 << (I + 1) << FirstInit->getSourceRange();
11411 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11412 ParameterDifferentDefaultArgument)
11413 << (I + 1) << SecondInit->getSourceRange();
11414 ParameterMismatch = true;
11415 break;
11416 }
11417
11418 assert(ComputeSubDeclODRHash(FirstParam) ==
11419 ComputeSubDeclODRHash(SecondParam) &&
11420 "Undiagnosed parameter difference.");
11421 }
11422
11423 if (ParameterMismatch) {
11424 Diagnosed = true;
11425 break;
11426 }
11427
11428 // If no error has been generated before now, assume the problem is in
11429 // the body and generate a message.
11430 ODRDiagError(FirstFunction->getLocation(),
11431 FirstFunction->getSourceRange(), FunctionBody);
11432 ODRDiagNote(SecondFunction->getLocation(),
11433 SecondFunction->getSourceRange(), FunctionBody);
11434 Diagnosed = true;
11435 break;
11436 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011437 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011438 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11439 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011440
11441 // Issue ODR failures diagnostics for enums.
11442 for (auto &Merge : EnumOdrMergeFailures) {
11443 enum ODREnumDifference {
11444 SingleScopedEnum,
11445 EnumTagKeywordMismatch,
11446 SingleSpecifiedType,
11447 DifferentSpecifiedTypes,
11448 DifferentNumberEnumConstants,
11449 EnumConstantName,
11450 EnumConstantSingleInitilizer,
11451 EnumConstantDifferentInitilizer,
11452 };
11453
11454 // If we've already pointed out a specific problem with this enum, don't
11455 // bother issuing a general "something's different" diagnostic.
11456 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11457 continue;
11458
11459 EnumDecl *FirstEnum = Merge.first;
11460 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11461
11462 using DeclHashes =
11463 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11464 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11465 DeclHashes &Hashes, EnumDecl *Enum) {
11466 for (auto *D : Enum->decls()) {
11467 // Due to decl merging, the first EnumDecl is the parent of
11468 // Decls in both records.
11469 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11470 continue;
11471 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11472 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11473 ComputeSubDeclODRHash(D));
11474 }
11475 };
11476 DeclHashes FirstHashes;
11477 PopulateHashes(FirstHashes, FirstEnum);
11478 bool Diagnosed = false;
11479 for (auto &SecondEnum : Merge.second) {
11480
11481 if (FirstEnum == SecondEnum)
11482 continue;
11483
11484 std::string SecondModule =
11485 getOwningModuleNameForDiagnostic(SecondEnum);
11486
11487 auto ODRDiagError = [FirstEnum, &FirstModule,
11488 this](SourceLocation Loc, SourceRange Range,
11489 ODREnumDifference DiffType) {
11490 return Diag(Loc, diag::err_module_odr_violation_enum)
11491 << FirstEnum << FirstModule.empty() << FirstModule << Range
11492 << DiffType;
11493 };
11494 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11495 SourceRange Range,
11496 ODREnumDifference DiffType) {
11497 return Diag(Loc, diag::note_module_odr_violation_enum)
11498 << SecondModule << Range << DiffType;
11499 };
11500
11501 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11502 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11503 SingleScopedEnum)
11504 << FirstEnum->isScoped();
11505 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11506 SingleScopedEnum)
11507 << SecondEnum->isScoped();
11508 Diagnosed = true;
11509 continue;
11510 }
11511
11512 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11513 if (FirstEnum->isScopedUsingClassTag() !=
11514 SecondEnum->isScopedUsingClassTag()) {
11515 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11516 EnumTagKeywordMismatch)
11517 << FirstEnum->isScopedUsingClassTag();
11518 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11519 EnumTagKeywordMismatch)
11520 << SecondEnum->isScopedUsingClassTag();
11521 Diagnosed = true;
11522 continue;
11523 }
11524 }
11525
11526 QualType FirstUnderlyingType =
11527 FirstEnum->getIntegerTypeSourceInfo()
11528 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11529 : QualType();
11530 QualType SecondUnderlyingType =
11531 SecondEnum->getIntegerTypeSourceInfo()
11532 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11533 : QualType();
11534 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11535 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11536 SingleSpecifiedType)
11537 << !FirstUnderlyingType.isNull();
11538 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11539 SingleSpecifiedType)
11540 << !SecondUnderlyingType.isNull();
11541 Diagnosed = true;
11542 continue;
11543 }
11544
11545 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11546 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11547 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11548 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11549 DifferentSpecifiedTypes)
11550 << FirstUnderlyingType;
11551 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11552 DifferentSpecifiedTypes)
11553 << SecondUnderlyingType;
11554 Diagnosed = true;
11555 continue;
11556 }
11557 }
11558
11559 DeclHashes SecondHashes;
11560 PopulateHashes(SecondHashes, SecondEnum);
11561
11562 if (FirstHashes.size() != SecondHashes.size()) {
11563 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11564 DifferentNumberEnumConstants)
11565 << (int)FirstHashes.size();
11566 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11567 DifferentNumberEnumConstants)
11568 << (int)SecondHashes.size();
11569 Diagnosed = true;
11570 continue;
11571 }
11572
11573 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11574 if (FirstHashes[I].second == SecondHashes[I].second)
11575 continue;
11576 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11577 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11578
11579 if (FirstEnumConstant->getDeclName() !=
11580 SecondEnumConstant->getDeclName()) {
11581
11582 ODRDiagError(FirstEnumConstant->getLocation(),
11583 FirstEnumConstant->getSourceRange(), EnumConstantName)
11584 << I + 1 << FirstEnumConstant;
11585 ODRDiagNote(SecondEnumConstant->getLocation(),
11586 SecondEnumConstant->getSourceRange(), EnumConstantName)
11587 << I + 1 << SecondEnumConstant;
11588 Diagnosed = true;
11589 break;
11590 }
11591
11592 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11593 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11594 if (!FirstInit && !SecondInit)
11595 continue;
11596
11597 if (!FirstInit || !SecondInit) {
11598 ODRDiagError(FirstEnumConstant->getLocation(),
11599 FirstEnumConstant->getSourceRange(),
11600 EnumConstantSingleInitilizer)
11601 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11602 ODRDiagNote(SecondEnumConstant->getLocation(),
11603 SecondEnumConstant->getSourceRange(),
11604 EnumConstantSingleInitilizer)
11605 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11606 Diagnosed = true;
11607 break;
11608 }
11609
11610 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11611 ODRDiagError(FirstEnumConstant->getLocation(),
11612 FirstEnumConstant->getSourceRange(),
11613 EnumConstantDifferentInitilizer)
11614 << I + 1 << FirstEnumConstant;
11615 ODRDiagNote(SecondEnumConstant->getLocation(),
11616 SecondEnumConstant->getSourceRange(),
11617 EnumConstantDifferentInitilizer)
11618 << I + 1 << SecondEnumConstant;
11619 Diagnosed = true;
11620 break;
11621 }
11622 }
11623 }
11624
11625 (void)Diagnosed;
11626 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11627 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011628}
11629
Richard Smithce18a182015-07-14 00:26:00 +000011630void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011631 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011632 ReadTimer->startTimer();
11633}
11634
Guy Benyei11169dd2012-12-18 14:30:41 +000011635void ASTReader::FinishedDeserializing() {
11636 assert(NumCurrentElementsDeserializing &&
11637 "FinishedDeserializing not paired with StartedDeserializing");
11638 if (NumCurrentElementsDeserializing == 1) {
11639 // We decrease NumCurrentElementsDeserializing only after pending actions
11640 // are finished, to avoid recursively re-calling finishPendingActions().
11641 finishPendingActions();
11642 }
11643 --NumCurrentElementsDeserializing;
11644
Richard Smitha0ce9c42014-07-29 23:23:27 +000011645 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011646 // Propagate exception specification and deduced type updates along
11647 // redeclaration chains.
11648 //
11649 // We do this now rather than in finishPendingActions because we want to
11650 // be able to walk the complete redeclaration chains of the updated decls.
11651 while (!PendingExceptionSpecUpdates.empty() ||
11652 !PendingDeducedTypeUpdates.empty()) {
11653 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011654 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011655 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011656 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011657 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011658 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011659 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011660 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011661 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011662 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011663 }
Richard Smitha62d1982018-08-03 01:00:01 +000011664
11665 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11666 PendingDeducedTypeUpdates.clear();
11667 for (auto Update : DTUpdates) {
11668 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11669 // FIXME: If the return type is already deduced, check that it matches.
11670 getContext().adjustDeducedFunctionResultType(Update.first,
11671 Update.second);
11672 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011673 }
11674
Richard Smithce18a182015-07-14 00:26:00 +000011675 if (ReadTimer)
11676 ReadTimer->stopTimer();
11677
Richard Smith0f4e2c42015-08-06 04:23:48 +000011678 diagnoseOdrViolations();
11679
Richard Smith04d05b52014-03-23 00:27:18 +000011680 // We are not in recursive loading, so it's safe to pass the "interesting"
11681 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011682 if (Consumer)
11683 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011684 }
11685}
11686
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011687void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011688 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11689 // Remove any fake results before adding any real ones.
11690 auto It = PendingFakeLookupResults.find(II);
11691 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011692 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011693 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011694 // FIXME: this works around module+PCH performance issue.
11695 // Rather than erase the result from the map, which is O(n), just clear
11696 // the vector of NamedDecls.
11697 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011698 }
11699 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011700
11701 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11702 SemaObj->TUScope->AddDecl(D);
11703 } else if (SemaObj->TUScope) {
11704 // Adding the decl to IdResolver may have failed because it was already in
11705 // (even though it was not added in scope). If it is already in, make sure
11706 // it gets in the scope as well.
11707 if (std::find(SemaObj->IdResolver.begin(Name),
11708 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11709 SemaObj->TUScope->AddDecl(D);
11710 }
11711}
11712
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011713ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
11714 ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011715 const PCHContainerReader &PCHContainerRdr,
11716 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11717 StringRef isysroot, bool DisableValidation,
11718 bool AllowASTWithCompilerErrors,
11719 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11720 bool UseGlobalIndex,
11721 std::unique_ptr<llvm::Timer> ReadTimer)
11722 : Listener(DisableValidation
11723 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11724 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011725 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011726 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +000011727 ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
11728 PCHContainerRdr, PP.getHeaderSearchInfo()),
11729 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011730 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011731 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11732 AllowConfigurationMismatch(AllowConfigurationMismatch),
11733 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011734 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011735 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011736
11737 for (const auto &Ext : Extensions) {
11738 auto BlockName = Ext->getExtensionMetadata().BlockName;
11739 auto Known = ModuleFileExtensions.find(BlockName);
11740 if (Known != ModuleFileExtensions.end()) {
11741 Diags.Report(diag::warn_duplicate_module_file_extension)
11742 << BlockName;
11743 continue;
11744 }
11745
11746 ModuleFileExtensions.insert({BlockName, Ext});
11747 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011748}
11749
11750ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011751 if (OwnsDeserializationListener)
11752 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011753}
Richard Smith10379092016-05-06 23:14:07 +000011754
11755IdentifierResolver &ASTReader::getIdResolver() {
11756 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11757}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011758
11759unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11760 unsigned AbbrevID) {
11761 Idx = 0;
11762 Record.clear();
11763 return Cursor.readRecord(AbbrevID, Record);
11764}
Kelvin Libe286f52018-09-15 13:54:15 +000011765//===----------------------------------------------------------------------===//
11766//// OMPClauseReader implementation
11767////===----------------------------------------------------------------------===//
11768
11769OMPClause *OMPClauseReader::readClause() {
11770 OMPClause *C;
11771 switch (Record.readInt()) {
11772 case OMPC_if:
11773 C = new (Context) OMPIfClause();
11774 break;
11775 case OMPC_final:
11776 C = new (Context) OMPFinalClause();
11777 break;
11778 case OMPC_num_threads:
11779 C = new (Context) OMPNumThreadsClause();
11780 break;
11781 case OMPC_safelen:
11782 C = new (Context) OMPSafelenClause();
11783 break;
11784 case OMPC_simdlen:
11785 C = new (Context) OMPSimdlenClause();
11786 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011787 case OMPC_allocator:
11788 C = new (Context) OMPAllocatorClause();
11789 break;
Kelvin Libe286f52018-09-15 13:54:15 +000011790 case OMPC_collapse:
11791 C = new (Context) OMPCollapseClause();
11792 break;
11793 case OMPC_default:
11794 C = new (Context) OMPDefaultClause();
11795 break;
11796 case OMPC_proc_bind:
11797 C = new (Context) OMPProcBindClause();
11798 break;
11799 case OMPC_schedule:
11800 C = new (Context) OMPScheduleClause();
11801 break;
11802 case OMPC_ordered:
11803 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11804 break;
11805 case OMPC_nowait:
11806 C = new (Context) OMPNowaitClause();
11807 break;
11808 case OMPC_untied:
11809 C = new (Context) OMPUntiedClause();
11810 break;
11811 case OMPC_mergeable:
11812 C = new (Context) OMPMergeableClause();
11813 break;
11814 case OMPC_read:
11815 C = new (Context) OMPReadClause();
11816 break;
11817 case OMPC_write:
11818 C = new (Context) OMPWriteClause();
11819 break;
11820 case OMPC_update:
11821 C = new (Context) OMPUpdateClause();
11822 break;
11823 case OMPC_capture:
11824 C = new (Context) OMPCaptureClause();
11825 break;
11826 case OMPC_seq_cst:
11827 C = new (Context) OMPSeqCstClause();
11828 break;
11829 case OMPC_threads:
11830 C = new (Context) OMPThreadsClause();
11831 break;
11832 case OMPC_simd:
11833 C = new (Context) OMPSIMDClause();
11834 break;
11835 case OMPC_nogroup:
11836 C = new (Context) OMPNogroupClause();
11837 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011838 case OMPC_unified_address:
11839 C = new (Context) OMPUnifiedAddressClause();
11840 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011841 case OMPC_unified_shared_memory:
11842 C = new (Context) OMPUnifiedSharedMemoryClause();
11843 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011844 case OMPC_reverse_offload:
11845 C = new (Context) OMPReverseOffloadClause();
11846 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011847 case OMPC_dynamic_allocators:
11848 C = new (Context) OMPDynamicAllocatorsClause();
11849 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011850 case OMPC_atomic_default_mem_order:
11851 C = new (Context) OMPAtomicDefaultMemOrderClause();
11852 break;
11853 case OMPC_private:
Kelvin Libe286f52018-09-15 13:54:15 +000011854 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11855 break;
11856 case OMPC_firstprivate:
11857 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11858 break;
11859 case OMPC_lastprivate:
11860 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11861 break;
11862 case OMPC_shared:
11863 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11864 break;
11865 case OMPC_reduction:
11866 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11867 break;
11868 case OMPC_task_reduction:
11869 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11870 break;
11871 case OMPC_in_reduction:
11872 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11873 break;
11874 case OMPC_linear:
11875 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11876 break;
11877 case OMPC_aligned:
11878 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11879 break;
11880 case OMPC_copyin:
11881 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11882 break;
11883 case OMPC_copyprivate:
11884 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11885 break;
11886 case OMPC_flush:
11887 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11888 break;
11889 case OMPC_depend: {
11890 unsigned NumVars = Record.readInt();
11891 unsigned NumLoops = Record.readInt();
11892 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11893 break;
11894 }
11895 case OMPC_device:
11896 C = new (Context) OMPDeviceClause();
11897 break;
11898 case OMPC_map: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011899 OMPMappableExprListSizeTy Sizes;
11900 Sizes.NumVars = Record.readInt();
11901 Sizes.NumUniqueDeclarations = Record.readInt();
11902 Sizes.NumComponentLists = Record.readInt();
11903 Sizes.NumComponents = Record.readInt();
11904 C = OMPMapClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011905 break;
11906 }
11907 case OMPC_num_teams:
11908 C = new (Context) OMPNumTeamsClause();
11909 break;
11910 case OMPC_thread_limit:
11911 C = new (Context) OMPThreadLimitClause();
11912 break;
11913 case OMPC_priority:
11914 C = new (Context) OMPPriorityClause();
11915 break;
11916 case OMPC_grainsize:
11917 C = new (Context) OMPGrainsizeClause();
11918 break;
11919 case OMPC_num_tasks:
11920 C = new (Context) OMPNumTasksClause();
11921 break;
11922 case OMPC_hint:
11923 C = new (Context) OMPHintClause();
11924 break;
11925 case OMPC_dist_schedule:
11926 C = new (Context) OMPDistScheduleClause();
11927 break;
11928 case OMPC_defaultmap:
11929 C = new (Context) OMPDefaultmapClause();
11930 break;
11931 case OMPC_to: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011932 OMPMappableExprListSizeTy Sizes;
11933 Sizes.NumVars = Record.readInt();
11934 Sizes.NumUniqueDeclarations = Record.readInt();
11935 Sizes.NumComponentLists = Record.readInt();
11936 Sizes.NumComponents = Record.readInt();
11937 C = OMPToClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011938 break;
11939 }
11940 case OMPC_from: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011941 OMPMappableExprListSizeTy Sizes;
11942 Sizes.NumVars = Record.readInt();
11943 Sizes.NumUniqueDeclarations = Record.readInt();
11944 Sizes.NumComponentLists = Record.readInt();
11945 Sizes.NumComponents = Record.readInt();
11946 C = OMPFromClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011947 break;
11948 }
11949 case OMPC_use_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011950 OMPMappableExprListSizeTy Sizes;
11951 Sizes.NumVars = Record.readInt();
11952 Sizes.NumUniqueDeclarations = Record.readInt();
11953 Sizes.NumComponentLists = Record.readInt();
11954 Sizes.NumComponents = Record.readInt();
11955 C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011956 break;
11957 }
11958 case OMPC_is_device_ptr: {
Michael Kruse4304e9d2019-02-19 16:38:20 +000011959 OMPMappableExprListSizeTy Sizes;
11960 Sizes.NumVars = Record.readInt();
11961 Sizes.NumUniqueDeclarations = Record.readInt();
11962 Sizes.NumComponentLists = Record.readInt();
11963 Sizes.NumComponents = Record.readInt();
11964 C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
Kelvin Libe286f52018-09-15 13:54:15 +000011965 break;
11966 }
Alexey Bataeve04483e2019-03-27 14:14:31 +000011967 case OMPC_allocate:
11968 C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
11969 break;
Kelvin Libe286f52018-09-15 13:54:15 +000011970 }
11971 Visit(C);
11972 C->setLocStart(Record.readSourceLocation());
11973 C->setLocEnd(Record.readSourceLocation());
11974
11975 return C;
11976}
11977
11978void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11979 C->setPreInitStmt(Record.readSubStmt(),
11980 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11981}
11982
11983void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11984 VisitOMPClauseWithPreInit(C);
11985 C->setPostUpdateExpr(Record.readSubExpr());
11986}
11987
11988void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11989 VisitOMPClauseWithPreInit(C);
11990 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11991 C->setNameModifierLoc(Record.readSourceLocation());
11992 C->setColonLoc(Record.readSourceLocation());
11993 C->setCondition(Record.readSubExpr());
11994 C->setLParenLoc(Record.readSourceLocation());
11995}
11996
11997void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11998 C->setCondition(Record.readSubExpr());
11999 C->setLParenLoc(Record.readSourceLocation());
12000}
12001
12002void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
12003 VisitOMPClauseWithPreInit(C);
12004 C->setNumThreads(Record.readSubExpr());
12005 C->setLParenLoc(Record.readSourceLocation());
12006}
12007
12008void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
12009 C->setSafelen(Record.readSubExpr());
12010 C->setLParenLoc(Record.readSourceLocation());
12011}
12012
12013void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
12014 C->setSimdlen(Record.readSubExpr());
12015 C->setLParenLoc(Record.readSourceLocation());
12016}
12017
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012018void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
12019 C->setAllocator(Record.readExpr());
12020 C->setLParenLoc(Record.readSourceLocation());
12021}
12022
Kelvin Libe286f52018-09-15 13:54:15 +000012023void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
12024 C->setNumForLoops(Record.readSubExpr());
12025 C->setLParenLoc(Record.readSourceLocation());
12026}
12027
12028void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
12029 C->setDefaultKind(
12030 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
12031 C->setLParenLoc(Record.readSourceLocation());
12032 C->setDefaultKindKwLoc(Record.readSourceLocation());
12033}
12034
12035void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
12036 C->setProcBindKind(
12037 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
12038 C->setLParenLoc(Record.readSourceLocation());
12039 C->setProcBindKindKwLoc(Record.readSourceLocation());
12040}
12041
12042void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
12043 VisitOMPClauseWithPreInit(C);
12044 C->setScheduleKind(
12045 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
12046 C->setFirstScheduleModifier(
12047 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12048 C->setSecondScheduleModifier(
12049 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
12050 C->setChunkSize(Record.readSubExpr());
12051 C->setLParenLoc(Record.readSourceLocation());
12052 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
12053 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
12054 C->setScheduleKindLoc(Record.readSourceLocation());
12055 C->setCommaLoc(Record.readSourceLocation());
12056}
12057
12058void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
12059 C->setNumForLoops(Record.readSubExpr());
12060 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12061 C->setLoopNumIterations(I, Record.readSubExpr());
12062 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
12063 C->setLoopCounter(I, Record.readSubExpr());
12064 C->setLParenLoc(Record.readSourceLocation());
12065}
12066
12067void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
12068
12069void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
12070
12071void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
12072
12073void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
12074
12075void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
12076
12077void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
12078
12079void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
12080
12081void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
12082
12083void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
12084
12085void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
12086
12087void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
12088
Kelvin Li1408f912018-09-26 04:28:39 +000012089void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
12090
Patrick Lyster4a370b92018-10-01 13:47:43 +000012091void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
12092 OMPUnifiedSharedMemoryClause *) {}
12093
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012094void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
12095
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012096void
12097OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
12098}
12099
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012100void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
12101 OMPAtomicDefaultMemOrderClause *C) {
12102 C->setAtomicDefaultMemOrderKind(
12103 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
12104 C->setLParenLoc(Record.readSourceLocation());
12105 C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
12106}
12107
Kelvin Libe286f52018-09-15 13:54:15 +000012108void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
12109 C->setLParenLoc(Record.readSourceLocation());
12110 unsigned NumVars = C->varlist_size();
12111 SmallVector<Expr *, 16> Vars;
12112 Vars.reserve(NumVars);
12113 for (unsigned i = 0; i != NumVars; ++i)
12114 Vars.push_back(Record.readSubExpr());
12115 C->setVarRefs(Vars);
12116 Vars.clear();
12117 for (unsigned i = 0; i != NumVars; ++i)
12118 Vars.push_back(Record.readSubExpr());
12119 C->setPrivateCopies(Vars);
12120}
12121
12122void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
12123 VisitOMPClauseWithPreInit(C);
12124 C->setLParenLoc(Record.readSourceLocation());
12125 unsigned NumVars = C->varlist_size();
12126 SmallVector<Expr *, 16> Vars;
12127 Vars.reserve(NumVars);
12128 for (unsigned i = 0; i != NumVars; ++i)
12129 Vars.push_back(Record.readSubExpr());
12130 C->setVarRefs(Vars);
12131 Vars.clear();
12132 for (unsigned i = 0; i != NumVars; ++i)
12133 Vars.push_back(Record.readSubExpr());
12134 C->setPrivateCopies(Vars);
12135 Vars.clear();
12136 for (unsigned i = 0; i != NumVars; ++i)
12137 Vars.push_back(Record.readSubExpr());
12138 C->setInits(Vars);
12139}
12140
12141void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
12142 VisitOMPClauseWithPostUpdate(C);
12143 C->setLParenLoc(Record.readSourceLocation());
12144 unsigned NumVars = C->varlist_size();
12145 SmallVector<Expr *, 16> Vars;
12146 Vars.reserve(NumVars);
12147 for (unsigned i = 0; i != NumVars; ++i)
12148 Vars.push_back(Record.readSubExpr());
12149 C->setVarRefs(Vars);
12150 Vars.clear();
12151 for (unsigned i = 0; i != NumVars; ++i)
12152 Vars.push_back(Record.readSubExpr());
12153 C->setPrivateCopies(Vars);
12154 Vars.clear();
12155 for (unsigned i = 0; i != NumVars; ++i)
12156 Vars.push_back(Record.readSubExpr());
12157 C->setSourceExprs(Vars);
12158 Vars.clear();
12159 for (unsigned i = 0; i != NumVars; ++i)
12160 Vars.push_back(Record.readSubExpr());
12161 C->setDestinationExprs(Vars);
12162 Vars.clear();
12163 for (unsigned i = 0; i != NumVars; ++i)
12164 Vars.push_back(Record.readSubExpr());
12165 C->setAssignmentOps(Vars);
12166}
12167
12168void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12169 C->setLParenLoc(Record.readSourceLocation());
12170 unsigned NumVars = C->varlist_size();
12171 SmallVector<Expr *, 16> Vars;
12172 Vars.reserve(NumVars);
12173 for (unsigned i = 0; i != NumVars; ++i)
12174 Vars.push_back(Record.readSubExpr());
12175 C->setVarRefs(Vars);
12176}
12177
12178void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12179 VisitOMPClauseWithPostUpdate(C);
12180 C->setLParenLoc(Record.readSourceLocation());
12181 C->setColonLoc(Record.readSourceLocation());
12182 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12183 DeclarationNameInfo DNI;
12184 Record.readDeclarationNameInfo(DNI);
12185 C->setQualifierLoc(NNSL);
12186 C->setNameInfo(DNI);
12187
12188 unsigned NumVars = C->varlist_size();
12189 SmallVector<Expr *, 16> Vars;
12190 Vars.reserve(NumVars);
12191 for (unsigned i = 0; i != NumVars; ++i)
12192 Vars.push_back(Record.readSubExpr());
12193 C->setVarRefs(Vars);
12194 Vars.clear();
12195 for (unsigned i = 0; i != NumVars; ++i)
12196 Vars.push_back(Record.readSubExpr());
12197 C->setPrivates(Vars);
12198 Vars.clear();
12199 for (unsigned i = 0; i != NumVars; ++i)
12200 Vars.push_back(Record.readSubExpr());
12201 C->setLHSExprs(Vars);
12202 Vars.clear();
12203 for (unsigned i = 0; i != NumVars; ++i)
12204 Vars.push_back(Record.readSubExpr());
12205 C->setRHSExprs(Vars);
12206 Vars.clear();
12207 for (unsigned i = 0; i != NumVars; ++i)
12208 Vars.push_back(Record.readSubExpr());
12209 C->setReductionOps(Vars);
12210}
12211
12212void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12213 VisitOMPClauseWithPostUpdate(C);
12214 C->setLParenLoc(Record.readSourceLocation());
12215 C->setColonLoc(Record.readSourceLocation());
12216 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12217 DeclarationNameInfo DNI;
12218 Record.readDeclarationNameInfo(DNI);
12219 C->setQualifierLoc(NNSL);
12220 C->setNameInfo(DNI);
12221
12222 unsigned NumVars = C->varlist_size();
12223 SmallVector<Expr *, 16> Vars;
12224 Vars.reserve(NumVars);
12225 for (unsigned I = 0; I != NumVars; ++I)
12226 Vars.push_back(Record.readSubExpr());
12227 C->setVarRefs(Vars);
12228 Vars.clear();
12229 for (unsigned I = 0; I != NumVars; ++I)
12230 Vars.push_back(Record.readSubExpr());
12231 C->setPrivates(Vars);
12232 Vars.clear();
12233 for (unsigned I = 0; I != NumVars; ++I)
12234 Vars.push_back(Record.readSubExpr());
12235 C->setLHSExprs(Vars);
12236 Vars.clear();
12237 for (unsigned I = 0; I != NumVars; ++I)
12238 Vars.push_back(Record.readSubExpr());
12239 C->setRHSExprs(Vars);
12240 Vars.clear();
12241 for (unsigned I = 0; I != NumVars; ++I)
12242 Vars.push_back(Record.readSubExpr());
12243 C->setReductionOps(Vars);
12244}
12245
12246void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12247 VisitOMPClauseWithPostUpdate(C);
12248 C->setLParenLoc(Record.readSourceLocation());
12249 C->setColonLoc(Record.readSourceLocation());
12250 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12251 DeclarationNameInfo DNI;
12252 Record.readDeclarationNameInfo(DNI);
12253 C->setQualifierLoc(NNSL);
12254 C->setNameInfo(DNI);
12255
12256 unsigned NumVars = C->varlist_size();
12257 SmallVector<Expr *, 16> Vars;
12258 Vars.reserve(NumVars);
12259 for (unsigned I = 0; I != NumVars; ++I)
12260 Vars.push_back(Record.readSubExpr());
12261 C->setVarRefs(Vars);
12262 Vars.clear();
12263 for (unsigned I = 0; I != NumVars; ++I)
12264 Vars.push_back(Record.readSubExpr());
12265 C->setPrivates(Vars);
12266 Vars.clear();
12267 for (unsigned I = 0; I != NumVars; ++I)
12268 Vars.push_back(Record.readSubExpr());
12269 C->setLHSExprs(Vars);
12270 Vars.clear();
12271 for (unsigned I = 0; I != NumVars; ++I)
12272 Vars.push_back(Record.readSubExpr());
12273 C->setRHSExprs(Vars);
12274 Vars.clear();
12275 for (unsigned I = 0; I != NumVars; ++I)
12276 Vars.push_back(Record.readSubExpr());
12277 C->setReductionOps(Vars);
12278 Vars.clear();
12279 for (unsigned I = 0; I != NumVars; ++I)
12280 Vars.push_back(Record.readSubExpr());
12281 C->setTaskgroupDescriptors(Vars);
12282}
12283
12284void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12285 VisitOMPClauseWithPostUpdate(C);
12286 C->setLParenLoc(Record.readSourceLocation());
12287 C->setColonLoc(Record.readSourceLocation());
12288 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12289 C->setModifierLoc(Record.readSourceLocation());
12290 unsigned NumVars = C->varlist_size();
12291 SmallVector<Expr *, 16> Vars;
12292 Vars.reserve(NumVars);
12293 for (unsigned i = 0; i != NumVars; ++i)
12294 Vars.push_back(Record.readSubExpr());
12295 C->setVarRefs(Vars);
12296 Vars.clear();
12297 for (unsigned i = 0; i != NumVars; ++i)
12298 Vars.push_back(Record.readSubExpr());
12299 C->setPrivates(Vars);
12300 Vars.clear();
12301 for (unsigned i = 0; i != NumVars; ++i)
12302 Vars.push_back(Record.readSubExpr());
12303 C->setInits(Vars);
12304 Vars.clear();
12305 for (unsigned i = 0; i != NumVars; ++i)
12306 Vars.push_back(Record.readSubExpr());
12307 C->setUpdates(Vars);
12308 Vars.clear();
12309 for (unsigned i = 0; i != NumVars; ++i)
12310 Vars.push_back(Record.readSubExpr());
12311 C->setFinals(Vars);
12312 C->setStep(Record.readSubExpr());
12313 C->setCalcStep(Record.readSubExpr());
12314}
12315
12316void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12317 C->setLParenLoc(Record.readSourceLocation());
12318 C->setColonLoc(Record.readSourceLocation());
12319 unsigned NumVars = C->varlist_size();
12320 SmallVector<Expr *, 16> Vars;
12321 Vars.reserve(NumVars);
12322 for (unsigned i = 0; i != NumVars; ++i)
12323 Vars.push_back(Record.readSubExpr());
12324 C->setVarRefs(Vars);
12325 C->setAlignment(Record.readSubExpr());
12326}
12327
12328void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12329 C->setLParenLoc(Record.readSourceLocation());
12330 unsigned NumVars = C->varlist_size();
12331 SmallVector<Expr *, 16> Exprs;
12332 Exprs.reserve(NumVars);
12333 for (unsigned i = 0; i != NumVars; ++i)
12334 Exprs.push_back(Record.readSubExpr());
12335 C->setVarRefs(Exprs);
12336 Exprs.clear();
12337 for (unsigned i = 0; i != NumVars; ++i)
12338 Exprs.push_back(Record.readSubExpr());
12339 C->setSourceExprs(Exprs);
12340 Exprs.clear();
12341 for (unsigned i = 0; i != NumVars; ++i)
12342 Exprs.push_back(Record.readSubExpr());
12343 C->setDestinationExprs(Exprs);
12344 Exprs.clear();
12345 for (unsigned i = 0; i != NumVars; ++i)
12346 Exprs.push_back(Record.readSubExpr());
12347 C->setAssignmentOps(Exprs);
12348}
12349
12350void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12351 C->setLParenLoc(Record.readSourceLocation());
12352 unsigned NumVars = C->varlist_size();
12353 SmallVector<Expr *, 16> Exprs;
12354 Exprs.reserve(NumVars);
12355 for (unsigned i = 0; i != NumVars; ++i)
12356 Exprs.push_back(Record.readSubExpr());
12357 C->setVarRefs(Exprs);
12358 Exprs.clear();
12359 for (unsigned i = 0; i != NumVars; ++i)
12360 Exprs.push_back(Record.readSubExpr());
12361 C->setSourceExprs(Exprs);
12362 Exprs.clear();
12363 for (unsigned i = 0; i != NumVars; ++i)
12364 Exprs.push_back(Record.readSubExpr());
12365 C->setDestinationExprs(Exprs);
12366 Exprs.clear();
12367 for (unsigned i = 0; i != NumVars; ++i)
12368 Exprs.push_back(Record.readSubExpr());
12369 C->setAssignmentOps(Exprs);
12370}
12371
12372void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12373 C->setLParenLoc(Record.readSourceLocation());
12374 unsigned NumVars = C->varlist_size();
12375 SmallVector<Expr *, 16> Vars;
12376 Vars.reserve(NumVars);
12377 for (unsigned i = 0; i != NumVars; ++i)
12378 Vars.push_back(Record.readSubExpr());
12379 C->setVarRefs(Vars);
12380}
12381
12382void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12383 C->setLParenLoc(Record.readSourceLocation());
12384 C->setDependencyKind(
12385 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12386 C->setDependencyLoc(Record.readSourceLocation());
12387 C->setColonLoc(Record.readSourceLocation());
12388 unsigned NumVars = C->varlist_size();
12389 SmallVector<Expr *, 16> Vars;
12390 Vars.reserve(NumVars);
12391 for (unsigned I = 0; I != NumVars; ++I)
12392 Vars.push_back(Record.readSubExpr());
12393 C->setVarRefs(Vars);
12394 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12395 C->setLoopData(I, Record.readSubExpr());
12396}
12397
12398void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12399 VisitOMPClauseWithPreInit(C);
12400 C->setDevice(Record.readSubExpr());
12401 C->setLParenLoc(Record.readSourceLocation());
12402}
12403
12404void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12405 C->setLParenLoc(Record.readSourceLocation());
Kelvin Lief579432018-12-18 22:18:41 +000012406 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
12407 C->setMapTypeModifier(
12408 I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
12409 C->setMapTypeModifierLoc(I, Record.readSourceLocation());
12410 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000012411 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12412 DeclarationNameInfo DNI;
12413 Record.readDeclarationNameInfo(DNI);
12414 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012415 C->setMapType(
12416 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12417 C->setMapLoc(Record.readSourceLocation());
12418 C->setColonLoc(Record.readSourceLocation());
12419 auto NumVars = C->varlist_size();
12420 auto UniqueDecls = C->getUniqueDeclarationsNum();
12421 auto TotalLists = C->getTotalComponentListNum();
12422 auto TotalComponents = C->getTotalComponentsNum();
12423
12424 SmallVector<Expr *, 16> Vars;
12425 Vars.reserve(NumVars);
12426 for (unsigned i = 0; i != NumVars; ++i)
Michael Kruse251e1482019-02-01 20:25:04 +000012427 Vars.push_back(Record.readExpr());
Kelvin Libe286f52018-09-15 13:54:15 +000012428 C->setVarRefs(Vars);
12429
Michael Kruse4304e9d2019-02-19 16:38:20 +000012430 SmallVector<Expr *, 16> UDMappers;
12431 UDMappers.reserve(NumVars);
12432 for (unsigned I = 0; I < NumVars; ++I)
12433 UDMappers.push_back(Record.readExpr());
12434 C->setUDMapperRefs(UDMappers);
12435
Kelvin Libe286f52018-09-15 13:54:15 +000012436 SmallVector<ValueDecl *, 16> Decls;
12437 Decls.reserve(UniqueDecls);
12438 for (unsigned i = 0; i < UniqueDecls; ++i)
12439 Decls.push_back(Record.readDeclAs<ValueDecl>());
12440 C->setUniqueDecls(Decls);
12441
12442 SmallVector<unsigned, 16> ListsPerDecl;
12443 ListsPerDecl.reserve(UniqueDecls);
12444 for (unsigned i = 0; i < UniqueDecls; ++i)
12445 ListsPerDecl.push_back(Record.readInt());
12446 C->setDeclNumLists(ListsPerDecl);
12447
12448 SmallVector<unsigned, 32> ListSizes;
12449 ListSizes.reserve(TotalLists);
12450 for (unsigned i = 0; i < TotalLists; ++i)
12451 ListSizes.push_back(Record.readInt());
12452 C->setComponentListSizes(ListSizes);
12453
12454 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12455 Components.reserve(TotalComponents);
12456 for (unsigned i = 0; i < TotalComponents; ++i) {
Michael Kruse251e1482019-02-01 20:25:04 +000012457 Expr *AssociatedExpr = Record.readExpr();
Kelvin Libe286f52018-09-15 13:54:15 +000012458 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12459 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12460 AssociatedExpr, AssociatedDecl));
12461 }
12462 C->setComponents(Components, ListSizes);
12463}
12464
Alexey Bataeve04483e2019-03-27 14:14:31 +000012465void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
12466 C->setLParenLoc(Record.readSourceLocation());
12467 C->setColonLoc(Record.readSourceLocation());
12468 C->setAllocator(Record.readSubExpr());
12469 unsigned NumVars = C->varlist_size();
12470 SmallVector<Expr *, 16> Vars;
12471 Vars.reserve(NumVars);
12472 for (unsigned i = 0; i != NumVars; ++i)
12473 Vars.push_back(Record.readSubExpr());
12474 C->setVarRefs(Vars);
12475}
12476
Kelvin Libe286f52018-09-15 13:54:15 +000012477void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12478 VisitOMPClauseWithPreInit(C);
12479 C->setNumTeams(Record.readSubExpr());
12480 C->setLParenLoc(Record.readSourceLocation());
12481}
12482
12483void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12484 VisitOMPClauseWithPreInit(C);
12485 C->setThreadLimit(Record.readSubExpr());
12486 C->setLParenLoc(Record.readSourceLocation());
12487}
12488
12489void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12490 C->setPriority(Record.readSubExpr());
12491 C->setLParenLoc(Record.readSourceLocation());
12492}
12493
12494void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12495 C->setGrainsize(Record.readSubExpr());
12496 C->setLParenLoc(Record.readSourceLocation());
12497}
12498
12499void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12500 C->setNumTasks(Record.readSubExpr());
12501 C->setLParenLoc(Record.readSourceLocation());
12502}
12503
12504void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12505 C->setHint(Record.readSubExpr());
12506 C->setLParenLoc(Record.readSourceLocation());
12507}
12508
12509void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12510 VisitOMPClauseWithPreInit(C);
12511 C->setDistScheduleKind(
12512 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12513 C->setChunkSize(Record.readSubExpr());
12514 C->setLParenLoc(Record.readSourceLocation());
12515 C->setDistScheduleKindLoc(Record.readSourceLocation());
12516 C->setCommaLoc(Record.readSourceLocation());
12517}
12518
12519void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12520 C->setDefaultmapKind(
12521 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12522 C->setDefaultmapModifier(
12523 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12524 C->setLParenLoc(Record.readSourceLocation());
12525 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12526 C->setDefaultmapKindLoc(Record.readSourceLocation());
12527}
12528
12529void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12530 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse01f670d2019-02-22 22:29:42 +000012531 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12532 DeclarationNameInfo DNI;
12533 Record.readDeclarationNameInfo(DNI);
12534 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012535 auto NumVars = C->varlist_size();
12536 auto UniqueDecls = C->getUniqueDeclarationsNum();
12537 auto TotalLists = C->getTotalComponentListNum();
12538 auto TotalComponents = C->getTotalComponentsNum();
12539
12540 SmallVector<Expr *, 16> Vars;
12541 Vars.reserve(NumVars);
12542 for (unsigned i = 0; i != NumVars; ++i)
12543 Vars.push_back(Record.readSubExpr());
12544 C->setVarRefs(Vars);
12545
Michael Kruse01f670d2019-02-22 22:29:42 +000012546 SmallVector<Expr *, 16> UDMappers;
12547 UDMappers.reserve(NumVars);
12548 for (unsigned I = 0; I < NumVars; ++I)
12549 UDMappers.push_back(Record.readSubExpr());
12550 C->setUDMapperRefs(UDMappers);
12551
Kelvin Libe286f52018-09-15 13:54:15 +000012552 SmallVector<ValueDecl *, 16> Decls;
12553 Decls.reserve(UniqueDecls);
12554 for (unsigned i = 0; i < UniqueDecls; ++i)
12555 Decls.push_back(Record.readDeclAs<ValueDecl>());
12556 C->setUniqueDecls(Decls);
12557
12558 SmallVector<unsigned, 16> ListsPerDecl;
12559 ListsPerDecl.reserve(UniqueDecls);
12560 for (unsigned i = 0; i < UniqueDecls; ++i)
12561 ListsPerDecl.push_back(Record.readInt());
12562 C->setDeclNumLists(ListsPerDecl);
12563
12564 SmallVector<unsigned, 32> ListSizes;
12565 ListSizes.reserve(TotalLists);
12566 for (unsigned i = 0; i < TotalLists; ++i)
12567 ListSizes.push_back(Record.readInt());
12568 C->setComponentListSizes(ListSizes);
12569
12570 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12571 Components.reserve(TotalComponents);
12572 for (unsigned i = 0; i < TotalComponents; ++i) {
12573 Expr *AssociatedExpr = Record.readSubExpr();
12574 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12575 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12576 AssociatedExpr, AssociatedDecl));
12577 }
12578 C->setComponents(Components, ListSizes);
12579}
12580
12581void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12582 C->setLParenLoc(Record.readSourceLocation());
Michael Kruse0336c752019-02-25 20:34:15 +000012583 C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
12584 DeclarationNameInfo DNI;
12585 Record.readDeclarationNameInfo(DNI);
12586 C->setMapperIdInfo(DNI);
Kelvin Libe286f52018-09-15 13:54:15 +000012587 auto NumVars = C->varlist_size();
12588 auto UniqueDecls = C->getUniqueDeclarationsNum();
12589 auto TotalLists = C->getTotalComponentListNum();
12590 auto TotalComponents = C->getTotalComponentsNum();
12591
12592 SmallVector<Expr *, 16> Vars;
12593 Vars.reserve(NumVars);
12594 for (unsigned i = 0; i != NumVars; ++i)
12595 Vars.push_back(Record.readSubExpr());
12596 C->setVarRefs(Vars);
12597
Michael Kruse0336c752019-02-25 20:34:15 +000012598 SmallVector<Expr *, 16> UDMappers;
12599 UDMappers.reserve(NumVars);
12600 for (unsigned I = 0; I < NumVars; ++I)
12601 UDMappers.push_back(Record.readSubExpr());
12602 C->setUDMapperRefs(UDMappers);
12603
Kelvin Libe286f52018-09-15 13:54:15 +000012604 SmallVector<ValueDecl *, 16> Decls;
12605 Decls.reserve(UniqueDecls);
12606 for (unsigned i = 0; i < UniqueDecls; ++i)
12607 Decls.push_back(Record.readDeclAs<ValueDecl>());
12608 C->setUniqueDecls(Decls);
12609
12610 SmallVector<unsigned, 16> ListsPerDecl;
12611 ListsPerDecl.reserve(UniqueDecls);
12612 for (unsigned i = 0; i < UniqueDecls; ++i)
12613 ListsPerDecl.push_back(Record.readInt());
12614 C->setDeclNumLists(ListsPerDecl);
12615
12616 SmallVector<unsigned, 32> ListSizes;
12617 ListSizes.reserve(TotalLists);
12618 for (unsigned i = 0; i < TotalLists; ++i)
12619 ListSizes.push_back(Record.readInt());
12620 C->setComponentListSizes(ListSizes);
12621
12622 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12623 Components.reserve(TotalComponents);
12624 for (unsigned i = 0; i < TotalComponents; ++i) {
12625 Expr *AssociatedExpr = Record.readSubExpr();
12626 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12627 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12628 AssociatedExpr, AssociatedDecl));
12629 }
12630 C->setComponents(Components, ListSizes);
12631}
12632
12633void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12634 C->setLParenLoc(Record.readSourceLocation());
12635 auto NumVars = C->varlist_size();
12636 auto UniqueDecls = C->getUniqueDeclarationsNum();
12637 auto TotalLists = C->getTotalComponentListNum();
12638 auto TotalComponents = C->getTotalComponentsNum();
12639
12640 SmallVector<Expr *, 16> Vars;
12641 Vars.reserve(NumVars);
12642 for (unsigned i = 0; i != NumVars; ++i)
12643 Vars.push_back(Record.readSubExpr());
12644 C->setVarRefs(Vars);
12645 Vars.clear();
12646 for (unsigned i = 0; i != NumVars; ++i)
12647 Vars.push_back(Record.readSubExpr());
12648 C->setPrivateCopies(Vars);
12649 Vars.clear();
12650 for (unsigned i = 0; i != NumVars; ++i)
12651 Vars.push_back(Record.readSubExpr());
12652 C->setInits(Vars);
12653
12654 SmallVector<ValueDecl *, 16> Decls;
12655 Decls.reserve(UniqueDecls);
12656 for (unsigned i = 0; i < UniqueDecls; ++i)
12657 Decls.push_back(Record.readDeclAs<ValueDecl>());
12658 C->setUniqueDecls(Decls);
12659
12660 SmallVector<unsigned, 16> ListsPerDecl;
12661 ListsPerDecl.reserve(UniqueDecls);
12662 for (unsigned i = 0; i < UniqueDecls; ++i)
12663 ListsPerDecl.push_back(Record.readInt());
12664 C->setDeclNumLists(ListsPerDecl);
12665
12666 SmallVector<unsigned, 32> ListSizes;
12667 ListSizes.reserve(TotalLists);
12668 for (unsigned i = 0; i < TotalLists; ++i)
12669 ListSizes.push_back(Record.readInt());
12670 C->setComponentListSizes(ListSizes);
12671
12672 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12673 Components.reserve(TotalComponents);
12674 for (unsigned i = 0; i < TotalComponents; ++i) {
12675 Expr *AssociatedExpr = Record.readSubExpr();
12676 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12677 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12678 AssociatedExpr, AssociatedDecl));
12679 }
12680 C->setComponents(Components, ListSizes);
12681}
12682
12683void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12684 C->setLParenLoc(Record.readSourceLocation());
12685 auto NumVars = C->varlist_size();
12686 auto UniqueDecls = C->getUniqueDeclarationsNum();
12687 auto TotalLists = C->getTotalComponentListNum();
12688 auto TotalComponents = C->getTotalComponentsNum();
12689
12690 SmallVector<Expr *, 16> Vars;
12691 Vars.reserve(NumVars);
12692 for (unsigned i = 0; i != NumVars; ++i)
12693 Vars.push_back(Record.readSubExpr());
12694 C->setVarRefs(Vars);
12695 Vars.clear();
12696
12697 SmallVector<ValueDecl *, 16> Decls;
12698 Decls.reserve(UniqueDecls);
12699 for (unsigned i = 0; i < UniqueDecls; ++i)
12700 Decls.push_back(Record.readDeclAs<ValueDecl>());
12701 C->setUniqueDecls(Decls);
12702
12703 SmallVector<unsigned, 16> ListsPerDecl;
12704 ListsPerDecl.reserve(UniqueDecls);
12705 for (unsigned i = 0; i < UniqueDecls; ++i)
12706 ListsPerDecl.push_back(Record.readInt());
12707 C->setDeclNumLists(ListsPerDecl);
12708
12709 SmallVector<unsigned, 32> ListSizes;
12710 ListSizes.reserve(TotalLists);
12711 for (unsigned i = 0; i < TotalLists; ++i)
12712 ListSizes.push_back(Record.readInt());
12713 C->setComponentListSizes(ListSizes);
12714
12715 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12716 Components.reserve(TotalComponents);
12717 for (unsigned i = 0; i < TotalComponents; ++i) {
12718 Expr *AssociatedExpr = Record.readSubExpr();
12719 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12720 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12721 AssociatedExpr, AssociatedDecl));
12722 }
12723 C->setComponents(Components, ListSizes);
12724}