blob: bb2076e25fd32997dfec9de4d3aa77219f0dca96 [file] [log] [blame]
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001//===- ASTReader.cpp - AST File Reader ------------------------------------===//
Guy Benyei11169dd2012-12-18 14:30:41 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the ASTReader class, which reads AST files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Serialization/ASTReader.h"
15#include "ASTCommon.h"
16#include "ASTReaderInternals.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ASTContext.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000019#include "clang/AST/ASTMutationListener.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Decl.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000022#include "clang/AST/DeclBase.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/AST/DeclCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000024#include "clang/AST/DeclFriend.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000025#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000027#include "clang/AST/DeclTemplate.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000028#include "clang/AST/DeclarationName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000029#include "clang/AST/Expr.h"
30#include "clang/AST/ExprCXX.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000031#include "clang/AST/ExternalASTSource.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000032#include "clang/AST/NestedNameSpecifier.h"
Richard Trieue7f7ed22017-02-22 01:11:25 +000033#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000034#include "clang/AST/RawCommentList.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000035#include "clang/AST/TemplateBase.h"
36#include "clang/AST/TemplateName.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/AST/Type.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000038#include "clang/AST/TypeLoc.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000039#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "clang/AST/UnresolvedSet.h"
41#include "clang/Basic/CommentOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000042#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000043#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/FileSystemOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000047#include "clang/Basic/IdentifierTable.h"
48#include "clang/Basic/LLVM.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000050#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000051#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include "clang/Basic/ObjCRuntime.h"
53#include "clang/Basic/OperatorKinds.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000054#include "clang/Basic/PragmaKinds.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000055#include "clang/Basic/Sanitizers.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000056#include "clang/Basic/SourceLocation.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include "clang/Basic/SourceManager.h"
58#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000059#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000060#include "clang/Basic/TargetInfo.h"
61#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Basic/Version.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000064#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000065#include "clang/Lex/HeaderSearch.h"
66#include "clang/Lex/HeaderSearchOptions.h"
67#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000069#include "clang/Lex/PreprocessingRecord.h"
70#include "clang/Lex/Preprocessor.h"
71#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000072#include "clang/Lex/Token.h"
73#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000074#include "clang/Sema/Scope.h"
75#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000076#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000077#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000078#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000079#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000080#include "clang/Serialization/GlobalModuleIndex.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000081#include "clang/Serialization/Module.h"
82#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000083#include "clang/Serialization/ModuleManager.h"
84#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000085#include "llvm/ADT/APFloat.h"
86#include "llvm/ADT/APInt.h"
87#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000088#include "llvm/ADT/ArrayRef.h"
89#include "llvm/ADT/DenseMap.h"
90#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000091#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000092#include "llvm/ADT/IntrusiveRefCntPtr.h"
93#include "llvm/ADT/None.h"
94#include "llvm/ADT/Optional.h"
95#include "llvm/ADT/STLExtras.h"
96#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());
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000399 llvm::sort(ExistingFeatures.begin(), ExistingFeatures.end());
400 llvm::sort(ReadFeatures.begin(), ReadFeatures.end());
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) &&
Richard Smitha534a312015-07-21 23:54:07 +0000911 II.getFETokenInfo<void>());
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;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002363 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002364 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002365
Chris Lattnere7b154b2013-01-19 21:39:22 +00002366 switch (Entry.Kind) {
2367 case llvm::BitstreamEntry::Error:
2368 Error("malformed block record in AST file");
2369 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002370 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002371 // Validate the module before returning. This call catches an AST with
2372 // no module name and no imports.
2373 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2374 return Result;
2375
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002376 // Validate input files.
2377 const HeaderSearchOptions &HSOpts =
2378 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002379
Richard Smitha1825302014-10-23 22:18:29 +00002380 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002381 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2382 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002383 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2384 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002386
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002387 // If we are reading a module, we will create a verification timestamp,
2388 // so we verify all input files. Otherwise, verify only user input
2389 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002390
2391 unsigned N = NumUserInputs;
2392 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002393 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002394 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002395 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002396 N = NumInputs;
2397
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002398 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002399 InputFile IF = getInputFile(F, I+1, Complain);
2400 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002401 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002402 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002404
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002405 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002406 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002407
Ben Langmuircb69b572014-03-07 06:40:32 +00002408 if (Listener && Listener->needsInputFileVisitation()) {
2409 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2410 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002411 for (unsigned I = 0; I < N; ++I) {
2412 bool IsSystem = I >= NumUserInputs;
2413 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002414 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002415 F.Kind == MK_ExplicitModule ||
2416 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002417 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002418 }
2419
Richard Smith8a308ec2015-11-05 00:54:55 +00002420 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002421 }
2422
Chris Lattnere7b154b2013-01-19 21:39:22 +00002423 case llvm::BitstreamEntry::SubBlock:
2424 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 case INPUT_FILES_BLOCK_ID:
2426 F.InputFilesCursor = Stream;
2427 if (Stream.SkipBlock() || // Skip with the main cursor
2428 // Read the abbreviations
2429 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2430 Error("malformed block record in AST file");
2431 return Failure;
2432 }
2433 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002434
2435 case OPTIONS_BLOCK_ID:
2436 // If we're reading the first module for this group, check its options
2437 // are compatible with ours. For modules it imports, no further checking
2438 // is required, because we checked them when we built it.
2439 if (Listener && !ImportedBy) {
2440 // Should we allow the configuration of the module file to differ from
2441 // the configuration of the current translation unit in a compatible
2442 // way?
2443 //
2444 // FIXME: Allow this for files explicitly specified with -include-pch.
2445 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002446 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002447
Richard Smith8a308ec2015-11-05 00:54:55 +00002448 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2449 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002450 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002451 if (Result == Failure) {
2452 Error("malformed block record in AST file");
2453 return Result;
2454 }
2455
Richard Smith8a308ec2015-11-05 00:54:55 +00002456 if (DisableValidation ||
2457 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2458 Result = Success;
2459
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002460 // If we can't load the module, exit early since we likely
2461 // will rebuild the module anyway. The stream may be in the
2462 // middle of a block.
2463 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002464 return Result;
2465 } else if (Stream.SkipBlock()) {
2466 Error("malformed block record in AST file");
2467 return Failure;
2468 }
2469 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002470
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002472 if (Stream.SkipBlock()) {
2473 Error("malformed block record in AST file");
2474 return Failure;
2475 }
2476 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002478
Chris Lattnere7b154b2013-01-19 21:39:22 +00002479 case llvm::BitstreamEntry::Record:
2480 // The interesting case.
2481 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 }
2483
2484 // Read and process a record.
2485 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002486 StringRef Blob;
2487 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 case METADATA: {
2489 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2490 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002491 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2492 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 return VersionMismatch;
2494 }
2495
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002496 bool hasErrors = Record[7];
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2498 Diag(diag::err_pch_with_compiler_errors);
2499 return HadErrors;
2500 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002501 if (hasErrors) {
2502 Diags.ErrorOccurred = true;
2503 Diags.UncompilableErrorOccurred = true;
2504 Diags.UnrecoverableErrorOccurred = true;
2505 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002506
2507 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002508 // Relative paths in a relocatable PCH are relative to our sysroot.
2509 if (F.RelocatablePCH)
2510 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002511
Richard Smithe75ee0f2015-08-17 07:13:32 +00002512 F.HasTimestamps = Record[5];
2513
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00002514 F.PCHHasObjectFile = Record[6];
2515
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002517 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2519 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002520 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 return VersionMismatch;
2522 }
2523 break;
2524 }
2525
2526 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002527 // Validate the AST before processing any imports (otherwise, untangling
2528 // them can be error-prone and expensive). A module will have a name and
2529 // will already have been validated, but this catches the PCH case.
2530 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2531 return Result;
2532
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002533 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002534 unsigned Idx = 0, N = Record.size();
2535 while (Idx < N) {
2536 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002537 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 // The import location will be the local one for now; we will adjust
2539 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002540 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002542 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002543 off_t StoredSize = (off_t)Record[Idx++];
2544 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002545 ASTFileSignature StoredSignature = {
2546 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2547 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2548 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002549
2550 std::string ImportedName = ReadString(Record, Idx);
2551 std::string ImportedFile;
2552
2553 // For prebuilt and explicit modules first consult the file map for
2554 // an override. Note that here we don't search prebuilt module
2555 // directories, only the explicit name to file mappings. Also, we will
2556 // still verify the size/signature making sure it is essentially the
2557 // same file but perhaps in a different location.
2558 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2559 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2560 ImportedName, /*FileMapOnly*/ true);
2561
2562 if (ImportedFile.empty())
2563 ImportedFile = ReadPath(F, Record, Idx);
2564 else
2565 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002566
Richard Smith0f99d6a2015-08-09 08:48:41 +00002567 // If our client can't cope with us being out of date, we can't cope with
2568 // our dependency being missing.
2569 unsigned Capabilities = ClientLoadCapabilities;
2570 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2571 Capabilities &= ~ARR_Missing;
2572
Guy Benyei11169dd2012-12-18 14:30:41 +00002573 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002574 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2575 Loaded, StoredSize, StoredModTime,
2576 StoredSignature, Capabilities);
2577
2578 // If we diagnosed a problem, produce a backtrace.
2579 if (isDiagnosedResult(Result, Capabilities))
2580 Diag(diag::note_module_file_imported_by)
2581 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2582
2583 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 case Failure: return Failure;
2585 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002586 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 case OutOfDate: return OutOfDate;
2588 case VersionMismatch: return VersionMismatch;
2589 case ConfigurationMismatch: return ConfigurationMismatch;
2590 case HadErrors: return HadErrors;
2591 case Success: break;
2592 }
2593 }
2594 break;
2595 }
2596
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 case ORIGINAL_FILE:
2598 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002599 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002601 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 break;
2603
2604 case ORIGINAL_FILE_ID:
2605 F.OriginalSourceFileID = FileID::get(Record[0]);
2606 break;
2607
2608 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002609 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 break;
2611
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002612 case MODULE_NAME:
2613 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002614 if (Listener)
2615 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002616
2617 // Validate the AST as soon as we have a name so we can exit early on
2618 // failure.
2619 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2620 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002621
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002622 break;
2623
Richard Smith223d3f22014-12-06 03:21:08 +00002624 case MODULE_DIRECTORY: {
2625 assert(!F.ModuleName.empty() &&
2626 "MODULE_DIRECTORY found before MODULE_NAME");
2627 // If we've already loaded a module map file covering this module, we may
2628 // have a better path for it (relative to the current build).
Bruno Cardoso Lopes52431f32018-07-18 23:21:19 +00002629 Module *M = PP.getHeaderSearchInfo().lookupModule(
2630 F.ModuleName, /*AllowSearch*/ true,
2631 /*AllowExtraModuleMapSearch*/ true);
Richard Smith223d3f22014-12-06 03:21:08 +00002632 if (M && M->Directory) {
2633 // If we're implicitly loading a module, the base directory can't
2634 // change between the build and use.
Yuka Takahashid8baec22018-08-01 09:50:02 +00002635 // Don't emit module relocation error if we have -fno-validate-pch
2636 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
2637 F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002638 const DirectoryEntry *BuildDir =
2639 PP.getFileManager().getDirectory(Blob);
2640 if (!BuildDir || BuildDir != M->Directory) {
2641 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2642 Diag(diag::err_imported_module_relocated)
2643 << F.ModuleName << Blob << M->Directory->getName();
2644 return OutOfDate;
2645 }
2646 }
2647 F.BaseDirectory = M->Directory->getName();
2648 } else {
2649 F.BaseDirectory = Blob;
2650 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002651 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002652 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002653
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002654 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002655 if (ASTReadResult Result =
2656 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2657 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002658 break;
2659
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002660 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002661 NumInputs = Record[0];
2662 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002663 F.InputFileOffsets =
2664 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002665 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002666 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 break;
2668 }
2669 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002670}
2671
Ben Langmuir2c9af442014-04-10 17:57:43 +00002672ASTReader::ASTReadResult
2673ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002674 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002675
2676 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2677 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002678 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 }
2680
2681 // Read all of the records and blocks for the AST file.
2682 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002683 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002684 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002685
Chris Lattnere7b154b2013-01-19 21:39:22 +00002686 switch (Entry.Kind) {
2687 case llvm::BitstreamEntry::Error:
2688 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002689 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002690 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002691 // Outside of C++, we do not store a lookup map for the translation unit.
2692 // Instead, mark it as needing a lookup map to be built if this module
2693 // contains any declarations lexically within it (which it always does!).
2694 // This usually has no cost, since we very rarely need the lookup map for
2695 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002696 if (ASTContext *Ctx = ContextObj) {
2697 DeclContext *DC = Ctx->getTranslationUnitDecl();
2698 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2699 DC->setMustBuildLookupTable();
2700 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002701
Ben Langmuir2c9af442014-04-10 17:57:43 +00002702 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002703 case llvm::BitstreamEntry::SubBlock:
2704 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 case DECLTYPES_BLOCK_ID:
2706 // We lazily load the decls block, but we want to set up the
2707 // DeclsCursor cursor to point into it. Clone our current bitcode
2708 // cursor to it, enter the block and read the abbrevs in that block.
2709 // With the main cursor, we just skip over it.
2710 F.DeclsCursor = Stream;
2711 if (Stream.SkipBlock() || // Skip with the main cursor.
2712 // Read the abbrevs.
2713 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2714 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002715 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 }
2717 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002718
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 case PREPROCESSOR_BLOCK_ID:
2720 F.MacroCursor = Stream;
2721 if (!PP.getExternalSource())
2722 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002723
Guy Benyei11169dd2012-12-18 14:30:41 +00002724 if (Stream.SkipBlock() ||
2725 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2726 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002727 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 }
2729 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2730 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 case PREPROCESSOR_DETAIL_BLOCK_ID:
2733 F.PreprocessorDetailCursor = Stream;
2734 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002735 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002737 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002738 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002739 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002740 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002741 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002742
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 if (!PP.getPreprocessingRecord())
2744 PP.createPreprocessingRecord();
2745 if (!PP.getPreprocessingRecord()->getExternalSource())
2746 PP.getPreprocessingRecord()->SetExternalSource(*this);
2747 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002748
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 case SOURCE_MANAGER_BLOCK_ID:
2750 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002751 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002753
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002755 if (ASTReadResult Result =
2756 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002757 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002759
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002761 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 if (Stream.SkipBlock() ||
2763 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2764 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002765 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 }
2767 CommentsCursors.push_back(std::make_pair(C, &F));
2768 break;
2769 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002770
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002772 if (Stream.SkipBlock()) {
2773 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002774 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002775 }
2776 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 }
2778 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002779
Chris Lattnere7b154b2013-01-19 21:39:22 +00002780 case llvm::BitstreamEntry::Record:
2781 // The interesting case.
2782 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 }
2784
2785 // Read and process a record.
2786 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002787 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002788 auto RecordType =
2789 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2790
2791 // If we're not loading an AST context, we don't care about most records.
2792 if (!ContextObj) {
2793 switch (RecordType) {
2794 case IDENTIFIER_TABLE:
2795 case IDENTIFIER_OFFSET:
2796 case INTERESTING_IDENTIFIERS:
2797 case STATISTICS:
2798 case PP_CONDITIONAL_STACK:
2799 case PP_COUNTER_VALUE:
2800 case SOURCE_LOCATION_OFFSETS:
2801 case MODULE_OFFSET_MAP:
2802 case SOURCE_MANAGER_LINE_TABLE:
2803 case SOURCE_LOCATION_PRELOADS:
2804 case PPD_ENTITIES_OFFSETS:
2805 case HEADER_SEARCH_TABLE:
2806 case IMPORTED_MODULES:
2807 case MACRO_OFFSET:
2808 break;
2809 default:
2810 continue;
2811 }
2812 }
2813
2814 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 default: // Default behavior: ignore.
2816 break;
2817
2818 case TYPE_OFFSET: {
2819 if (F.LocalNumTypes != 0) {
2820 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002821 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002822 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002823 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 F.LocalNumTypes = Record[0];
2825 unsigned LocalBaseTypeIndex = Record[1];
2826 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002827
Guy Benyei11169dd2012-12-18 14:30:41 +00002828 if (F.LocalNumTypes > 0) {
2829 // Introduce the global -> local mapping for types within this module.
2830 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002831
Guy Benyei11169dd2012-12-18 14:30:41 +00002832 // Introduce the local -> global mapping for types within this module.
2833 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002834 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002836
2837 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002838 }
2839 break;
2840 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002841
Guy Benyei11169dd2012-12-18 14:30:41 +00002842 case DECL_OFFSET: {
2843 if (F.LocalNumDecls != 0) {
2844 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002845 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002847 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 F.LocalNumDecls = Record[0];
2849 unsigned LocalBaseDeclID = Record[1];
2850 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002851
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002853 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 // module.
2855 GlobalDeclMap.insert(
2856 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002857
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 // Introduce the local -> global mapping for declarations within this
2859 // module.
2860 F.DeclRemap.insertOrReplace(
2861 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002862
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 // Introduce the global -> local mapping for declarations within this
2864 // module.
2865 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002866
Ben Langmuir52ca6782014-10-20 16:27:32 +00002867 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2868 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 break;
2870 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002871
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002873 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002874 LexicalContents Contents(
2875 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2876 Blob.data()),
2877 static_cast<unsigned int>(Blob.size() / 4));
2878 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002879 TU->setHasExternalLexicalStorage(true);
2880 break;
2881 }
2882
2883 case UPDATE_VISIBLE: {
2884 unsigned Idx = 0;
2885 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002886 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002887 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002888 // If we've already loaded the decl, perform the updates when we finish
2889 // loading this block.
2890 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002891 PendingUpdateRecords.push_back(
2892 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002893 break;
2894 }
2895
2896 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002897 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002899 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2900 (const unsigned char *)F.IdentifierTableData + Record[0],
2901 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2902 (const unsigned char *)F.IdentifierTableData,
2903 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002904
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2906 }
2907 break;
2908
2909 case IDENTIFIER_OFFSET: {
2910 if (F.LocalNumIdentifiers != 0) {
2911 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002912 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002914 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002915 F.LocalNumIdentifiers = Record[0];
2916 unsigned LocalBaseIdentifierID = Record[1];
2917 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002918
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 if (F.LocalNumIdentifiers > 0) {
2920 // Introduce the global -> local mapping for identifiers within this
2921 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002922 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002924
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 // Introduce the local -> global mapping for identifiers within this
2926 // module.
2927 F.IdentifierRemap.insertOrReplace(
2928 std::make_pair(LocalBaseIdentifierID,
2929 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002930
Ben Langmuir52ca6782014-10-20 16:27:32 +00002931 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2932 + F.LocalNumIdentifiers);
2933 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 break;
2935 }
2936
Richard Smith33e0f7e2015-07-22 02:08:40 +00002937 case INTERESTING_IDENTIFIERS:
2938 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2939 break;
2940
Ben Langmuir332aafe2014-01-31 01:06:56 +00002941 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002942 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2943 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002944 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002945 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 break;
2947
David Blaikie9ffe5a32017-01-30 05:00:26 +00002948 case MODULAR_CODEGEN_DECLS:
2949 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2950 // them (ie: if we're not codegenerating this module).
2951 if (F.Kind == MK_MainFile)
2952 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2953 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2954 break;
2955
Guy Benyei11169dd2012-12-18 14:30:41 +00002956 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002957 if (SpecialTypes.empty()) {
2958 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2959 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2960 break;
2961 }
2962
2963 if (SpecialTypes.size() != Record.size()) {
2964 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002965 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002966 }
2967
2968 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2969 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2970 if (!SpecialTypes[I])
2971 SpecialTypes[I] = ID;
2972 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2973 // merge step?
2974 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 break;
2976
2977 case STATISTICS:
2978 TotalNumStatements += Record[0];
2979 TotalNumMacros += Record[1];
2980 TotalLexicalDeclContexts += Record[2];
2981 TotalVisibleDeclContexts += Record[3];
2982 break;
2983
2984 case UNUSED_FILESCOPED_DECLS:
2985 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2986 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2987 break;
2988
2989 case DELEGATING_CTORS:
2990 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2991 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2992 break;
2993
2994 case WEAK_UNDECLARED_IDENTIFIERS:
2995 if (Record.size() % 4 != 0) {
2996 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002997 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002998 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002999
3000 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 // files. This isn't the way to do it :)
3002 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003003
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 // Translate the weak, undeclared identifiers into global IDs.
3005 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
3006 WeakUndeclaredIdentifiers.push_back(
3007 getGlobalIdentifierID(F, Record[I++]));
3008 WeakUndeclaredIdentifiers.push_back(
3009 getGlobalIdentifierID(F, Record[I++]));
3010 WeakUndeclaredIdentifiers.push_back(
3011 ReadSourceLocation(F, Record, I).getRawEncoding());
3012 WeakUndeclaredIdentifiers.push_back(Record[I++]);
3013 }
3014 break;
3015
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003017 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 F.LocalNumSelectors = Record[0];
3019 unsigned LocalBaseSelectorID = Record[1];
3020 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003021
Guy Benyei11169dd2012-12-18 14:30:41 +00003022 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003023 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 // module.
3025 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003026
3027 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003028 // module.
3029 F.SelectorRemap.insertOrReplace(
3030 std::make_pair(LocalBaseSelectorID,
3031 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003032
3033 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003034 }
3035 break;
3036 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003037
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003039 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003040 if (Record[0])
3041 F.SelectorLookupTable
3042 = ASTSelectorLookupTable::Create(
3043 F.SelectorLookupTableData + Record[0],
3044 F.SelectorLookupTableData,
3045 ASTSelectorLookupTrait(*this, F));
3046 TotalNumMethodPoolEntries += Record[1];
3047 break;
3048
3049 case REFERENCED_SELECTOR_POOL:
3050 if (!Record.empty()) {
3051 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003052 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 Record[Idx++]));
3054 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3055 getRawEncoding());
3056 }
3057 }
3058 break;
3059
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003060 case PP_CONDITIONAL_STACK:
3061 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003062 unsigned Idx = 0, End = Record.size() - 1;
3063 bool ReachedEOFWhileSkipping = Record[Idx++];
3064 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3065 if (ReachedEOFWhileSkipping) {
3066 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3067 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3068 bool FoundNonSkipPortion = Record[Idx++];
3069 bool FoundElse = Record[Idx++];
3070 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3071 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3072 FoundElse, ElseLoc);
3073 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003074 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003075 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003076 auto Loc = ReadSourceLocation(F, Record, Idx);
3077 bool WasSkipping = Record[Idx++];
3078 bool FoundNonSkip = Record[Idx++];
3079 bool FoundElse = Record[Idx++];
3080 ConditionalStack.push_back(
3081 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3082 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003083 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003084 }
3085 break;
3086
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 case PP_COUNTER_VALUE:
3088 if (!Record.empty() && Listener)
3089 Listener->ReadCounter(F, Record[0]);
3090 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003091
Guy Benyei11169dd2012-12-18 14:30:41 +00003092 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003093 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 F.NumFileSortedDecls = Record[0];
3095 break;
3096
3097 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003098 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003099 F.LocalNumSLocEntries = Record[0];
3100 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003101 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003102 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003104 if (!F.SLocEntryBaseID) {
3105 Error("ran out of source locations");
3106 break;
3107 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 // Make our entry in the range map. BaseID is negative and growing, so
3109 // we invert it. Because we invert it, though, we need the other end of
3110 // the range.
3111 unsigned RangeStart =
3112 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3113 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3114 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3115
3116 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3117 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3118 GlobalSLocOffsetMap.insert(
3119 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3120 - SLocSpaceSize,&F));
3121
3122 // Initialize the remapping table.
3123 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003124 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003126 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003128
Guy Benyei11169dd2012-12-18 14:30:41 +00003129 TotalNumSLocEntries += F.LocalNumSLocEntries;
3130 break;
3131 }
3132
Richard Smith37a93df2017-02-18 00:32:02 +00003133 case MODULE_OFFSET_MAP:
3134 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003136
3137 case SOURCE_MANAGER_LINE_TABLE:
3138 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003139 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 break;
3141
3142 case SOURCE_LOCATION_PRELOADS: {
3143 // Need to transform from the local view (1-based IDs) to the global view,
3144 // which is based off F.SLocEntryBaseID.
3145 if (!F.PreloadSLocEntries.empty()) {
3146 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003147 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003149
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 F.PreloadSLocEntries.swap(Record);
3151 break;
3152 }
3153
3154 case EXT_VECTOR_DECLS:
3155 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3156 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3157 break;
3158
3159 case VTABLE_USES:
3160 if (Record.size() % 3 != 0) {
3161 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003162 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003164
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 // Later tables overwrite earlier ones.
3166 // FIXME: Modules will have some trouble with this. This is clearly not
3167 // the right way to do this.
3168 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003169
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3171 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3172 VTableUses.push_back(
3173 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3174 VTableUses.push_back(Record[Idx++]);
3175 }
3176 break;
3177
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 case PENDING_IMPLICIT_INSTANTIATIONS:
3179 if (PendingInstantiations.size() % 2 != 0) {
3180 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003181 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 }
3183
3184 if (Record.size() % 2 != 0) {
3185 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003186 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 }
3188
3189 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3190 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3191 PendingInstantiations.push_back(
3192 ReadSourceLocation(F, Record, I).getRawEncoding());
3193 }
3194 break;
3195
3196 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003197 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003198 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003199 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3202 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3203 break;
3204
3205 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003206 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3207 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3208 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003209
3210 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003211
Guy Benyei11169dd2012-12-18 14:30:41 +00003212 unsigned StartingID;
3213 if (!PP.getPreprocessingRecord())
3214 PP.createPreprocessingRecord();
3215 if (!PP.getPreprocessingRecord()->getExternalSource())
3216 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003217 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003219 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003220 F.BasePreprocessedEntityID = StartingID;
3221
3222 if (F.NumPreprocessedEntities > 0) {
3223 // Introduce the global -> local mapping for preprocessed entities in
3224 // this module.
3225 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003226
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 // Introduce the local -> global mapping for preprocessed entities in
3228 // this module.
3229 F.PreprocessedEntityRemap.insertOrReplace(
3230 std::make_pair(LocalBasePreprocessedEntityID,
3231 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3232 }
3233
3234 break;
3235 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003236
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003237 case PPD_SKIPPED_RANGES: {
3238 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3239 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3240 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3241
3242 if (!PP.getPreprocessingRecord())
3243 PP.createPreprocessingRecord();
3244 if (!PP.getPreprocessingRecord()->getExternalSource())
3245 PP.getPreprocessingRecord()->SetExternalSource(*this);
3246 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3247 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003248
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003249 if (F.NumPreprocessedSkippedRanges > 0)
3250 GlobalSkippedRangeMap.insert(
3251 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3252 break;
3253 }
3254
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003255 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 if (Record.size() % 2 != 0) {
3257 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003258 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003260 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3261 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3262 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3263
3264 // If we've already loaded the decl, perform the updates when we finish
3265 // loading this block.
3266 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003267 PendingUpdateRecords.push_back(
3268 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003269 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003271
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003272 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003273 if (F.LocalNumObjCCategoriesInMap != 0) {
3274 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003275 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003276 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003277
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003279 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003281
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 case OBJC_CATEGORIES:
3283 F.ObjCCategories.swap(Record);
3284 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003285
Guy Benyei11169dd2012-12-18 14:30:41 +00003286 case CUDA_SPECIAL_DECL_REFS:
3287 // Later tables overwrite earlier ones.
3288 // FIXME: Modules will have trouble with this.
3289 CUDASpecialDeclRefs.clear();
3290 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3291 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3292 break;
3293
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003294 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003295 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003296 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 if (Record[0]) {
3298 F.HeaderFileInfoTable
3299 = HeaderFileInfoLookupTable::Create(
3300 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3301 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003302 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003303 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003304 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003305
Guy Benyei11169dd2012-12-18 14:30:41 +00003306 PP.getHeaderSearchInfo().SetExternalSource(this);
3307 if (!PP.getHeaderSearchInfo().getExternalLookup())
3308 PP.getHeaderSearchInfo().SetExternalLookup(this);
3309 }
3310 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003311
Guy Benyei11169dd2012-12-18 14:30:41 +00003312 case FP_PRAGMA_OPTIONS:
3313 // Later tables overwrite earlier ones.
3314 FPPragmaOptions.swap(Record);
3315 break;
3316
3317 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003318 for (unsigned I = 0, E = Record.size(); I != E; ) {
3319 auto Name = ReadString(Record, I);
3320 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003321 Opt.Supported = Record[I++] != 0;
3322 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003323 Opt.Avail = Record[I++];
3324 Opt.Core = Record[I++];
3325 }
3326 break;
3327
3328 case OPENCL_EXTENSION_TYPES:
3329 for (unsigned I = 0, E = Record.size(); I != E;) {
3330 auto TypeID = static_cast<::TypeID>(Record[I++]);
3331 auto *Type = GetType(TypeID).getTypePtr();
3332 auto NumExt = static_cast<unsigned>(Record[I++]);
3333 for (unsigned II = 0; II != NumExt; ++II) {
3334 auto Ext = ReadString(Record, I);
3335 OpenCLTypeExtMap[Type].insert(Ext);
3336 }
3337 }
3338 break;
3339
3340 case OPENCL_EXTENSION_DECLS:
3341 for (unsigned I = 0, E = Record.size(); I != E;) {
3342 auto DeclID = static_cast<::DeclID>(Record[I++]);
3343 auto *Decl = GetDecl(DeclID);
3344 auto NumExt = static_cast<unsigned>(Record[I++]);
3345 for (unsigned II = 0; II != NumExt; ++II) {
3346 auto Ext = ReadString(Record, I);
3347 OpenCLDeclExtMap[Decl].insert(Ext);
3348 }
3349 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003350 break;
3351
3352 case TENTATIVE_DEFINITIONS:
3353 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3354 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3355 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003356
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 case KNOWN_NAMESPACES:
3358 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3359 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3360 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003361
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003362 case UNDEFINED_BUT_USED:
3363 if (UndefinedButUsed.size() % 2 != 0) {
3364 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003365 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003366 }
3367
3368 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003369 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003370 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003371 }
3372 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003373 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3374 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003375 ReadSourceLocation(F, Record, I).getRawEncoding());
3376 }
3377 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003378
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003379 case DELETE_EXPRS_TO_ANALYZE:
3380 for (unsigned I = 0, N = Record.size(); I != N;) {
3381 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3382 const uint64_t Count = Record[I++];
3383 DelayedDeleteExprs.push_back(Count);
3384 for (uint64_t C = 0; C < Count; ++C) {
3385 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3386 bool IsArrayForm = Record[I++] == 1;
3387 DelayedDeleteExprs.push_back(IsArrayForm);
3388 }
3389 }
3390 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003391
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003392 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003393 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003394 // If we aren't loading a module (which has its own exports), make
3395 // all of the imported modules visible.
3396 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003397 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3398 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3399 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003400 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003401 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003402 if (DeserializationListener)
3403 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3404 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003405 }
3406 }
3407 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003408
Guy Benyei11169dd2012-12-18 14:30:41 +00003409 case MACRO_OFFSET: {
3410 if (F.LocalNumMacros != 0) {
3411 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003412 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003414 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003415 F.LocalNumMacros = Record[0];
3416 unsigned LocalBaseMacroID = Record[1];
3417 F.BaseMacroID = getTotalNumMacros();
3418
3419 if (F.LocalNumMacros > 0) {
3420 // Introduce the global -> local mapping for macros within this module.
3421 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3422
3423 // Introduce the local -> global mapping for macros within this module.
3424 F.MacroRemap.insertOrReplace(
3425 std::make_pair(LocalBaseMacroID,
3426 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003427
3428 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003429 }
3430 break;
3431 }
3432
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003433 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003434 LateParsedTemplates.append(Record.begin(), Record.end());
3435 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003436
3437 case OPTIMIZE_PRAGMA_OPTIONS:
3438 if (Record.size() != 1) {
3439 Error("invalid pragma optimize record");
3440 return Failure;
3441 }
3442 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3443 break;
Nico Weber72889432014-09-06 01:25:55 +00003444
Nico Weber779355f2016-03-02 23:22:00 +00003445 case MSSTRUCT_PRAGMA_OPTIONS:
3446 if (Record.size() != 1) {
3447 Error("invalid pragma ms_struct record");
3448 return Failure;
3449 }
3450 PragmaMSStructState = Record[0];
3451 break;
3452
Nico Weber42932312016-03-03 00:17:35 +00003453 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3454 if (Record.size() != 2) {
3455 Error("invalid pragma ms_struct record");
3456 return Failure;
3457 }
3458 PragmaMSPointersToMembersState = Record[0];
3459 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3460 break;
3461
Nico Weber72889432014-09-06 01:25:55 +00003462 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3463 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3464 UnusedLocalTypedefNameCandidates.push_back(
3465 getGlobalDeclID(F, Record[I]));
3466 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003467
3468 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3469 if (Record.size() != 1) {
3470 Error("invalid cuda pragma options record");
3471 return Failure;
3472 }
3473 ForceCUDAHostDeviceDepth = Record[0];
3474 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003475
3476 case PACK_PRAGMA_OPTIONS: {
3477 if (Record.size() < 3) {
3478 Error("invalid pragma pack record");
3479 return Failure;
3480 }
3481 PragmaPackCurrentValue = Record[0];
3482 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3483 unsigned NumStackEntries = Record[2];
3484 unsigned Idx = 3;
3485 // Reset the stack when importing a new module.
3486 PragmaPackStack.clear();
3487 for (unsigned I = 0; I < NumStackEntries; ++I) {
3488 PragmaPackStackEntry Entry;
3489 Entry.Value = Record[Idx++];
3490 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003491 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003492 PragmaPackStrings.push_back(ReadString(Record, Idx));
3493 Entry.SlotLabel = PragmaPackStrings.back();
3494 PragmaPackStack.push_back(Entry);
3495 }
3496 break;
3497 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003498 }
3499 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003500}
3501
Richard Smith37a93df2017-02-18 00:32:02 +00003502void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3503 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3504
3505 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003506 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003507 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3508 F.ModuleOffsetMap = StringRef();
3509
3510 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3511 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3512 F.SLocRemap.insert(std::make_pair(0U, 0));
3513 F.SLocRemap.insert(std::make_pair(2U, 1));
3514 }
3515
3516 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003517 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003518 RemapBuilder SLocRemap(F.SLocRemap);
3519 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3520 RemapBuilder MacroRemap(F.MacroRemap);
3521 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3522 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3523 RemapBuilder SelectorRemap(F.SelectorRemap);
3524 RemapBuilder DeclRemap(F.DeclRemap);
3525 RemapBuilder TypeRemap(F.TypeRemap);
3526
3527 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003528 // FIXME: Looking up dependency modules by filename is horrible. Let's
3529 // start fixing this with prebuilt and explicit modules and see how it
3530 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003531 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003532 ModuleKind Kind = static_cast<ModuleKind>(
3533 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003534 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3535 StringRef Name = StringRef((const char*)Data, Len);
3536 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003537 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3538 ? ModuleMgr.lookupByModuleName(Name)
3539 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003540 if (!OM) {
3541 std::string Msg =
3542 "SourceLocation remap refers to unknown module, cannot find ";
3543 Msg.append(Name);
3544 Error(Msg);
3545 return;
3546 }
3547
3548 uint32_t SLocOffset =
3549 endian::readNext<uint32_t, little, unaligned>(Data);
3550 uint32_t IdentifierIDOffset =
3551 endian::readNext<uint32_t, little, unaligned>(Data);
3552 uint32_t MacroIDOffset =
3553 endian::readNext<uint32_t, little, unaligned>(Data);
3554 uint32_t PreprocessedEntityIDOffset =
3555 endian::readNext<uint32_t, little, unaligned>(Data);
3556 uint32_t SubmoduleIDOffset =
3557 endian::readNext<uint32_t, little, unaligned>(Data);
3558 uint32_t SelectorIDOffset =
3559 endian::readNext<uint32_t, little, unaligned>(Data);
3560 uint32_t DeclIDOffset =
3561 endian::readNext<uint32_t, little, unaligned>(Data);
3562 uint32_t TypeIndexOffset =
3563 endian::readNext<uint32_t, little, unaligned>(Data);
3564
3565 uint32_t None = std::numeric_limits<uint32_t>::max();
3566
3567 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3568 RemapBuilder &Remap) {
3569 if (Offset != None)
3570 Remap.insert(std::make_pair(Offset,
3571 static_cast<int>(BaseOffset - Offset)));
3572 };
3573 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3574 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3575 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3576 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3577 PreprocessedEntityRemap);
3578 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3579 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3580 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3581 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3582
3583 // Global -> local mappings.
3584 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3585 }
3586}
3587
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003588ASTReader::ASTReadResult
3589ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3590 const ModuleFile *ImportedBy,
3591 unsigned ClientLoadCapabilities) {
3592 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003593 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003594
3595 // Try to resolve ModuleName in the current header search context and
3596 // verify that it is found in the same module map file as we saved. If the
3597 // top-level AST file is a main file, skip this check because there is no
3598 // usable header search context.
3599 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003600 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003601 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003602 // An implicitly-loaded module file should have its module listed in some
3603 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003604 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003605 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3606 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
Yuka Takahashid8baec22018-08-01 09:50:02 +00003607 // Don't emit module relocation error if we have -fno-validate-pch
3608 if (!PP.getPreprocessorOpts().DisablePCHValidation && !ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003609 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003610 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003611 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003612 // This module was defined by an imported (explicit) module.
3613 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3614 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003615 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003616 // This module was built with a different module map.
3617 Diag(diag::err_imported_module_not_found)
3618 << F.ModuleName << F.FileName << ImportedBy->FileName
3619 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003620 // In case it was imported by a PCH, there's a chance the user is
3621 // just missing to include the search path to the directory containing
3622 // the modulemap.
3623 if (ImportedBy->Kind == MK_PCH)
3624 Diag(diag::note_imported_by_pch_module_not_found)
3625 << llvm::sys::path::parent_path(F.ModuleMapPath);
3626 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003627 }
3628 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003629 }
3630
Richard Smithe842a472014-10-22 02:05:46 +00003631 assert(M->Name == F.ModuleName && "found module with different name");
3632
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003633 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003634 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003635 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3636 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003637 assert(ImportedBy && "top-level import should be verified");
3638 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3639 Diag(diag::err_imported_module_modmap_changed)
3640 << F.ModuleName << ImportedBy->FileName
3641 << ModMap->getName() << F.ModuleMapPath;
3642 return OutOfDate;
3643 }
3644
3645 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3646 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3647 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003648 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003649 const FileEntry *F =
3650 FileMgr.getFile(Filename, false, false);
3651 if (F == nullptr) {
3652 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3653 Error("could not find file '" + Filename +"' referenced by AST file");
3654 return OutOfDate;
3655 }
3656 AdditionalStoredMaps.insert(F);
3657 }
3658
3659 // Check any additional module map files (e.g. module.private.modulemap)
3660 // that are not in the pcm.
3661 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003662 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003663 // Remove files that match
3664 // Note: SmallPtrSet::erase is really remove
3665 if (!AdditionalStoredMaps.erase(ModMap)) {
3666 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3667 Diag(diag::err_module_different_modmap)
3668 << F.ModuleName << /*new*/0 << ModMap->getName();
3669 return OutOfDate;
3670 }
3671 }
3672 }
3673
3674 // Check any additional module map files that are in the pcm, but not
3675 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003676 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003677 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3678 Diag(diag::err_module_different_modmap)
3679 << F.ModuleName << /*not new*/1 << ModMap->getName();
3680 return OutOfDate;
3681 }
3682 }
3683
3684 if (Listener)
3685 Listener->ReadModuleMapFile(F.ModuleMapPath);
3686 return Success;
3687}
3688
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003689/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003690static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3691 // Find the entry for this selector in the method pool.
3692 Sema::GlobalMethodPool::iterator Known
3693 = S.MethodPool.find(Method->getSelector());
3694 if (Known == S.MethodPool.end())
3695 return;
3696
3697 // Retrieve the appropriate method list.
3698 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3699 : Known->second.second;
3700 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003701 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003702 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003703 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003704 Found = true;
3705 } else {
3706 // Keep searching.
3707 continue;
3708 }
3709 }
3710
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003711 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003712 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003713 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003714 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003715 }
3716}
3717
Richard Smithde711422015-04-23 21:20:19 +00003718void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003719 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003720 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003721 bool wasHidden = D->isHidden();
3722 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003723
Vedant Kumar48b4f762018-04-14 01:40:48 +00003724 if (wasHidden && SemaObj) {
3725 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003726 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003727 }
3728 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 }
3730}
3731
Richard Smith49f906a2014-03-01 00:08:04 +00003732void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003733 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003734 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003736 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003737 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003738 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003739 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003740
3741 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003742 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 // there is nothing more to do.
3744 continue;
3745 }
Richard Smith49f906a2014-03-01 00:08:04 +00003746
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 if (!Mod->isAvailable()) {
3748 // Modules that aren't available cannot be made visible.
3749 continue;
3750 }
3751
3752 // Update the module's name visibility.
3753 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003754
Guy Benyei11169dd2012-12-18 14:30:41 +00003755 // If we've already deserialized any names from this module,
3756 // mark them as visible.
3757 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3758 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003759 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003761 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003762 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3763 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003764 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003765
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003767 SmallVector<Module *, 16> Exports;
3768 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003769 for (SmallVectorImpl<Module *>::iterator
3770 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3771 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003772 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003773 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 }
3776}
3777
Richard Smith6561f922016-09-12 21:06:40 +00003778/// We've merged the definition \p MergedDef into the existing definition
3779/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3780/// visible.
3781void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3782 NamedDecl *MergedDef) {
Richard Smith6561f922016-09-12 21:06:40 +00003783 if (Def->isHidden()) {
3784 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003785 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003786 Def->setVisibleDespiteOwningModule();
Richard Smith13897eb2018-09-12 23:37:00 +00003787 else {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003788 getContext().mergeDefinitionIntoModule(
3789 Def, MergedDef->getImportedOwningModule(),
3790 /*NotifyListeners*/ false);
3791 PendingMergedDefinitionsToDeduplicate.insert(Def);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003792 }
Richard Smith6561f922016-09-12 21:06:40 +00003793 }
3794}
3795
Douglas Gregore060e572013-01-25 01:03:03 +00003796bool ASTReader::loadGlobalIndex() {
3797 if (GlobalIndex)
3798 return false;
3799
3800 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003801 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003802 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003803
Douglas Gregore060e572013-01-25 01:03:03 +00003804 // Try to load the global index.
3805 TriedLoadingGlobalIndex = true;
3806 StringRef ModuleCachePath
3807 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3808 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003809 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003810 if (!Result.first)
3811 return true;
3812
3813 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003814 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003815 return false;
3816}
3817
3818bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003819 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003820 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3821}
3822
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003823static void updateModuleTimestamp(ModuleFile &MF) {
3824 // Overwrite the timestamp file contents so that file's mtime changes.
3825 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003826 std::error_code EC;
3827 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3828 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003829 return;
3830 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003831 OS.close();
3832 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003833}
3834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003835/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003836/// cursor into the start of the given block ID, returning false on success and
3837/// true on failure.
3838static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003839 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003840 llvm::BitstreamEntry Entry = Cursor.advance();
3841 switch (Entry.Kind) {
3842 case llvm::BitstreamEntry::Error:
3843 case llvm::BitstreamEntry::EndBlock:
3844 return true;
3845
3846 case llvm::BitstreamEntry::Record:
3847 // Ignore top-level records.
3848 Cursor.skipRecord(Entry.ID);
3849 break;
3850
3851 case llvm::BitstreamEntry::SubBlock:
3852 if (Entry.ID == BlockID) {
3853 if (Cursor.EnterSubBlock(BlockID))
3854 return true;
3855 // Found it!
3856 return false;
3857 }
3858
3859 if (Cursor.SkipBlock())
3860 return true;
3861 }
3862 }
3863}
3864
Benjamin Kramer0772c422016-02-13 13:42:54 +00003865ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003866 ModuleKind Type,
3867 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003868 unsigned ClientLoadCapabilities,
3869 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003870 llvm::SaveAndRestore<SourceLocation>
3871 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3872
Richard Smithd1c46742014-04-30 02:24:17 +00003873 // Defer any pending actions until we get to the end of reading the AST file.
3874 Deserializing AnASTFile(this);
3875
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003877 unsigned PreviousGeneration = 0;
3878 if (ContextObj)
3879 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003880
3881 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003882 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003883 switch (ASTReadResult ReadResult =
3884 ReadASTCore(FileName, Type, ImportLoc,
3885 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3886 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003888 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 case OutOfDate:
3890 case VersionMismatch:
3891 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003892 case HadErrors: {
3893 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003894 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00003895 LoadedSet.insert(IM.Mod);
3896
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003897 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003898 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003899 ? &PP.getHeaderSearchInfo().getModuleMap()
3900 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003901
3902 // If we find that any modules are unusable, the global index is going
3903 // to be out-of-date. Just remove it.
3904 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003905 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003907 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003908 case Success:
3909 break;
3910 }
3911
3912 // Here comes stuff that we only do once the entire chain is loaded.
3913
3914 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003915 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3916 MEnd = Loaded.end();
3917 M != MEnd; ++M) {
3918 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00003919
3920 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003921 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3922 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003923
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003924 // Read the extension blocks.
3925 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3926 if (ASTReadResult Result = ReadExtensionBlock(F))
3927 return Result;
3928 }
3929
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003930 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003931 // bits of all files we've seen.
3932 F.GlobalBitOffset = TotalModulesSizeInBits;
3933 TotalModulesSizeInBits += F.SizeInBits;
3934 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003935
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003937 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3938 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00003939 // Load it through the SourceManager and don't call ReadSLocEntry()
3940 // directly because the entry may have already been loaded in which case
3941 // calling ReadSLocEntry() directly would trigger an assertion in
3942 // SourceManager.
3943 SourceMgr.getLoadedSLocEntryByID(Index);
3944 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003945
Richard Smithea741482017-05-01 22:10:47 +00003946 // Map the original source file ID into the ID space of the current
3947 // compilation.
3948 if (F.OriginalSourceFileID.isValid()) {
3949 F.OriginalSourceFileID = FileID::get(
3950 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3951 }
3952
Richard Smith33e0f7e2015-07-22 02:08:40 +00003953 // Preload all the pending interesting identifiers by marking them out of
3954 // date.
3955 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003956 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00003957 F.IdentifierTableData + Offset);
3958
3959 ASTIdentifierLookupTrait Trait(*this, F);
3960 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3961 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003962 auto &II = PP.getIdentifierTable().getOwn(Key);
3963 II.setOutOfDate(true);
3964
3965 // Mark this identifier as being from an AST file so that we can track
3966 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003967 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003968
3969 // Associate the ID with the identifier so that the writer can reuse it.
3970 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3971 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003972 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 }
3974
Douglas Gregor603cd862013-03-22 18:50:14 +00003975 // Setup the import locations and notify the module manager that we've
3976 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003977 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3978 MEnd = Loaded.end();
3979 M != MEnd; ++M) {
3980 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003981
3982 ModuleMgr.moduleFileAccepted(&F);
3983
3984 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003985 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003986 // FIXME: We assume that locations from PCH / preamble do not need
3987 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003988 if (!M->ImportedBy)
3989 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003990 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00003991 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003992 }
3993
Richard Smithdbafb6c2017-06-29 23:23:46 +00003994 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003995 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3996 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003997 // Mark all of the identifiers in the identifier table as being out of date,
3998 // so that various accessors know to check the loaded modules when the
3999 // identifier is used.
4000 //
4001 // For C++ modules, we don't need information on many identifiers (just
4002 // those that provide macros or are poisoned), so we mark all of
4003 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004004 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
4005 IdEnd = PP.getIdentifierTable().end();
4006 Id != IdEnd; ++Id)
4007 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00004008 }
Manman Rena0f31a02016-04-29 19:04:05 +00004009 // Mark selectors as out of date.
4010 for (auto Sel : SelectorGeneration)
4011 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004012
Guy Benyei11169dd2012-12-18 14:30:41 +00004013 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004014 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4015 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004016 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4017 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004018
4019 switch (Unresolved.Kind) {
4020 case UnresolvedModuleRef::Conflict:
4021 if (ResolvedMod) {
4022 Module::Conflict Conflict;
4023 Conflict.Other = ResolvedMod;
4024 Conflict.Message = Unresolved.String.str();
4025 Unresolved.Mod->Conflicts.push_back(Conflict);
4026 }
4027 continue;
4028
4029 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004031 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004032 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004033
Douglas Gregorfb912652013-03-20 21:10:35 +00004034 case UnresolvedModuleRef::Export:
4035 if (ResolvedMod || Unresolved.IsWildcard)
4036 Unresolved.Mod->Exports.push_back(
4037 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4038 continue;
4039 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004040 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004041 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004042
Graydon Hoaree7196af2016-12-09 21:45:49 +00004043 if (Imported)
4044 Imported->append(ImportedModules.begin(),
4045 ImportedModules.end());
4046
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004047 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4048 // Might be unnecessary as use declarations are only used to build the
4049 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004050
Richard Smithdbafb6c2017-06-29 23:23:46 +00004051 if (ContextObj)
4052 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004053
Richard Smith3d8e97e2013-10-18 06:54:39 +00004054 if (SemaObj)
4055 UpdateSema();
4056
Guy Benyei11169dd2012-12-18 14:30:41 +00004057 if (DeserializationListener)
4058 DeserializationListener->ReaderInitialized(this);
4059
4060 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004061 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004062 // If this AST file is a precompiled preamble, then set the
4063 // preamble file ID of the source manager to the file source file
4064 // from which the preamble was built.
4065 if (Type == MK_Preamble) {
4066 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4067 } else if (Type == MK_MainFile) {
4068 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4069 }
4070 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004071
Guy Benyei11169dd2012-12-18 14:30:41 +00004072 // For any Objective-C class definitions we have already loaded, make sure
4073 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004074 if (ContextObj) {
4075 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4076 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4077 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004078 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004079 }
4080 }
Douglas Gregore060e572013-01-25 01:03:03 +00004081
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004082 if (PP.getHeaderSearchInfo()
4083 .getHeaderSearchOpts()
4084 .ModulesValidateOncePerBuildSession) {
4085 // Now we are certain that the module and all modules it depends on are
4086 // up to date. Create or update timestamp files for modules that are
4087 // located in the module cache (not for PCH files that could be anywhere
4088 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004089 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4090 ImportedModule &M = Loaded[I];
4091 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004092 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004093 }
4094 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004095 }
4096
Guy Benyei11169dd2012-12-18 14:30:41 +00004097 return Success;
4098}
4099
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004100static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004102/// Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004103static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004104 return Stream.canSkipToPos(4) &&
4105 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004106 Stream.Read(8) == 'P' &&
4107 Stream.Read(8) == 'C' &&
4108 Stream.Read(8) == 'H';
4109}
4110
Richard Smith0f99d6a2015-08-09 08:48:41 +00004111static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4112 switch (Kind) {
4113 case MK_PCH:
4114 return 0; // PCH
4115 case MK_ImplicitModule:
4116 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004117 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004118 return 1; // module
4119 case MK_MainFile:
4120 case MK_Preamble:
4121 return 2; // main source file
4122 }
4123 llvm_unreachable("unknown module kind");
4124}
4125
Guy Benyei11169dd2012-12-18 14:30:41 +00004126ASTReader::ASTReadResult
4127ASTReader::ReadASTCore(StringRef FileName,
4128 ModuleKind Type,
4129 SourceLocation ImportLoc,
4130 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004131 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004132 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004133 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004134 unsigned ClientLoadCapabilities) {
4135 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004137 ModuleManager::AddModuleResult AddResult
4138 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004139 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004140 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004141 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004142
Douglas Gregor7029ce12013-03-19 00:28:20 +00004143 switch (AddResult) {
4144 case ModuleManager::AlreadyLoaded:
4145 return Success;
4146
4147 case ModuleManager::NewlyLoaded:
4148 // Load module file below.
4149 break;
4150
4151 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004152 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004153 // it.
4154 if (ClientLoadCapabilities & ARR_Missing)
4155 return Missing;
4156
4157 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004158 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004159 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004160 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004161 return Failure;
4162
4163 case ModuleManager::OutOfDate:
4164 // We couldn't load the module file because it is out-of-date. If the
4165 // client can handle out-of-date, return it.
4166 if (ClientLoadCapabilities & ARR_OutOfDate)
4167 return OutOfDate;
4168
4169 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004170 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004171 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004172 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004173 return Failure;
4174 }
4175
Douglas Gregor7029ce12013-03-19 00:28:20 +00004176 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004177
Guy Benyei11169dd2012-12-18 14:30:41 +00004178 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004179 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004180 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004181 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004182
Guy Benyei11169dd2012-12-18 14:30:41 +00004183 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004184 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004185 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4186 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004187 return Failure;
4188 }
4189
4190 // This is used for compatibility with older PCH formats.
4191 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004192 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004193 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004194
Chris Lattnerefa77172013-01-20 00:00:22 +00004195 switch (Entry.Kind) {
4196 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004197 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004198 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 Error("invalid record at top-level of AST file");
4200 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004201
Chris Lattnerefa77172013-01-20 00:00:22 +00004202 case llvm::BitstreamEntry::SubBlock:
4203 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004204 }
4205
Chris Lattnerefa77172013-01-20 00:00:22 +00004206 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 case CONTROL_BLOCK_ID:
4208 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004209 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004210 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004211 // Check that we didn't try to load a non-module AST file as a module.
4212 //
4213 // FIXME: Should we also perform the converse check? Loading a module as
4214 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004215 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4216 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004217 F.ModuleName.empty()) {
4218 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4219 if (Result != OutOfDate ||
4220 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4221 Diag(diag::err_module_file_not_module) << FileName;
4222 return Result;
4223 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 break;
4225
4226 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004227 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 case OutOfDate: return OutOfDate;
4229 case VersionMismatch: return VersionMismatch;
4230 case ConfigurationMismatch: return ConfigurationMismatch;
4231 case HadErrors: return HadErrors;
4232 }
4233 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004234
Guy Benyei11169dd2012-12-18 14:30:41 +00004235 case AST_BLOCK_ID:
4236 if (!HaveReadControlBlock) {
4237 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004238 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004239 return VersionMismatch;
4240 }
4241
4242 // Record that we've loaded this module.
4243 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4244 return Success;
4245
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004246 case UNHASHED_CONTROL_BLOCK_ID:
4247 // This block is handled using look-ahead during ReadControlBlock. We
4248 // shouldn't get here!
4249 Error("malformed block record in AST file");
4250 return Failure;
4251
Guy Benyei11169dd2012-12-18 14:30:41 +00004252 default:
4253 if (Stream.SkipBlock()) {
4254 Error("malformed block record in AST file");
4255 return Failure;
4256 }
4257 break;
4258 }
4259 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004260
4261 return Success;
4262}
4263
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004264ASTReader::ASTReadResult
4265ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4266 unsigned ClientLoadCapabilities) {
4267 const HeaderSearchOptions &HSOpts =
4268 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4269 bool AllowCompatibleConfigurationMismatch =
4270 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4271
4272 ASTReadResult Result = readUnhashedControlBlockImpl(
4273 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4274 Listener.get(),
4275 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4276
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004277 // If F was directly imported by another module, it's implicitly validated by
4278 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004279 if (DisableValidation || WasImportedBy ||
4280 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4281 return Success;
4282
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004283 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004284 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004285 return Failure;
4286 }
4287
4288 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4289 // If this module has already been finalized in the PCMCache, we're stuck
4290 // with it; we can only load a single version of each module.
4291 //
4292 // This can happen when a module is imported in two contexts: in one, as a
4293 // user module; in another, as a system module (due to an import from
4294 // another module marked with the [system] flag). It usually indicates a
4295 // bug in the module map: this module should also be marked with [system].
4296 //
4297 // If -Wno-system-headers (the default), and the first import is as a
4298 // system module, then validation will fail during the as-user import,
4299 // since -Werror flags won't have been validated. However, it's reasonable
4300 // to treat this consistently as a system module.
4301 //
4302 // If -Wsystem-headers, the PCM on disk was built with
4303 // -Wno-system-headers, and the first import is as a user module, then
4304 // validation will fail during the as-system import since the PCM on disk
4305 // doesn't guarantee that -Werror was respected. However, the -Werror
4306 // flags were checked during the initial as-user import.
4307 if (PCMCache.isBufferFinal(F.FileName)) {
4308 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4309 return Success;
4310 }
4311 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004312
4313 return Result;
4314}
4315
4316ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4317 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4318 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4319 bool ValidateDiagnosticOptions) {
4320 // Initialize a stream.
4321 BitstreamCursor Stream(StreamData);
4322
4323 // Sniff for the signature.
4324 if (!startsWithASTFileMagic(Stream))
4325 return Failure;
4326
4327 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4328 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4329 return Failure;
4330
4331 // Read all of the records in the options block.
4332 RecordData Record;
4333 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004334 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004335 llvm::BitstreamEntry Entry = Stream.advance();
4336
4337 switch (Entry.Kind) {
4338 case llvm::BitstreamEntry::Error:
4339 case llvm::BitstreamEntry::SubBlock:
4340 return Failure;
4341
4342 case llvm::BitstreamEntry::EndBlock:
4343 return Result;
4344
4345 case llvm::BitstreamEntry::Record:
4346 // The interesting case.
4347 break;
4348 }
4349
4350 // Read and process a record.
4351 Record.clear();
4352 switch (
4353 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004354 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004355 if (F)
4356 std::copy(Record.begin(), Record.end(), F->Signature.data());
4357 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004358 case DIAGNOSTIC_OPTIONS: {
4359 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4360 if (Listener && ValidateDiagnosticOptions &&
4361 !AllowCompatibleConfigurationMismatch &&
4362 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004363 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004364 break;
4365 }
4366 case DIAG_PRAGMA_MAPPINGS:
4367 if (!F)
4368 break;
4369 if (F->PragmaDiagMappings.empty())
4370 F->PragmaDiagMappings.swap(Record);
4371 else
4372 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4373 Record.begin(), Record.end());
4374 break;
4375 }
4376 }
4377}
4378
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004379/// Parse a record and blob containing module file extension metadata.
4380static bool parseModuleFileExtensionMetadata(
4381 const SmallVectorImpl<uint64_t> &Record,
4382 StringRef Blob,
4383 ModuleFileExtensionMetadata &Metadata) {
4384 if (Record.size() < 4) return true;
4385
4386 Metadata.MajorVersion = Record[0];
4387 Metadata.MinorVersion = Record[1];
4388
4389 unsigned BlockNameLen = Record[2];
4390 unsigned UserInfoLen = Record[3];
4391
4392 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4393
4394 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4395 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4396 Blob.data() + BlockNameLen + UserInfoLen);
4397 return false;
4398}
4399
4400ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4401 BitstreamCursor &Stream = F.Stream;
4402
4403 RecordData Record;
4404 while (true) {
4405 llvm::BitstreamEntry Entry = Stream.advance();
4406 switch (Entry.Kind) {
4407 case llvm::BitstreamEntry::SubBlock:
4408 if (Stream.SkipBlock())
4409 return Failure;
4410
4411 continue;
4412
4413 case llvm::BitstreamEntry::EndBlock:
4414 return Success;
4415
4416 case llvm::BitstreamEntry::Error:
4417 return HadErrors;
4418
4419 case llvm::BitstreamEntry::Record:
4420 break;
4421 }
4422
4423 Record.clear();
4424 StringRef Blob;
4425 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4426 switch (RecCode) {
4427 case EXTENSION_METADATA: {
4428 ModuleFileExtensionMetadata Metadata;
4429 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4430 return Failure;
4431
4432 // Find a module file extension with this block name.
4433 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4434 if (Known == ModuleFileExtensions.end()) break;
4435
4436 // Form a reader.
4437 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4438 F, Stream)) {
4439 F.ExtensionReaders.push_back(std::move(Reader));
4440 }
4441
4442 break;
4443 }
4444 }
4445 }
4446
4447 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004448}
4449
Richard Smitha7e2cc62015-05-01 01:53:09 +00004450void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004451 assert(ContextObj && "no context to initialize");
4452 ASTContext &Context = *ContextObj;
4453
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 // If there's a listener, notify them that we "read" the translation unit.
4455 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004456 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004457 Context.getTranslationUnitDecl());
4458
Guy Benyei11169dd2012-12-18 14:30:41 +00004459 // FIXME: Find a better way to deal with collisions between these
4460 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004461
Guy Benyei11169dd2012-12-18 14:30:41 +00004462 // Load the special types.
4463 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4464 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4465 if (!Context.CFConstantStringTypeDecl)
4466 Context.setCFConstantStringType(GetType(String));
4467 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004468
Guy Benyei11169dd2012-12-18 14:30:41 +00004469 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4470 QualType FileType = GetType(File);
4471 if (FileType.isNull()) {
4472 Error("FILE type is NULL");
4473 return;
4474 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004475
Guy Benyei11169dd2012-12-18 14:30:41 +00004476 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004477 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 Context.setFILEDecl(Typedef->getDecl());
4479 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004480 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004481 if (!Tag) {
4482 Error("Invalid FILE type in AST file");
4483 return;
4484 }
4485 Context.setFILEDecl(Tag->getDecl());
4486 }
4487 }
4488 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004489
Guy Benyei11169dd2012-12-18 14:30:41 +00004490 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4491 QualType Jmp_bufType = GetType(Jmp_buf);
4492 if (Jmp_bufType.isNull()) {
4493 Error("jmp_buf 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.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004498 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 Context.setjmp_bufDecl(Typedef->getDecl());
4500 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004501 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004502 if (!Tag) {
4503 Error("Invalid jmp_buf type in AST file");
4504 return;
4505 }
4506 Context.setjmp_bufDecl(Tag->getDecl());
4507 }
4508 }
4509 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004510
Guy Benyei11169dd2012-12-18 14:30:41 +00004511 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4512 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4513 if (Sigjmp_bufType.isNull()) {
4514 Error("sigjmp_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.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004519 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004520 Context.setsigjmp_bufDecl(Typedef->getDecl());
4521 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004522 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004523 assert(Tag && "Invalid sigjmp_buf type in AST file");
4524 Context.setsigjmp_bufDecl(Tag->getDecl());
4525 }
4526 }
4527 }
4528
4529 if (unsigned ObjCIdRedef
4530 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4531 if (Context.ObjCIdRedefinitionType.isNull())
4532 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4533 }
4534
4535 if (unsigned ObjCClassRedef
4536 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4537 if (Context.ObjCClassRedefinitionType.isNull())
4538 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4539 }
4540
4541 if (unsigned ObjCSelRedef
4542 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4543 if (Context.ObjCSelRedefinitionType.isNull())
4544 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4545 }
4546
4547 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4548 QualType Ucontext_tType = GetType(Ucontext_t);
4549 if (Ucontext_tType.isNull()) {
4550 Error("ucontext_t type is NULL");
4551 return;
4552 }
4553
4554 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004555 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004556 Context.setucontext_tDecl(Typedef->getDecl());
4557 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004558 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004559 assert(Tag && "Invalid ucontext_t type in AST file");
4560 Context.setucontext_tDecl(Tag->getDecl());
4561 }
4562 }
4563 }
4564 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004565
Guy Benyei11169dd2012-12-18 14:30:41 +00004566 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4567
4568 // If there were any CUDA special declarations, deserialize them.
4569 if (!CUDASpecialDeclRefs.empty()) {
4570 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4571 Context.setcudaConfigureCallDecl(
4572 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4573 }
Richard Smith56be7542014-03-21 00:33:59 +00004574
Guy Benyei11169dd2012-12-18 14:30:41 +00004575 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004576 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004577 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004578 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004579 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004580 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004581 if (Import.ImportLoc.isValid())
4582 PP.makeModuleVisible(Imported, Import.ImportLoc);
4583 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004585 }
4586 ImportedModules.clear();
4587}
4588
4589void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004590 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004591}
4592
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004593/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004594/// else returns 0.
4595static ASTFileSignature readASTFileSignature(StringRef PCH) {
4596 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004597 if (!startsWithASTFileMagic(Stream))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004598 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004599
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004600 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4601 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004602 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004603
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004604 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004605 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004606 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004607 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004608 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004609 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004610
4611 Record.clear();
4612 StringRef Blob;
4613 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004614 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4615 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004616 }
4617}
4618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004619/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004620/// directly from the AST file, without actually loading the AST
4621/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004622std::string ASTReader::getOriginalSourceFile(
4623 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004624 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004626 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004628 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4629 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004630 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004631 }
4632
4633 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004634 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004635
4636 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004637 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004638 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004639 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004640 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004641
Chris Lattnere7b154b2013-01-19 21:39:22 +00004642 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004643 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004644 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004645 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004646 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004647
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004648 // Scan for ORIGINAL_FILE inside the control block.
4649 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004650 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004651 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004652 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004653 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004654
Chris Lattnere7b154b2013-01-19 21:39:22 +00004655 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4656 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004657 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004659
Guy Benyei11169dd2012-12-18 14:30:41 +00004660 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004661 StringRef Blob;
4662 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4663 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004665}
4666
4667namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004668
Guy Benyei11169dd2012-12-18 14:30:41 +00004669 class SimplePCHValidator : public ASTReaderListener {
4670 const LangOptions &ExistingLangOpts;
4671 const TargetOptions &ExistingTargetOpts;
4672 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004673 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004674 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004675
Guy Benyei11169dd2012-12-18 14:30:41 +00004676 public:
4677 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4678 const TargetOptions &ExistingTargetOpts,
4679 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004680 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 FileManager &FileMgr)
4682 : ExistingLangOpts(ExistingLangOpts),
4683 ExistingTargetOpts(ExistingTargetOpts),
4684 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004685 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004686 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004687
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004688 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4689 bool AllowCompatibleDifferences) override {
4690 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4691 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004692 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004693
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004694 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4695 bool AllowCompatibleDifferences) override {
4696 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4697 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004698 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004699
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004700 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4701 StringRef SpecificModuleCachePath,
4702 bool Complain) override {
4703 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4704 ExistingModuleCachePath,
4705 nullptr, ExistingLangOpts);
4706 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004707
Craig Topper3e89dfe2014-03-13 02:13:41 +00004708 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4709 bool Complain,
4710 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004711 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004712 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004713 }
4714 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004715
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004716} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004717
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004718bool ASTReader::readASTFileControlBlock(
4719 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004720 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004721 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004722 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004723 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004724 // FIXME: This allows use of the VFS; we do not allow use of the
4725 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004726 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004727 if (!Buffer) {
4728 return true;
4729 }
4730
4731 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004732 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4733 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004734
4735 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004736 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004738
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004739 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004740 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004741 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004742
4743 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004744 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004745 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004746 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004747
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004749 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004750 bool DoneWithControlBlock = false;
4751 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004752 llvm::BitstreamEntry Entry = Stream.advance();
4753
4754 switch (Entry.Kind) {
4755 case llvm::BitstreamEntry::SubBlock: {
4756 switch (Entry.ID) {
4757 case OPTIONS_BLOCK_ID: {
4758 std::string IgnoredSuggestedPredefines;
4759 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4760 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004761 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004762 return true;
4763 break;
4764 }
4765
4766 case INPUT_FILES_BLOCK_ID:
4767 InputFilesCursor = Stream;
4768 if (Stream.SkipBlock() ||
4769 (NeedsInputFiles &&
4770 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4771 return true;
4772 break;
4773
4774 default:
4775 if (Stream.SkipBlock())
4776 return true;
4777 break;
4778 }
4779
4780 continue;
4781 }
4782
4783 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004784 DoneWithControlBlock = true;
4785 break;
Richard Smith0516b182015-09-08 19:40:14 +00004786
4787 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004788 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004789
4790 case llvm::BitstreamEntry::Record:
4791 break;
4792 }
4793
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004794 if (DoneWithControlBlock) break;
4795
Guy Benyei11169dd2012-12-18 14:30:41 +00004796 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004797 StringRef Blob;
4798 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004799 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004800 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004801 if (Record[0] != VERSION_MAJOR)
4802 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004803 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004804 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004805 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004806 case MODULE_NAME:
4807 Listener.ReadModuleName(Blob);
4808 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004809 case MODULE_DIRECTORY:
4810 ModuleDir = Blob;
4811 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004812 case MODULE_MAP_FILE: {
4813 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004814 auto Path = ReadString(Record, Idx);
4815 ResolveImportedPath(Path, ModuleDir);
4816 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004817 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004818 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004819 case INPUT_FILE_OFFSETS: {
4820 if (!NeedsInputFiles)
4821 break;
4822
4823 unsigned NumInputFiles = Record[0];
4824 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00004825 const llvm::support::unaligned_uint64_t *InputFileOffs =
4826 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004827 for (unsigned I = 0; I != NumInputFiles; ++I) {
4828 // Go find this input file.
4829 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004830
4831 if (isSystemFile && !NeedsSystemInputFiles)
4832 break; // the rest are system input files
4833
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004834 BitstreamCursor &Cursor = InputFilesCursor;
4835 SavedStreamPosition SavedPosition(Cursor);
4836 Cursor.JumpToBit(InputFileOffs[I]);
4837
4838 unsigned Code = Cursor.ReadCode();
4839 RecordData Record;
4840 StringRef Blob;
4841 bool shouldContinue = false;
4842 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4843 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00004844 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004845 std::string Filename = Blob;
4846 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004847 shouldContinue = Listener.visitInputFile(
4848 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004849 break;
4850 }
4851 if (!shouldContinue)
4852 break;
4853 }
4854 break;
4855 }
4856
Richard Smithd4b230b2014-10-27 23:01:16 +00004857 case IMPORTS: {
4858 if (!NeedsImports)
4859 break;
4860
4861 unsigned Idx = 0, N = Record.size();
4862 while (Idx < N) {
4863 // Read information about the AST file.
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00004864 Idx += 1+1+1+1+5; // Kind, ImportLoc, Size, ModTime, Signature
4865 std::string ModuleName = ReadString(Record, Idx);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004866 std::string Filename = ReadString(Record, Idx);
4867 ResolveImportedPath(Filename, ModuleDir);
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +00004868 Listener.visitImport(ModuleName, Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004869 }
4870 break;
4871 }
4872
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004873 default:
4874 // No other validation to perform.
4875 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 }
4877 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004878
4879 // Look for module file extension blocks, if requested.
4880 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004881 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004882 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4883 bool DoneWithExtensionBlock = false;
4884 while (!DoneWithExtensionBlock) {
4885 llvm::BitstreamEntry Entry = Stream.advance();
4886
4887 switch (Entry.Kind) {
4888 case llvm::BitstreamEntry::SubBlock:
4889 if (Stream.SkipBlock())
4890 return true;
4891
4892 continue;
4893
4894 case llvm::BitstreamEntry::EndBlock:
4895 DoneWithExtensionBlock = true;
4896 continue;
4897
4898 case llvm::BitstreamEntry::Error:
4899 return true;
4900
4901 case llvm::BitstreamEntry::Record:
4902 break;
4903 }
4904
4905 Record.clear();
4906 StringRef Blob;
4907 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4908 switch (RecCode) {
4909 case EXTENSION_METADATA: {
4910 ModuleFileExtensionMetadata Metadata;
4911 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4912 return true;
4913
4914 Listener.readModuleFileExtension(Metadata);
4915 break;
4916 }
4917 }
4918 }
4919 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004920 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004921 }
4922
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004923 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4924 if (readUnhashedControlBlockImpl(
4925 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4926 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4927 ValidateDiagnosticOptions) != Success)
4928 return true;
4929
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004930 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004931}
4932
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004933bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4934 const PCHContainerReader &PCHContainerRdr,
4935 const LangOptions &LangOpts,
4936 const TargetOptions &TargetOpts,
4937 const PreprocessorOptions &PPOpts,
4938 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004939 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4940 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004941 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004942 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004943 validator,
4944 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004945}
4946
Ben Langmuir2c9af442014-04-10 17:57:43 +00004947ASTReader::ASTReadResult
4948ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 // Enter the submodule block.
4950 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4951 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004952 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004953 }
4954
4955 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4956 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004957 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004958 RecordData Record;
4959 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004960 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004961
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004962 switch (Entry.Kind) {
4963 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4964 case llvm::BitstreamEntry::Error:
4965 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004966 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004967 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004968 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004969 case llvm::BitstreamEntry::Record:
4970 // The interesting case.
4971 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004973
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004975 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004976 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004977 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4978
4979 if ((Kind == SUBMODULE_METADATA) != First) {
4980 Error("submodule metadata record should be at beginning of block");
4981 return Failure;
4982 }
4983 First = false;
4984
4985 // Submodule information is only valid if we have a current module.
4986 // FIXME: Should we error on these cases?
4987 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4988 Kind != SUBMODULE_DEFINITION)
4989 continue;
4990
4991 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004992 default: // Default behavior: ignore.
4993 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004994
Richard Smith03478d92014-10-23 22:12:14 +00004995 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00004996 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004997 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004998 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004999 }
Richard Smith03478d92014-10-23 22:12:14 +00005000
Chris Lattner0e6c9402013-01-20 02:38:54 +00005001 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00005002 unsigned Idx = 0;
5003 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
5004 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005005 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00005006 bool IsFramework = Record[Idx++];
5007 bool IsExplicit = Record[Idx++];
5008 bool IsSystem = Record[Idx++];
5009 bool IsExternC = Record[Idx++];
5010 bool InferSubmodules = Record[Idx++];
5011 bool InferExplicitSubmodules = Record[Idx++];
5012 bool InferExportWildcard = Record[Idx++];
5013 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005014 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005015
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005016 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005017 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005019
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 // Retrieve this (sub)module from the module map, creating it if
5021 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005022 CurrentModule =
5023 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5024 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005025
5026 // FIXME: set the definition loc for CurrentModule, or call
5027 // ModMap.setInferredModuleAllowedBy()
5028
Guy Benyei11169dd2012-12-18 14:30:41 +00005029 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5030 if (GlobalIndex >= SubmodulesLoaded.size() ||
5031 SubmodulesLoaded[GlobalIndex]) {
5032 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005033 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005035
Douglas Gregor7029ce12013-03-19 00:28:20 +00005036 if (!ParentModule) {
5037 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
Yuka Takahashid8baec22018-08-01 09:50:02 +00005038 // Don't emit module relocation error if we have -fno-validate-pch
5039 if (!PP.getPreprocessorOpts().DisablePCHValidation &&
5040 CurFile != F.File) {
Douglas Gregor7029ce12013-03-19 00:28:20 +00005041 if (!Diags.isDiagnosticInFlight()) {
5042 Diag(diag::err_module_file_conflict)
5043 << CurrentModule->getTopLevelModuleName()
5044 << CurFile->getName()
5045 << F.File->getName();
5046 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005047 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005048 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005049 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005050
5051 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005052 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005053 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005054
Richard Smithdd8b5332017-09-04 05:37:53 +00005055 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005056 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 CurrentModule->IsFromModuleFile = true;
5058 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005059 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 CurrentModule->InferSubmodules = InferSubmodules;
5061 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5062 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005063 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005064 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005065 if (DeserializationListener)
5066 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005067
Guy Benyei11169dd2012-12-18 14:30:41 +00005068 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005069
Richard Smith8a3e39a2016-03-28 21:31:09 +00005070 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005071 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005072 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005073 CurrentModule->UnresolvedConflicts.clear();
5074 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005075
5076 // The module is available unless it's missing a requirement; relevant
5077 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5078 // Missing headers that were present when the module was built do not
5079 // make it unavailable -- if we got this far, this must be an explicitly
5080 // imported module file.
5081 CurrentModule->Requirements.clear();
5082 CurrentModule->MissingHeaders.clear();
5083 CurrentModule->IsMissingRequirement =
5084 ParentModule && ParentModule->IsMissingRequirement;
5085 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 break;
5087 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005088
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005090 std::string Filename = Blob;
5091 ResolveImportedPath(F, Filename);
5092 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005093 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005094 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5095 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005096 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5097 Error("mismatched umbrella headers in submodule");
5098 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 }
5100 }
5101 break;
5102 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005103
Richard Smith202210b2014-10-24 20:23:01 +00005104 case SUBMODULE_HEADER:
5105 case SUBMODULE_EXCLUDED_HEADER:
5106 case SUBMODULE_PRIVATE_HEADER:
5107 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005108 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5109 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005110 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005111
Richard Smith202210b2014-10-24 20:23:01 +00005112 case SUBMODULE_TEXTUAL_HEADER:
5113 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5114 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5115 // them here.
5116 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005117
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005118 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005119 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005120 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005121
5122 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005123 std::string Dirname = Blob;
5124 ResolveImportedPath(F, Dirname);
5125 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005126 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005127 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5128 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005129 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5130 Error("mismatched umbrella directories in submodule");
5131 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005132 }
5133 }
5134 break;
5135 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005136
Guy Benyei11169dd2012-12-18 14:30:41 +00005137 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005138 F.BaseSubmoduleID = getTotalNumSubmodules();
5139 F.LocalNumSubmodules = Record[0];
5140 unsigned LocalBaseSubmoduleID = Record[1];
5141 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005142 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005143 // module.
5144 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005145
5146 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 // module.
5148 F.SubmoduleRemap.insertOrReplace(
5149 std::make_pair(LocalBaseSubmoduleID,
5150 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005151
Ben Langmuir52ca6782014-10-20 16:27:32 +00005152 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5153 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 break;
5155 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005156
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005157 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005158 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005159 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005160 Unresolved.File = &F;
5161 Unresolved.Mod = CurrentModule;
5162 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005163 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005165 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005166 }
5167 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005168
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005169 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005170 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005171 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005172 Unresolved.File = &F;
5173 Unresolved.Mod = CurrentModule;
5174 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005175 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005176 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005177 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005178 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005179
5180 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005181 // the parsed, unresolved exports around.
5182 CurrentModule->UnresolvedExports.clear();
5183 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005184
5185 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005186 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5187 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005189
5190 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005191 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005192 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005193 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005194 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005195
5196 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005197 CurrentModule->ConfigMacros.push_back(Blob.str());
5198 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005199
5200 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005201 UnresolvedModuleRef Unresolved;
5202 Unresolved.File = &F;
5203 Unresolved.Mod = CurrentModule;
5204 Unresolved.ID = Record[0];
5205 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5206 Unresolved.IsWildcard = false;
5207 Unresolved.String = Blob;
5208 UnresolvedModuleRefs.push_back(Unresolved);
5209 break;
5210 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005211
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005212 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005213 if (!ContextObj)
5214 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005215 SmallVector<uint32_t, 16> Inits;
5216 for (auto &ID : Record)
5217 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005218 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005219 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005220 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005221
5222 case SUBMODULE_EXPORT_AS:
5223 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005224 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005225 break;
5226 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005227 }
5228}
5229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005230/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005231/// structure.
5232///
5233/// This routine parses the language options from the AST file and then gives
5234/// them to the AST listener if one is set.
5235///
5236/// \returns true if the listener deems the file unacceptable, false otherwise.
5237bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5238 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005239 ASTReaderListener &Listener,
5240 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005241 LangOptions LangOpts;
5242 unsigned Idx = 0;
5243#define LANGOPT(Name, Bits, Default, Description) \
5244 LangOpts.Name = Record[Idx++];
5245#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5246 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5247#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005248#define SANITIZER(NAME, ID) \
5249 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005250#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005251
Ben Langmuircd98cb72015-06-23 18:20:18 +00005252 for (unsigned N = Record[Idx++]; N; --N)
5253 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5254
Vedant Kumar48b4f762018-04-14 01:40:48 +00005255 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005256 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5257 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005258
Ben Langmuird4a667a2015-06-23 18:20:23 +00005259 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005260
5261 // Comment options.
5262 for (unsigned N = Record[Idx++]; N; --N) {
5263 LangOpts.CommentOpts.BlockCommandNames.push_back(
5264 ReadString(Record, Idx));
5265 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005266 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005267
Samuel Antaoee8fb302016-01-06 13:42:12 +00005268 // OpenMP offloading options.
5269 for (unsigned N = Record[Idx++]; N; --N) {
5270 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5271 }
5272
5273 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5274
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005275 return Listener.ReadLanguageOptions(LangOpts, Complain,
5276 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005277}
5278
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005279bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5280 ASTReaderListener &Listener,
5281 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 unsigned Idx = 0;
5283 TargetOptions TargetOpts;
5284 TargetOpts.Triple = ReadString(Record, Idx);
5285 TargetOpts.CPU = ReadString(Record, Idx);
5286 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005287 for (unsigned N = Record[Idx++]; N; --N) {
5288 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5289 }
5290 for (unsigned N = Record[Idx++]; N; --N) {
5291 TargetOpts.Features.push_back(ReadString(Record, Idx));
5292 }
5293
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005294 return Listener.ReadTargetOptions(TargetOpts, Complain,
5295 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005296}
5297
5298bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5299 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005300 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005301 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005302#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005303#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005304 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005305#include "clang/Basic/DiagnosticOptions.def"
5306
Richard Smith3be1cb22014-08-07 00:24:21 +00005307 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005308 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005309 for (unsigned N = Record[Idx++]; N; --N)
5310 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005311
5312 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5313}
5314
5315bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5316 ASTReaderListener &Listener) {
5317 FileSystemOptions FSOpts;
5318 unsigned Idx = 0;
5319 FSOpts.WorkingDir = ReadString(Record, Idx);
5320 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5321}
5322
5323bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5324 bool Complain,
5325 ASTReaderListener &Listener) {
5326 HeaderSearchOptions HSOpts;
5327 unsigned Idx = 0;
5328 HSOpts.Sysroot = ReadString(Record, Idx);
5329
5330 // Include entries.
5331 for (unsigned N = Record[Idx++]; N; --N) {
5332 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005333 frontend::IncludeDirGroup Group
5334 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 bool IsFramework = Record[Idx++];
5336 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005337 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5338 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005339 }
5340
5341 // System header prefixes.
5342 for (unsigned N = Record[Idx++]; N; --N) {
5343 std::string Prefix = ReadString(Record, Idx);
5344 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005345 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005346 }
5347
5348 HSOpts.ResourceDir = ReadString(Record, Idx);
5349 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005350 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005352 HSOpts.ImplicitModuleMaps = Record[Idx++];
5353 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005354 HSOpts.UseBuiltinIncludes = Record[Idx++];
5355 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5356 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5357 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005358 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005359
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005360 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5361 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005362}
5363
5364bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5365 bool Complain,
5366 ASTReaderListener &Listener,
5367 std::string &SuggestedPredefines) {
5368 PreprocessorOptions PPOpts;
5369 unsigned Idx = 0;
5370
5371 // Macro definitions/undefs
5372 for (unsigned N = Record[Idx++]; N; --N) {
5373 std::string Macro = ReadString(Record, Idx);
5374 bool IsUndef = Record[Idx++];
5375 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5376 }
5377
5378 // Includes
5379 for (unsigned N = Record[Idx++]; N; --N) {
5380 PPOpts.Includes.push_back(ReadString(Record, Idx));
5381 }
5382
5383 // Macro Includes
5384 for (unsigned N = Record[Idx++]; N; --N) {
5385 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5386 }
5387
5388 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005389 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005390 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5391 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5392 PPOpts.ObjCXXARCStandardLibrary =
5393 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5394 SuggestedPredefines.clear();
5395 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5396 SuggestedPredefines);
5397}
5398
5399std::pair<ModuleFile *, unsigned>
5400ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5401 GlobalPreprocessedEntityMapType::iterator
5402 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005403 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005404 "Corrupted global preprocessed entity map");
5405 ModuleFile *M = I->second;
5406 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5407 return std::make_pair(M, LocalIndex);
5408}
5409
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005410llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005411ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5412 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5413 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5414 Mod.NumPreprocessedEntities);
5415
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005416 return llvm::make_range(PreprocessingRecord::iterator(),
5417 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005418}
5419
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005420llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005421ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005422 return llvm::make_range(
5423 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5424 ModuleDeclIterator(this, &Mod,
5425 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005426}
5427
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005428SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5429 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5430 assert(I != GlobalSkippedRangeMap.end() &&
5431 "Corrupted global skipped range map");
5432 ModuleFile *M = I->second;
5433 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5434 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5435 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5436 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5437 TranslateSourceLocation(*M, RawRange.getEnd()));
5438 assert(Range.isValid());
5439 return Range;
5440}
5441
Guy Benyei11169dd2012-12-18 14:30:41 +00005442PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5443 PreprocessedEntityID PPID = Index+1;
5444 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5445 ModuleFile &M = *PPInfo.first;
5446 unsigned LocalIndex = PPInfo.second;
5447 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5448
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 if (!PP.getPreprocessingRecord()) {
5450 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005451 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005453
5454 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005455 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5456
5457 llvm::BitstreamEntry Entry =
5458 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5459 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005460 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005461
Guy Benyei11169dd2012-12-18 14:30:41 +00005462 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005463 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5464 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005465 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005466 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 RecordData Record;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005468 PreprocessorDetailRecordTypes RecType =
5469 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5470 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 switch (RecType) {
5472 case PPD_MACRO_EXPANSION: {
5473 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005474 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005475 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 if (isBuiltin)
5477 Name = getLocalIdentifier(M, Record[1]);
5478 else {
Richard Smith66a81862015-05-04 02:25:31 +00005479 PreprocessedEntityID GlobalID =
5480 getGlobalPreprocessedEntityID(M, Record[1]);
5481 Def = cast<MacroDefinitionRecord>(
5482 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005483 }
5484
5485 MacroExpansion *ME;
5486 if (isBuiltin)
5487 ME = new (PPRec) MacroExpansion(Name, Range);
5488 else
5489 ME = new (PPRec) MacroExpansion(Def, Range);
5490
5491 return ME;
5492 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005493
Guy Benyei11169dd2012-12-18 14:30:41 +00005494 case PPD_MACRO_DEFINITION: {
5495 // Decode the identifier info and then check again; if the macro is
5496 // still defined and associated with the identifier,
5497 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005498 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005499
5500 if (DeserializationListener)
5501 DeserializationListener->MacroDefinitionRead(PPID, MD);
5502
5503 return MD;
5504 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005505
Guy Benyei11169dd2012-12-18 14:30:41 +00005506 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005507 const char *FullFileNameStart = Blob.data() + Record[0];
5508 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005509 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 if (!FullFileName.empty())
5511 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005512
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005514 InclusionDirective::InclusionKind Kind
5515 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5516 InclusionDirective *ID
5517 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005518 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 Record[1], Record[3],
5520 File,
5521 Range);
5522 return ID;
5523 }
5524 }
5525
5526 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5527}
5528
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005529/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005530/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005531///
5532/// \param SLocMapI points at a chunk of a module that contains no
5533/// preprocessed entities or the entities it contains are not the ones we are
5534/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005535PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5536 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5537 ++SLocMapI;
5538 for (GlobalSLocOffsetMapType::const_iterator
5539 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5540 ModuleFile &M = *SLocMapI->second;
5541 if (M.NumPreprocessedEntities)
5542 return M.BasePreprocessedEntityID;
5543 }
5544
5545 return getTotalNumPreprocessedEntities();
5546}
5547
5548namespace {
5549
Guy Benyei11169dd2012-12-18 14:30:41 +00005550struct PPEntityComp {
5551 const ASTReader &Reader;
5552 ModuleFile &M;
5553
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005554 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005555
5556 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5557 SourceLocation LHS = getLoc(L);
5558 SourceLocation RHS = getLoc(R);
5559 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5560 }
5561
5562 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5563 SourceLocation LHS = getLoc(L);
5564 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5565 }
5566
5567 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5568 SourceLocation RHS = getLoc(R);
5569 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5570 }
5571
5572 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005573 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005574 }
5575};
5576
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005577} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005578
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005579PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5580 bool EndsAfter) const {
5581 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005582 return getTotalNumPreprocessedEntities();
5583
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005584 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5585 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005586 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5587 "Corrupted global sloc offset map");
5588
5589 if (SLocMapI->second->NumPreprocessedEntities == 0)
5590 return findNextPreprocessedEntity(SLocMapI);
5591
5592 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005593
5594 using pp_iterator = const PPEntityOffset *;
5595
Guy Benyei11169dd2012-12-18 14:30:41 +00005596 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5597 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5598
5599 size_t Count = M.NumPreprocessedEntities;
5600 size_t Half;
5601 pp_iterator First = pp_begin;
5602 pp_iterator PPI;
5603
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005604 if (EndsAfter) {
5605 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005606 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005607 } else {
5608 // Do a binary search manually instead of using std::lower_bound because
5609 // The end locations of entities may be unordered (when a macro expansion
5610 // is inside another macro argument), but for this case it is not important
5611 // whether we get the first macro expansion or its containing macro.
5612 while (Count > 0) {
5613 Half = Count / 2;
5614 PPI = First;
5615 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005616 if (SourceMgr.isBeforeInTranslationUnit(
5617 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005618 First = PPI;
5619 ++First;
5620 Count = Count - Half - 1;
5621 } else
5622 Count = Half;
5623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005624 }
5625
5626 if (PPI == pp_end)
5627 return findNextPreprocessedEntity(SLocMapI);
5628
5629 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5630}
5631
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005632/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00005633/// preprocessed entities that \arg Range encompasses.
5634std::pair<unsigned, unsigned>
5635 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5636 if (Range.isInvalid())
5637 return std::make_pair(0,0);
5638 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5639
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005640 PreprocessedEntityID BeginID =
5641 findPreprocessedEntity(Range.getBegin(), false);
5642 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005643 return std::make_pair(BeginID, EndID);
5644}
5645
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005646/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00005647/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005648Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005649 FileID FID) {
5650 if (FID.isInvalid())
5651 return false;
5652
5653 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5654 ModuleFile &M = *PPInfo.first;
5655 unsigned LocalIndex = PPInfo.second;
5656 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005657
Richard Smithcb34bd32016-03-27 07:28:06 +00005658 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005659 if (Loc.isInvalid())
5660 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005661
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5663 return true;
5664 else
5665 return false;
5666}
5667
5668namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005670 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00005671 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005672 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005673 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005674
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005676 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005677
5678 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00005679 HeaderFileInfoLookupTable *Table
5680 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 if (!Table)
5682 return false;
5683
5684 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005685 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005686 if (Pos == Table->end())
5687 return false;
5688
Richard Smithbdf2d932015-07-30 03:37:16 +00005689 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005690 return true;
5691 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005692
David Blaikie05785d12013-02-20 22:23:23 +00005693 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005694 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005695
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005696} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005697
5698HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005699 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005700 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005701 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005702 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005703
Guy Benyei11169dd2012-12-18 14:30:41 +00005704 return HeaderFileInfo();
5705}
5706
5707void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005708 using DiagState = DiagnosticsEngine::DiagState;
5709 SmallVector<DiagState *, 32> DiagStates;
5710
Vedant Kumar48b4f762018-04-14 01:40:48 +00005711 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005712 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005713 auto &Record = F.PragmaDiagMappings;
5714 if (Record.empty())
5715 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005716
Richard Smithd230de22017-01-26 01:01:01 +00005717 DiagStates.clear();
5718
5719 auto ReadDiagState =
5720 [&](const DiagState &BasedOn, SourceLocation Loc,
5721 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5722 unsigned BackrefID = Record[Idx++];
5723 if (BackrefID != 0)
5724 return DiagStates[BackrefID - 1];
5725
Guy Benyei11169dd2012-12-18 14:30:41 +00005726 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005727 Diag.DiagStates.push_back(BasedOn);
5728 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005729 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005730 unsigned Size = Record[Idx++];
5731 assert(Idx + Size * 2 <= Record.size() &&
5732 "Invalid data, not enough diag/map pairs");
5733 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005734 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005735 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005736 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005737 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5738 continue;
5739
5740 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5741
5742 // If this mapping was specified as a warning but the severity was
5743 // upgraded due to diagnostic settings, simulate the current diagnostic
5744 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005745 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5746 NewMapping.setSeverity(diag::Severity::Warning);
5747 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005748 }
5749
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005750 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005751 }
Richard Smithd230de22017-01-26 01:01:01 +00005752 return NewState;
5753 };
5754
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005755 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005756 DiagState *FirstState;
5757 if (F.Kind == MK_ImplicitModule) {
5758 // Implicitly-built modules are reused with different diagnostic
5759 // settings. Use the initial diagnostic state from Diag to simulate this
5760 // compilation's diagnostic settings.
5761 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5762 DiagStates.push_back(FirstState);
5763
5764 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005765 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005766 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005767 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005768 assert(Idx < Record.size() &&
5769 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005770 } else if (F.isModule()) {
5771 // For an explicit module, preserve the flags from the module build
5772 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5773 // -Wblah flags.
5774 unsigned Flags = Record[Idx++];
5775 DiagState Initial;
5776 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5777 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5778 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5779 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5780 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5781 Initial.ExtBehavior = (diag::Severity)Flags;
5782 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005783
Richard Smith6c2b5a82018-02-09 01:15:13 +00005784 assert(F.OriginalSourceFileID.isValid());
5785
Richard Smithe37391c2017-05-03 00:28:49 +00005786 // Set up the root buffer of the module to start with the initial
5787 // diagnostic state of the module itself, to cover files that contain no
5788 // explicit transitions (for which we did not serialize anything).
5789 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5790 .StateTransitions.push_back({FirstState, 0});
5791 } else {
5792 // For prefix ASTs, start with whatever the user configured on the
5793 // command line.
5794 Idx++; // Skip flags.
5795 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5796 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005797 }
Richard Smithd230de22017-01-26 01:01:01 +00005798
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005799 // Read the state transitions.
5800 unsigned NumLocations = Record[Idx++];
5801 while (NumLocations--) {
5802 assert(Idx < Record.size() &&
5803 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005804 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5805 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00005806 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00005807 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5808 unsigned Transitions = Record[Idx++];
5809
5810 // Note that we don't need to set up Parent/ParentOffset here, because
5811 // we won't be changing the diagnostic state within imported FileIDs
5812 // (other than perhaps appending to the main source file, which has no
5813 // parent).
5814 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5815 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5816 for (unsigned I = 0; I != Transitions; ++I) {
5817 unsigned Offset = Record[Idx++];
5818 auto *State =
5819 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5820 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005821 }
5822 }
Richard Smithd230de22017-01-26 01:01:01 +00005823
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005824 // Read the final state.
5825 assert(Idx < Record.size() &&
5826 "Invalid data, missing final pragma diagnostic state");
5827 SourceLocation CurStateLoc =
5828 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5829 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5830
5831 if (!F.isModule()) {
5832 Diag.DiagStatesByLoc.CurDiagState = CurState;
5833 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5834
5835 // Preserve the property that the imaginary root file describes the
5836 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005837 FileID NullFile;
5838 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005839 if (T.empty())
5840 T.push_back({CurState, 0});
5841 else
5842 T[0].State = CurState;
5843 }
5844
Richard Smithd230de22017-01-26 01:01:01 +00005845 // Don't try to read these mappings again.
5846 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005847 }
5848}
5849
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005850/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00005851ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5852 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5853 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5854 ModuleFile *M = I->second;
5855 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5856}
5857
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005858/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00005859///
5860/// The index is the type ID, shifted and minus the number of predefs. This
5861/// routine actually reads the record corresponding to the type at the given
5862/// location. It is a helper routine for GetType, which deals with reading type
5863/// IDs.
5864QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005865 assert(ContextObj && "reading type with no AST context");
5866 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005868 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005869
5870 // Keep track of where we are in the stream, then jump back there
5871 // after reading this type.
5872 SavedStreamPosition SavedPosition(DeclsCursor);
5873
5874 ReadingKindTracker ReadingKind(Read_Type, *this);
5875
5876 // Note that we are loading a type record.
5877 Deserializing AType(this);
5878
5879 unsigned Idx = 0;
5880 DeclsCursor.JumpToBit(Loc.Offset);
5881 RecordData Record;
5882 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005883 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 case TYPE_EXT_QUAL: {
5885 if (Record.size() != 2) {
5886 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005887 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005888 }
5889 QualType Base = readType(*Loc.F, Record, Idx);
5890 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5891 return Context.getQualifiedType(Base, Quals);
5892 }
5893
5894 case TYPE_COMPLEX: {
5895 if (Record.size() != 1) {
5896 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005897 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005898 }
5899 QualType ElemType = readType(*Loc.F, Record, Idx);
5900 return Context.getComplexType(ElemType);
5901 }
5902
5903 case TYPE_POINTER: {
5904 if (Record.size() != 1) {
5905 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005906 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005907 }
5908 QualType PointeeType = readType(*Loc.F, Record, Idx);
5909 return Context.getPointerType(PointeeType);
5910 }
5911
Reid Kleckner8a365022013-06-24 17:51:48 +00005912 case TYPE_DECAYED: {
5913 if (Record.size() != 1) {
5914 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005915 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00005916 }
5917 QualType OriginalType = readType(*Loc.F, Record, Idx);
5918 QualType DT = Context.getAdjustedParameterType(OriginalType);
5919 if (!isa<DecayedType>(DT))
5920 Error("Decayed type does not decay");
5921 return DT;
5922 }
5923
Reid Kleckner0503a872013-12-05 01:23:43 +00005924 case TYPE_ADJUSTED: {
5925 if (Record.size() != 2) {
5926 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005927 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00005928 }
5929 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5930 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5931 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5932 }
5933
Guy Benyei11169dd2012-12-18 14:30:41 +00005934 case TYPE_BLOCK_POINTER: {
5935 if (Record.size() != 1) {
5936 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005937 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 }
5939 QualType PointeeType = readType(*Loc.F, Record, Idx);
5940 return Context.getBlockPointerType(PointeeType);
5941 }
5942
5943 case TYPE_LVALUE_REFERENCE: {
5944 if (Record.size() != 2) {
5945 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005946 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 }
5948 QualType PointeeType = readType(*Loc.F, Record, Idx);
5949 return Context.getLValueReferenceType(PointeeType, Record[1]);
5950 }
5951
5952 case TYPE_RVALUE_REFERENCE: {
5953 if (Record.size() != 1) {
5954 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005955 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005956 }
5957 QualType PointeeType = readType(*Loc.F, Record, Idx);
5958 return Context.getRValueReferenceType(PointeeType);
5959 }
5960
5961 case TYPE_MEMBER_POINTER: {
5962 if (Record.size() != 2) {
5963 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005964 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005965 }
5966 QualType PointeeType = readType(*Loc.F, Record, Idx);
5967 QualType ClassType = readType(*Loc.F, Record, Idx);
5968 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00005969 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005970
Guy Benyei11169dd2012-12-18 14:30:41 +00005971 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5972 }
5973
5974 case TYPE_CONSTANT_ARRAY: {
5975 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005976 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005977 unsigned IndexTypeQuals = Record[2];
5978 unsigned Idx = 3;
5979 llvm::APInt Size = ReadAPInt(Record, Idx);
5980 return Context.getConstantArrayType(ElementType, Size,
5981 ASM, IndexTypeQuals);
5982 }
5983
5984 case TYPE_INCOMPLETE_ARRAY: {
5985 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005986 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005987 unsigned IndexTypeQuals = Record[2];
5988 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5989 }
5990
5991 case TYPE_VARIABLE_ARRAY: {
5992 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005993 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005994 unsigned IndexTypeQuals = Record[2];
5995 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5996 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5997 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5998 ASM, IndexTypeQuals,
5999 SourceRange(LBLoc, RBLoc));
6000 }
6001
6002 case TYPE_VECTOR: {
6003 if (Record.size() != 3) {
6004 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006005 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006006 }
6007
6008 QualType ElementType = readType(*Loc.F, Record, Idx);
6009 unsigned NumElements = Record[1];
6010 unsigned VecKind = Record[2];
6011 return Context.getVectorType(ElementType, NumElements,
6012 (VectorType::VectorKind)VecKind);
6013 }
6014
6015 case TYPE_EXT_VECTOR: {
6016 if (Record.size() != 3) {
6017 Error("incorrect encoding of extended vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006018 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006019 }
6020
6021 QualType ElementType = readType(*Loc.F, Record, Idx);
6022 unsigned NumElements = Record[1];
6023 return Context.getExtVectorType(ElementType, NumElements);
6024 }
6025
6026 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006027 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006029 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006030 }
6031 QualType ResultType = readType(*Loc.F, Record, Idx);
6032 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Fangrui Song6907ce22018-07-30 19:24:48 +00006033 (CallingConv)Record[4], Record[5], Record[6],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006034 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006035 return Context.getFunctionNoProtoType(ResultType, Info);
6036 }
6037
6038 case TYPE_FUNCTION_PROTO: {
6039 QualType ResultType = readType(*Loc.F, Record, Idx);
6040
6041 FunctionProtoType::ExtProtoInfo EPI;
6042 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6043 /*hasregparm*/ Record[2],
6044 /*regparm*/ Record[3],
6045 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006046 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006047 /*nocallersavedregs*/ Record[6],
6048 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006049
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006050 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006051
6052 EPI.Variadic = Record[Idx++];
6053 EPI.HasTrailingReturn = Record[Idx++];
6054 EPI.TypeQuals = Record[Idx++];
6055 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006056 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006057 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006058
6059 unsigned NumParams = Record[Idx++];
6060 SmallVector<QualType, 16> ParamTypes;
6061 for (unsigned I = 0; I != NumParams; ++I)
6062 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6063
John McCall18afab72016-03-01 00:49:02 +00006064 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6065 if (Idx != Record.size()) {
6066 for (unsigned I = 0; I != NumParams; ++I)
6067 ExtParameterInfos.push_back(
6068 FunctionProtoType::ExtParameterInfo
6069 ::getFromOpaqueValue(Record[Idx++]));
6070 EPI.ExtParameterInfos = ExtParameterInfos.data();
6071 }
6072
6073 assert(Idx == Record.size());
6074
Jordan Rose5c382722013-03-08 21:51:21 +00006075 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006076 }
6077
6078 case TYPE_UNRESOLVED_USING: {
6079 unsigned Idx = 0;
6080 return Context.getTypeDeclType(
6081 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6082 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006083
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 case TYPE_TYPEDEF: {
6085 if (Record.size() != 2) {
6086 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006087 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006088 }
6089 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006090 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 QualType Canonical = readType(*Loc.F, Record, Idx);
6092 if (!Canonical.isNull())
6093 Canonical = Context.getCanonicalType(Canonical);
6094 return Context.getTypedefType(Decl, Canonical);
6095 }
6096
6097 case TYPE_TYPEOF_EXPR:
6098 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6099
6100 case TYPE_TYPEOF: {
6101 if (Record.size() != 1) {
6102 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006103 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006104 }
6105 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6106 return Context.getTypeOfType(UnderlyingType);
6107 }
6108
6109 case TYPE_DECLTYPE: {
6110 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6111 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6112 }
6113
6114 case TYPE_UNARY_TRANSFORM: {
6115 QualType BaseType = readType(*Loc.F, Record, Idx);
6116 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006117 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6119 }
6120
Richard Smith74aeef52013-04-26 16:15:35 +00006121 case TYPE_AUTO: {
6122 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006123 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006124 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006125 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006126 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006127
Richard Smith600b5262017-01-26 20:40:47 +00006128 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6129 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6130 QualType Deduced = readType(*Loc.F, Record, Idx);
6131 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6132 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6133 IsDependent);
6134 }
6135
Guy Benyei11169dd2012-12-18 14:30:41 +00006136 case TYPE_RECORD: {
6137 if (Record.size() != 2) {
6138 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006139 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006140 }
6141 unsigned Idx = 0;
6142 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006143 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6145 QualType T = Context.getRecordType(RD);
6146 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6147 return T;
6148 }
6149
6150 case TYPE_ENUM: {
6151 if (Record.size() != 2) {
6152 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006153 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 }
6155 unsigned Idx = 0;
6156 bool IsDependent = Record[Idx++];
6157 QualType T
6158 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6159 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6160 return T;
6161 }
6162
6163 case TYPE_ATTRIBUTED: {
6164 if (Record.size() != 3) {
6165 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006166 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006167 }
6168 QualType modifiedType = readType(*Loc.F, Record, Idx);
6169 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006170 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 return Context.getAttributedType(kind, modifiedType, equivalentType);
6172 }
6173
6174 case TYPE_PAREN: {
6175 if (Record.size() != 1) {
6176 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006177 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006178 }
6179 QualType InnerType = readType(*Loc.F, Record, Idx);
6180 return Context.getParenType(InnerType);
6181 }
6182
6183 case TYPE_PACK_EXPANSION: {
6184 if (Record.size() != 2) {
6185 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006186 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 }
6188 QualType Pattern = readType(*Loc.F, Record, Idx);
6189 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006190 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006191 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006192 if (Record[1])
6193 NumExpansions = Record[1] - 1;
6194 return Context.getPackExpansionType(Pattern, NumExpansions);
6195 }
6196
6197 case TYPE_ELABORATED: {
6198 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006199 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006200 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6201 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006202 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6203 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006204 }
6205
6206 case TYPE_OBJC_INTERFACE: {
6207 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006208 ObjCInterfaceDecl *ItfD
6209 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006210 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6211 }
6212
Manman Rene6be26c2016-09-13 17:25:08 +00006213 case TYPE_OBJC_TYPE_PARAM: {
6214 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006215 ObjCTypeParamDecl *Decl
6216 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006217 unsigned NumProtos = Record[Idx++];
6218 SmallVector<ObjCProtocolDecl*, 4> Protos;
6219 for (unsigned I = 0; I != NumProtos; ++I)
6220 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6221 return Context.getObjCTypeParamType(Decl, Protos);
6222 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006223
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 case TYPE_OBJC_OBJECT: {
6225 unsigned Idx = 0;
6226 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006227 unsigned NumTypeArgs = Record[Idx++];
6228 SmallVector<QualType, 4> TypeArgs;
6229 for (unsigned I = 0; I != NumTypeArgs; ++I)
6230 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006231 unsigned NumProtos = Record[Idx++];
6232 SmallVector<ObjCProtocolDecl*, 4> Protos;
6233 for (unsigned I = 0; I != NumProtos; ++I)
6234 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006235 bool IsKindOf = Record[Idx++];
6236 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 }
6238
6239 case TYPE_OBJC_OBJECT_POINTER: {
6240 unsigned Idx = 0;
6241 QualType Pointee = readType(*Loc.F, Record, Idx);
6242 return Context.getObjCObjectPointerType(Pointee);
6243 }
6244
6245 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6246 unsigned Idx = 0;
6247 QualType Parm = readType(*Loc.F, Record, Idx);
6248 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006249 return Context.getSubstTemplateTypeParmType(
6250 cast<TemplateTypeParmType>(Parm),
6251 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 }
6253
6254 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6255 unsigned Idx = 0;
6256 QualType Parm = readType(*Loc.F, Record, Idx);
6257 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6258 return Context.getSubstTemplateTypeParmPackType(
6259 cast<TemplateTypeParmType>(Parm),
6260 ArgPack);
6261 }
6262
6263 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006264 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006265 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6266 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6267 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006268 const Type *T = nullptr;
6269 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6270 if (const Type *Existing = DI->getTypeForDecl()) {
6271 T = Existing;
6272 break;
6273 }
6274 }
6275 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006276 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006277 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6278 DI->setTypeForDecl(T);
6279 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006280 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006281 }
6282
6283 case TYPE_TEMPLATE_TYPE_PARM: {
6284 unsigned Idx = 0;
6285 unsigned Depth = Record[Idx++];
6286 unsigned Index = Record[Idx++];
6287 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006288 TemplateTypeParmDecl *D
6289 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006290 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6291 }
6292
6293 case TYPE_DEPENDENT_NAME: {
6294 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006295 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006297 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006298 QualType Canon = readType(*Loc.F, Record, Idx);
6299 if (!Canon.isNull())
6300 Canon = Context.getCanonicalType(Canon);
6301 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6302 }
6303
6304 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6305 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006306 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006307 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006308 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006309 unsigned NumArgs = Record[Idx++];
6310 SmallVector<TemplateArgument, 8> Args;
6311 Args.reserve(NumArgs);
6312 while (NumArgs--)
6313 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6314 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006315 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006316 }
6317
6318 case TYPE_DEPENDENT_SIZED_ARRAY: {
6319 unsigned Idx = 0;
6320
6321 // ArrayType
6322 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006323 ArrayType::ArraySizeModifier ASM
6324 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006325 unsigned IndexTypeQuals = Record[Idx++];
6326
6327 // DependentSizedArrayType
6328 Expr *NumElts = ReadExpr(*Loc.F);
6329 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6330
6331 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6332 IndexTypeQuals, Brackets);
6333 }
6334
6335 case TYPE_TEMPLATE_SPECIALIZATION: {
6336 unsigned Idx = 0;
6337 bool IsDependent = Record[Idx++];
6338 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6339 SmallVector<TemplateArgument, 8> Args;
6340 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6341 QualType Underlying = readType(*Loc.F, Record, Idx);
6342 QualType T;
6343 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006344 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006345 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006346 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006347 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6348 return T;
6349 }
6350
6351 case TYPE_ATOMIC: {
6352 if (Record.size() != 1) {
6353 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006354 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006355 }
6356 QualType ValueType = readType(*Loc.F, Record, Idx);
6357 return Context.getAtomicType(ValueType);
6358 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006359
Joey Goulye3c85de2016-12-01 11:30:49 +00006360 case TYPE_PIPE: {
6361 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006362 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006363 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006364 }
6365
6366 // Reading the pipe element type.
6367 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006368 unsigned ReadOnly = Record[1];
6369 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006370 }
6371
Erich Keanef702b022018-07-13 19:46:04 +00006372 case TYPE_DEPENDENT_SIZED_VECTOR: {
6373 unsigned Idx = 0;
6374 QualType ElementType = readType(*Loc.F, Record, Idx);
6375 Expr *SizeExpr = ReadExpr(*Loc.F);
6376 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6377 unsigned VecKind = Record[Idx];
6378
6379 return Context.getDependentVectorType(ElementType, SizeExpr, AttrLoc,
6380 (VectorType::VectorKind)VecKind);
6381 }
6382
Alex Lorenz00aee432017-03-22 10:04:48 +00006383 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6384 unsigned Idx = 0;
6385
6386 // DependentSizedExtVectorType
6387 QualType ElementType = readType(*Loc.F, Record, Idx);
6388 Expr *SizeExpr = ReadExpr(*Loc.F);
6389 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6390
6391 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6392 AttrLoc);
6393 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006394
6395 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6396 unsigned Idx = 0;
6397
6398 // DependentAddressSpaceType
6399 QualType PointeeType = readType(*Loc.F, Record, Idx);
6400 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6401 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6402
6403 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6404 AttrLoc);
6405 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006406 }
6407 llvm_unreachable("Invalid TypeCode!");
6408}
6409
Richard Smith564417a2014-03-20 21:47:22 +00006410void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6411 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006412 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006413 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006414 ExceptionSpecificationType EST =
6415 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006416 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006417 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006418 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006419 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006420 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006421 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006422 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006423 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006424 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6425 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006426 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006427 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006428 }
6429}
6430
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006431namespace clang {
6432
6433class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006434 ModuleFile *F;
6435 ASTReader *Reader;
6436 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006437 unsigned &Idx;
6438
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006439 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006440 return Reader->ReadSourceLocation(*F, Record, Idx);
6441 }
6442
6443 TypeSourceInfo *GetTypeSourceInfo() {
6444 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6445 }
6446
6447 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6448 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006449 }
6450
Richard Smithe43e2b32018-08-20 21:47:29 +00006451 Attr *ReadAttr() {
6452 return Reader->ReadAttr(*F, Record, Idx);
6453 }
6454
Guy Benyei11169dd2012-12-18 14:30:41 +00006455public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006456 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006458 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006459
6460 // We want compile-time assurance that we've enumerated all of
6461 // these, so unfortunately we have to declare them first, then
6462 // define them out-of-line.
6463#define ABSTRACT_TYPELOC(CLASS, PARENT)
6464#define TYPELOC(CLASS, PARENT) \
6465 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6466#include "clang/AST/TypeLocNodes.def"
6467
6468 void VisitFunctionTypeLoc(FunctionTypeLoc);
6469 void VisitArrayTypeLoc(ArrayTypeLoc);
6470};
6471
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006472} // namespace clang
6473
Guy Benyei11169dd2012-12-18 14:30:41 +00006474void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6475 // nothing to do
6476}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006477
Guy Benyei11169dd2012-12-18 14:30:41 +00006478void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006479 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006480 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006481 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6482 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6483 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6484 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006485 }
6486}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006487
Guy Benyei11169dd2012-12-18 14:30:41 +00006488void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006489 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006490}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006491
Guy Benyei11169dd2012-12-18 14:30:41 +00006492void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006493 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006494}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006495
Reid Kleckner8a365022013-06-24 17:51:48 +00006496void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6497 // nothing to do
6498}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006499
Reid Kleckner0503a872013-12-05 01:23:43 +00006500void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6501 // nothing to do
6502}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006503
Guy Benyei11169dd2012-12-18 14:30:41 +00006504void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006505 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006506}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006507
Guy Benyei11169dd2012-12-18 14:30:41 +00006508void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006509 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006510}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006511
Guy Benyei11169dd2012-12-18 14:30:41 +00006512void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006513 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006514}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006515
Guy Benyei11169dd2012-12-18 14:30:41 +00006516void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006517 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006518 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006519}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006520
Guy Benyei11169dd2012-12-18 14:30:41 +00006521void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006522 TL.setLBracketLoc(ReadSourceLocation());
6523 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006524 if (Record[Idx++])
6525 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006526 else
Craig Toppera13603a2014-05-22 05:54:18 +00006527 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006528}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006529
Guy Benyei11169dd2012-12-18 14:30:41 +00006530void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6531 VisitArrayTypeLoc(TL);
6532}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006533
Guy Benyei11169dd2012-12-18 14:30:41 +00006534void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6535 VisitArrayTypeLoc(TL);
6536}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006537
Guy Benyei11169dd2012-12-18 14:30:41 +00006538void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6539 VisitArrayTypeLoc(TL);
6540}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006541
Guy Benyei11169dd2012-12-18 14:30:41 +00006542void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6543 DependentSizedArrayTypeLoc TL) {
6544 VisitArrayTypeLoc(TL);
6545}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006546
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006547void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6548 DependentAddressSpaceTypeLoc TL) {
6549
6550 TL.setAttrNameLoc(ReadSourceLocation());
6551 SourceRange range;
6552 range.setBegin(ReadSourceLocation());
6553 range.setEnd(ReadSourceLocation());
6554 TL.setAttrOperandParensRange(range);
6555 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6556}
6557
Guy Benyei11169dd2012-12-18 14:30:41 +00006558void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6559 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006560 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006561}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006562
Guy Benyei11169dd2012-12-18 14:30:41 +00006563void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006564 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006565}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006566
Erich Keanef702b022018-07-13 19:46:04 +00006567void TypeLocReader::VisitDependentVectorTypeLoc(
6568 DependentVectorTypeLoc TL) {
6569 TL.setNameLoc(ReadSourceLocation());
6570}
6571
Guy Benyei11169dd2012-12-18 14:30:41 +00006572void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006573 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006574}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006575
Guy Benyei11169dd2012-12-18 14:30:41 +00006576void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006577 TL.setLocalRangeBegin(ReadSourceLocation());
6578 TL.setLParenLoc(ReadSourceLocation());
6579 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006580 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6581 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006582 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006583 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006584 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006585 }
6586}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006587
Guy Benyei11169dd2012-12-18 14:30:41 +00006588void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6589 VisitFunctionTypeLoc(TL);
6590}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006591
Guy Benyei11169dd2012-12-18 14:30:41 +00006592void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6593 VisitFunctionTypeLoc(TL);
6594}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006595
Guy Benyei11169dd2012-12-18 14:30:41 +00006596void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006597 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006598}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006599
Guy Benyei11169dd2012-12-18 14:30:41 +00006600void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006601 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006602}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006603
Guy Benyei11169dd2012-12-18 14:30:41 +00006604void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006605 TL.setTypeofLoc(ReadSourceLocation());
6606 TL.setLParenLoc(ReadSourceLocation());
6607 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006608}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006609
Guy Benyei11169dd2012-12-18 14:30:41 +00006610void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006611 TL.setTypeofLoc(ReadSourceLocation());
6612 TL.setLParenLoc(ReadSourceLocation());
6613 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006614 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006615}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006616
Guy Benyei11169dd2012-12-18 14:30:41 +00006617void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006618 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006619}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006620
Guy Benyei11169dd2012-12-18 14:30:41 +00006621void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006622 TL.setKWLoc(ReadSourceLocation());
6623 TL.setLParenLoc(ReadSourceLocation());
6624 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006625 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006626}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006627
Guy Benyei11169dd2012-12-18 14:30:41 +00006628void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006629 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006630}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006631
Richard Smith600b5262017-01-26 20:40:47 +00006632void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6633 DeducedTemplateSpecializationTypeLoc TL) {
6634 TL.setTemplateNameLoc(ReadSourceLocation());
6635}
6636
Guy Benyei11169dd2012-12-18 14:30:41 +00006637void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006638 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006639}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006640
Guy Benyei11169dd2012-12-18 14:30:41 +00006641void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006642 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006643}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006644
Guy Benyei11169dd2012-12-18 14:30:41 +00006645void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
Richard Smithe43e2b32018-08-20 21:47:29 +00006646 TL.setAttr(ReadAttr());
Guy Benyei11169dd2012-12-18 14:30:41 +00006647}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006648
Guy Benyei11169dd2012-12-18 14:30:41 +00006649void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006650 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006651}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6654 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006655 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006656}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006657
Guy Benyei11169dd2012-12-18 14:30:41 +00006658void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6659 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006660 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006661}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006662
Guy Benyei11169dd2012-12-18 14:30:41 +00006663void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6664 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006665 TL.setTemplateKeywordLoc(ReadSourceLocation());
6666 TL.setTemplateNameLoc(ReadSourceLocation());
6667 TL.setLAngleLoc(ReadSourceLocation());
6668 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006669 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006670 TL.setArgLocInfo(
6671 i,
6672 Reader->GetTemplateArgumentLocInfo(
6673 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006674}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006675
Guy Benyei11169dd2012-12-18 14:30:41 +00006676void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006677 TL.setLParenLoc(ReadSourceLocation());
6678 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006679}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006680
Guy Benyei11169dd2012-12-18 14:30:41 +00006681void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006682 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006683 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006684}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006685
Guy Benyei11169dd2012-12-18 14:30:41 +00006686void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006687 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006688}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006689
Guy Benyei11169dd2012-12-18 14:30:41 +00006690void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006691 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006692 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006693 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006694}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006695
Guy Benyei11169dd2012-12-18 14:30:41 +00006696void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6697 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006698 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006699 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006700 TL.setTemplateKeywordLoc(ReadSourceLocation());
6701 TL.setTemplateNameLoc(ReadSourceLocation());
6702 TL.setLAngleLoc(ReadSourceLocation());
6703 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006704 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006705 TL.setArgLocInfo(
6706 I,
6707 Reader->GetTemplateArgumentLocInfo(
6708 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006709}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006710
Guy Benyei11169dd2012-12-18 14:30:41 +00006711void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006712 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006713}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006714
Guy Benyei11169dd2012-12-18 14:30:41 +00006715void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006716 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006717}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006718
Manman Rene6be26c2016-09-13 17:25:08 +00006719void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6720 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006721 TL.setProtocolLAngleLoc(ReadSourceLocation());
6722 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006723 }
6724 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006725 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006726}
6727
Guy Benyei11169dd2012-12-18 14:30:41 +00006728void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006729 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006730 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6731 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006732 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006733 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006734 TL.setProtocolLAngleLoc(ReadSourceLocation());
6735 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006737 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006738}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006739
Guy Benyei11169dd2012-12-18 14:30:41 +00006740void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006741 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006742}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006743
Guy Benyei11169dd2012-12-18 14:30:41 +00006744void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006745 TL.setKWLoc(ReadSourceLocation());
6746 TL.setLParenLoc(ReadSourceLocation());
6747 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006748}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006749
Xiuli Pan9c14e282016-01-09 12:53:17 +00006750void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006751 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006752}
Guy Benyei11169dd2012-12-18 14:30:41 +00006753
Richard Smithc23d7342018-06-29 20:46:25 +00006754void ASTReader::ReadTypeLoc(ModuleFile &F, const ASTReader::RecordData &Record,
6755 unsigned &Idx, TypeLoc TL) {
6756 TypeLocReader TLR(F, *this, Record, Idx);
6757 for (; !TL.isNull(); TL = TL.getNextTypeLoc())
6758 TLR.Visit(TL);
6759}
6760
David L. Jonesbe1557a2016-12-21 00:17:49 +00006761TypeSourceInfo *
6762ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6763 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 QualType InfoTy = readType(F, Record, Idx);
6765 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006766 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006767
6768 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
Richard Smithc23d7342018-06-29 20:46:25 +00006769 ReadTypeLoc(F, Record, Idx, TInfo->getTypeLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006770 return TInfo;
6771}
6772
6773QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006774 assert(ContextObj && "reading type with no AST context");
6775 ASTContext &Context = *ContextObj;
6776
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 unsigned FastQuals = ID & Qualifiers::FastMask;
6778 unsigned Index = ID >> Qualifiers::FastWidth;
6779
6780 if (Index < NUM_PREDEF_TYPE_IDS) {
6781 QualType T;
6782 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006783 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006784 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006785 case PREDEF_TYPE_VOID_ID:
6786 T = Context.VoidTy;
6787 break;
6788 case PREDEF_TYPE_BOOL_ID:
6789 T = Context.BoolTy;
6790 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006791 case PREDEF_TYPE_CHAR_U_ID:
6792 case PREDEF_TYPE_CHAR_S_ID:
6793 // FIXME: Check that the signedness of CharTy is correct!
6794 T = Context.CharTy;
6795 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006796 case PREDEF_TYPE_UCHAR_ID:
6797 T = Context.UnsignedCharTy;
6798 break;
6799 case PREDEF_TYPE_USHORT_ID:
6800 T = Context.UnsignedShortTy;
6801 break;
6802 case PREDEF_TYPE_UINT_ID:
6803 T = Context.UnsignedIntTy;
6804 break;
6805 case PREDEF_TYPE_ULONG_ID:
6806 T = Context.UnsignedLongTy;
6807 break;
6808 case PREDEF_TYPE_ULONGLONG_ID:
6809 T = Context.UnsignedLongLongTy;
6810 break;
6811 case PREDEF_TYPE_UINT128_ID:
6812 T = Context.UnsignedInt128Ty;
6813 break;
6814 case PREDEF_TYPE_SCHAR_ID:
6815 T = Context.SignedCharTy;
6816 break;
6817 case PREDEF_TYPE_WCHAR_ID:
6818 T = Context.WCharTy;
6819 break;
6820 case PREDEF_TYPE_SHORT_ID:
6821 T = Context.ShortTy;
6822 break;
6823 case PREDEF_TYPE_INT_ID:
6824 T = Context.IntTy;
6825 break;
6826 case PREDEF_TYPE_LONG_ID:
6827 T = Context.LongTy;
6828 break;
6829 case PREDEF_TYPE_LONGLONG_ID:
6830 T = Context.LongLongTy;
6831 break;
6832 case PREDEF_TYPE_INT128_ID:
6833 T = Context.Int128Ty;
6834 break;
6835 case PREDEF_TYPE_HALF_ID:
6836 T = Context.HalfTy;
6837 break;
6838 case PREDEF_TYPE_FLOAT_ID:
6839 T = Context.FloatTy;
6840 break;
6841 case PREDEF_TYPE_DOUBLE_ID:
6842 T = Context.DoubleTy;
6843 break;
6844 case PREDEF_TYPE_LONGDOUBLE_ID:
6845 T = Context.LongDoubleTy;
6846 break;
Leonard Chanf921d852018-06-04 16:07:52 +00006847 case PREDEF_TYPE_SHORT_ACCUM_ID:
6848 T = Context.ShortAccumTy;
6849 break;
6850 case PREDEF_TYPE_ACCUM_ID:
6851 T = Context.AccumTy;
6852 break;
6853 case PREDEF_TYPE_LONG_ACCUM_ID:
6854 T = Context.LongAccumTy;
6855 break;
6856 case PREDEF_TYPE_USHORT_ACCUM_ID:
6857 T = Context.UnsignedShortAccumTy;
6858 break;
6859 case PREDEF_TYPE_UACCUM_ID:
6860 T = Context.UnsignedAccumTy;
6861 break;
6862 case PREDEF_TYPE_ULONG_ACCUM_ID:
6863 T = Context.UnsignedLongAccumTy;
6864 break;
Leonard Chanab80f3c2018-06-14 14:53:51 +00006865 case PREDEF_TYPE_SHORT_FRACT_ID:
6866 T = Context.ShortFractTy;
6867 break;
6868 case PREDEF_TYPE_FRACT_ID:
6869 T = Context.FractTy;
6870 break;
6871 case PREDEF_TYPE_LONG_FRACT_ID:
6872 T = Context.LongFractTy;
6873 break;
6874 case PREDEF_TYPE_USHORT_FRACT_ID:
6875 T = Context.UnsignedShortFractTy;
6876 break;
6877 case PREDEF_TYPE_UFRACT_ID:
6878 T = Context.UnsignedFractTy;
6879 break;
6880 case PREDEF_TYPE_ULONG_FRACT_ID:
6881 T = Context.UnsignedLongFractTy;
6882 break;
6883 case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
6884 T = Context.SatShortAccumTy;
6885 break;
6886 case PREDEF_TYPE_SAT_ACCUM_ID:
6887 T = Context.SatAccumTy;
6888 break;
6889 case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
6890 T = Context.SatLongAccumTy;
6891 break;
6892 case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
6893 T = Context.SatUnsignedShortAccumTy;
6894 break;
6895 case PREDEF_TYPE_SAT_UACCUM_ID:
6896 T = Context.SatUnsignedAccumTy;
6897 break;
6898 case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
6899 T = Context.SatUnsignedLongAccumTy;
6900 break;
6901 case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
6902 T = Context.SatShortFractTy;
6903 break;
6904 case PREDEF_TYPE_SAT_FRACT_ID:
6905 T = Context.SatFractTy;
6906 break;
6907 case PREDEF_TYPE_SAT_LONG_FRACT_ID:
6908 T = Context.SatLongFractTy;
6909 break;
6910 case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
6911 T = Context.SatUnsignedShortFractTy;
6912 break;
6913 case PREDEF_TYPE_SAT_UFRACT_ID:
6914 T = Context.SatUnsignedFractTy;
6915 break;
6916 case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
6917 T = Context.SatUnsignedLongFractTy;
6918 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006919 case PREDEF_TYPE_FLOAT16_ID:
6920 T = Context.Float16Ty;
6921 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006922 case PREDEF_TYPE_FLOAT128_ID:
6923 T = Context.Float128Ty;
6924 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006925 case PREDEF_TYPE_OVERLOAD_ID:
6926 T = Context.OverloadTy;
6927 break;
6928 case PREDEF_TYPE_BOUND_MEMBER:
6929 T = Context.BoundMemberTy;
6930 break;
6931 case PREDEF_TYPE_PSEUDO_OBJECT:
6932 T = Context.PseudoObjectTy;
6933 break;
6934 case PREDEF_TYPE_DEPENDENT_ID:
6935 T = Context.DependentTy;
6936 break;
6937 case PREDEF_TYPE_UNKNOWN_ANY:
6938 T = Context.UnknownAnyTy;
6939 break;
6940 case PREDEF_TYPE_NULLPTR_ID:
6941 T = Context.NullPtrTy;
6942 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006943 case PREDEF_TYPE_CHAR8_ID:
6944 T = Context.Char8Ty;
6945 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006946 case PREDEF_TYPE_CHAR16_ID:
6947 T = Context.Char16Ty;
6948 break;
6949 case PREDEF_TYPE_CHAR32_ID:
6950 T = Context.Char32Ty;
6951 break;
6952 case PREDEF_TYPE_OBJC_ID:
6953 T = Context.ObjCBuiltinIdTy;
6954 break;
6955 case PREDEF_TYPE_OBJC_CLASS:
6956 T = Context.ObjCBuiltinClassTy;
6957 break;
6958 case PREDEF_TYPE_OBJC_SEL:
6959 T = Context.ObjCBuiltinSelTy;
6960 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006961#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6962 case PREDEF_TYPE_##Id##_ID: \
6963 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006964 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006965#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006966 case PREDEF_TYPE_SAMPLER_ID:
6967 T = Context.OCLSamplerTy;
6968 break;
6969 case PREDEF_TYPE_EVENT_ID:
6970 T = Context.OCLEventTy;
6971 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006972 case PREDEF_TYPE_CLK_EVENT_ID:
6973 T = Context.OCLClkEventTy;
6974 break;
6975 case PREDEF_TYPE_QUEUE_ID:
6976 T = Context.OCLQueueTy;
6977 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006978 case PREDEF_TYPE_RESERVE_ID_ID:
6979 T = Context.OCLReserveIDTy;
6980 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006981 case PREDEF_TYPE_AUTO_DEDUCT:
6982 T = Context.getAutoDeductType();
6983 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006984 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6985 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006986 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006987 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6988 T = Context.ARCUnbridgedCastTy;
6989 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006990 case PREDEF_TYPE_BUILTIN_FN:
6991 T = Context.BuiltinFnTy;
6992 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006993 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6994 T = Context.OMPArraySectionTy;
6995 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006996 }
6997
6998 assert(!T.isNull() && "Unknown predefined type");
6999 return T.withFastQualifiers(FastQuals);
7000 }
7001
7002 Index -= NUM_PREDEF_TYPE_IDS;
7003 assert(Index < TypesLoaded.size() && "Type index out-of-range");
7004 if (TypesLoaded[Index].isNull()) {
7005 TypesLoaded[Index] = readTypeRecord(Index);
7006 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00007007 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00007008
7009 TypesLoaded[Index]->setFromAST();
7010 if (DeserializationListener)
7011 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
7012 TypesLoaded[Index]);
7013 }
7014
7015 return TypesLoaded[Index].withFastQualifiers(FastQuals);
7016}
7017
7018QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
7019 return GetType(getGlobalTypeID(F, LocalID));
7020}
7021
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007022serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00007023ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
7024 unsigned FastQuals = LocalID & Qualifiers::FastMask;
7025 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007026
Guy Benyei11169dd2012-12-18 14:30:41 +00007027 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
7028 return LocalID;
7029
Richard Smith37a93df2017-02-18 00:32:02 +00007030 if (!F.ModuleOffsetMap.empty())
7031 ReadModuleOffsetMap(F);
7032
Guy Benyei11169dd2012-12-18 14:30:41 +00007033 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7034 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
7035 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007036
Guy Benyei11169dd2012-12-18 14:30:41 +00007037 unsigned GlobalIndex = LocalIndex + I->second;
7038 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
7039}
7040
7041TemplateArgumentLocInfo
7042ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
7043 TemplateArgument::ArgKind Kind,
7044 const RecordData &Record,
7045 unsigned &Index) {
7046 switch (Kind) {
7047 case TemplateArgument::Expression:
7048 return ReadExpr(F);
7049 case TemplateArgument::Type:
7050 return GetTypeSourceInfo(F, Record, Index);
7051 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007052 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 Index);
7054 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7055 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
7056 SourceLocation());
7057 }
7058 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007059 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00007060 Index);
7061 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
7062 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007063 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00007064 EllipsisLoc);
7065 }
7066 case TemplateArgument::Null:
7067 case TemplateArgument::Integral:
7068 case TemplateArgument::Declaration:
7069 case TemplateArgument::NullPtr:
7070 case TemplateArgument::Pack:
7071 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00007072 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 }
7074 llvm_unreachable("unexpected template argument loc");
7075}
7076
7077TemplateArgumentLoc
7078ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7079 const RecordData &Record, unsigned &Index) {
7080 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7081
7082 if (Arg.getKind() == TemplateArgument::Expression) {
7083 if (Record[Index++]) // bool InfoHasSameExpr.
7084 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7085 }
7086 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7087 Record, Index));
7088}
7089
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007090const ASTTemplateArgumentListInfo*
7091ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7092 const RecordData &Record,
7093 unsigned &Index) {
7094 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7095 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7096 unsigned NumArgsAsWritten = Record[Index++];
7097 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7098 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7099 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7100 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7101}
7102
Guy Benyei11169dd2012-12-18 14:30:41 +00007103Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7104 return GetDecl(ID);
7105}
7106
Richard Smith053f6c62014-05-16 23:01:30 +00007107void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007108 if (NumCurrentElementsDeserializing) {
7109 // We arrange to not care about the complete redeclaration chain while we're
7110 // deserializing. Just remember that the AST has marked this one as complete
7111 // but that it's not actually complete yet, so we know we still need to
7112 // complete it later.
7113 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7114 return;
7115 }
7116
Richard Smith053f6c62014-05-16 23:01:30 +00007117 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7118
Richard Smith053f6c62014-05-16 23:01:30 +00007119 // If this is a named declaration, complete it by looking it up
7120 // within its context.
7121 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007122 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007123 // all mergeable entities within it.
7124 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7125 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7126 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007127 if (!getContext().getLangOpts().CPlusPlus &&
7128 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007129 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007130 // the identifier instead. (For C++ modules, we don't store decls
7131 // in the serialized identifier table, so we do the lookup in the TU.)
7132 auto *II = Name.getAsIdentifierInfo();
7133 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007134 if (II->isOutOfDate())
7135 updateOutOfDateIdentifier(*II);
7136 } else
7137 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007138 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007139 // Find all declarations of this kind from the relevant context.
7140 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7141 auto *DC = cast<DeclContext>(DCDecl);
7142 SmallVector<Decl*, 8> Decls;
7143 FindExternalLexicalDecls(
7144 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7145 }
Richard Smith053f6c62014-05-16 23:01:30 +00007146 }
7147 }
Richard Smith50895422015-01-31 03:04:55 +00007148
7149 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7150 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7151 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7152 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7153 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7154 if (auto *Template = FD->getPrimaryTemplate())
7155 Template->LoadLazySpecializations();
7156 }
Richard Smith053f6c62014-05-16 23:01:30 +00007157}
7158
Richard Smithc2bb8182015-03-24 06:36:48 +00007159CXXCtorInitializer **
7160ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7161 RecordLocation Loc = getLocalBitOffset(Offset);
7162 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7163 SavedStreamPosition SavedPosition(Cursor);
7164 Cursor.JumpToBit(Loc.Offset);
7165 ReadingKindTracker ReadingKind(Read_Decl, *this);
7166
7167 RecordData Record;
7168 unsigned Code = Cursor.ReadCode();
7169 unsigned RecCode = Cursor.readRecord(Code, Record);
7170 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7171 Error("malformed AST file: missing C++ ctor initializers");
7172 return nullptr;
7173 }
7174
7175 unsigned Idx = 0;
7176 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7177}
7178
Guy Benyei11169dd2012-12-18 14:30:41 +00007179CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007180 assert(ContextObj && "reading base specifiers with no AST context");
7181 ASTContext &Context = *ContextObj;
7182
Guy Benyei11169dd2012-12-18 14:30:41 +00007183 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007184 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007185 SavedStreamPosition SavedPosition(Cursor);
7186 Cursor.JumpToBit(Loc.Offset);
7187 ReadingKindTracker ReadingKind(Read_Decl, *this);
7188 RecordData Record;
7189 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007190 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007191 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007192 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007193 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 }
7195
7196 unsigned Idx = 0;
7197 unsigned NumBases = Record[Idx++];
7198 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007199 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007200 for (unsigned I = 0; I != NumBases; ++I)
7201 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7202 return Bases;
7203}
7204
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007205serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007206ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7207 if (LocalID < NUM_PREDEF_DECL_IDS)
7208 return LocalID;
7209
Richard Smith37a93df2017-02-18 00:32:02 +00007210 if (!F.ModuleOffsetMap.empty())
7211 ReadModuleOffsetMap(F);
7212
Guy Benyei11169dd2012-12-18 14:30:41 +00007213 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7214 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7215 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007216
Guy Benyei11169dd2012-12-18 14:30:41 +00007217 return LocalID + I->second;
7218}
7219
7220bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7221 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007222 // Predefined decls aren't from any module.
7223 if (ID < NUM_PREDEF_DECL_IDS)
7224 return false;
7225
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007226 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007227 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007228}
7229
Douglas Gregor9f782892013-01-21 15:25:38 +00007230ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007231 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007232 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007233 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7234 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7235 return I->second;
7236}
7237
7238SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7239 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007240 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007241
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7243
7244 if (Index > DeclsLoaded.size()) {
7245 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007246 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007248
Guy Benyei11169dd2012-12-18 14:30:41 +00007249 if (Decl *D = DeclsLoaded[Index])
7250 return D->getLocation();
7251
Richard Smithcb34bd32016-03-27 07:28:06 +00007252 SourceLocation Loc;
7253 DeclCursorForID(ID, Loc);
7254 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007255}
7256
Richard Smithfe620d22015-03-05 23:24:12 +00007257static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7258 switch (ID) {
7259 case PREDEF_DECL_NULL_ID:
7260 return nullptr;
7261
7262 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7263 return Context.getTranslationUnitDecl();
7264
7265 case PREDEF_DECL_OBJC_ID_ID:
7266 return Context.getObjCIdDecl();
7267
7268 case PREDEF_DECL_OBJC_SEL_ID:
7269 return Context.getObjCSelDecl();
7270
7271 case PREDEF_DECL_OBJC_CLASS_ID:
7272 return Context.getObjCClassDecl();
7273
7274 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7275 return Context.getObjCProtocolDecl();
7276
7277 case PREDEF_DECL_INT_128_ID:
7278 return Context.getInt128Decl();
7279
7280 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7281 return Context.getUInt128Decl();
7282
7283 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7284 return Context.getObjCInstanceTypeDecl();
7285
7286 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7287 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007288
Richard Smith9b88a4c2015-07-27 05:40:23 +00007289 case PREDEF_DECL_VA_LIST_TAG:
7290 return Context.getVaListTagDecl();
7291
Charles Davisc7d5c942015-09-17 20:55:33 +00007292 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7293 return Context.getBuiltinMSVaListDecl();
7294
Richard Smithf19e1272015-03-07 00:04:49 +00007295 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7296 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007297
7298 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7299 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007300
7301 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7302 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007303
7304 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7305 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007306
7307 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7308 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007309 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007310 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007311}
7312
Richard Smithcd45dbc2014-04-19 03:48:30 +00007313Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007314 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007315 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007316 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007317 if (D) {
7318 // Track that we have merged the declaration with ID \p ID into the
7319 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007320 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007321 if (Merged.empty())
7322 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 }
Richard Smithfe620d22015-03-05 23:24:12 +00007324 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007326
Guy Benyei11169dd2012-12-18 14:30:41 +00007327 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7328
7329 if (Index >= DeclsLoaded.size()) {
7330 assert(0 && "declaration ID out-of-range for AST file");
7331 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007332 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007334
7335 return DeclsLoaded[Index];
7336}
7337
7338Decl *ASTReader::GetDecl(DeclID ID) {
7339 if (ID < NUM_PREDEF_DECL_IDS)
7340 return GetExistingDecl(ID);
7341
7342 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7343
7344 if (Index >= DeclsLoaded.size()) {
7345 assert(0 && "declaration ID out-of-range for AST file");
7346 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007347 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007348 }
7349
Guy Benyei11169dd2012-12-18 14:30:41 +00007350 if (!DeclsLoaded[Index]) {
7351 ReadDeclRecord(ID);
7352 if (DeserializationListener)
7353 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7354 }
7355
7356 return DeclsLoaded[Index];
7357}
7358
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007359DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007360 DeclID GlobalID) {
7361 if (GlobalID < NUM_PREDEF_DECL_IDS)
7362 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007363
Guy Benyei11169dd2012-12-18 14:30:41 +00007364 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7365 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7366 ModuleFile *Owner = I->second;
7367
7368 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7369 = M.GlobalToLocalDeclIDs.find(Owner);
7370 if (Pos == M.GlobalToLocalDeclIDs.end())
7371 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007372
Guy Benyei11169dd2012-12-18 14:30:41 +00007373 return GlobalID - Owner->BaseDeclID + Pos->second;
7374}
7375
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007376serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007377 const RecordData &Record,
7378 unsigned &Idx) {
7379 if (Idx >= Record.size()) {
7380 Error("Corrupted AST file");
7381 return 0;
7382 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007383
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 return getGlobalDeclID(F, Record[Idx++]);
7385}
7386
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007387/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007388///
7389/// This operation will read a new statement from the external
7390/// source each time it is called, and is meant to be used via a
7391/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7392Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7393 // Switch case IDs are per Decl.
7394 ClearSwitchCaseIDs();
7395
7396 // Offset here is a global offset across the entire chain.
7397 RecordLocation Loc = getLocalBitOffset(Offset);
7398 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007399 assert(NumCurrentElementsDeserializing == 0 &&
7400 "should not be called while already deserializing");
7401 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007402 return ReadStmtFromStream(*Loc.F);
7403}
7404
Richard Smith3cb15722015-08-05 22:41:45 +00007405void ASTReader::FindExternalLexicalDecls(
7406 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7407 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007408 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7409
Richard Smith9ccdd932015-08-06 22:14:12 +00007410 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007411 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7412 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7413 auto K = (Decl::Kind)+LexicalDecls[I];
7414 if (!IsKindWeWant(K))
7415 continue;
7416
7417 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7418
7419 // Don't add predefined declarations to the lexical context more
7420 // than once.
7421 if (ID < NUM_PREDEF_DECL_IDS) {
7422 if (PredefsVisited[ID])
7423 continue;
7424
7425 PredefsVisited[ID] = true;
7426 }
7427
7428 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007429 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007430 if (!DC->isDeclInLexicalTraversal(D))
7431 Decls.push_back(D);
7432 }
7433 }
7434 };
7435
7436 if (isa<TranslationUnitDecl>(DC)) {
7437 for (auto Lexical : TULexicalDecls)
7438 Visit(Lexical.first, Lexical.second);
7439 } else {
7440 auto I = LexicalDecls.find(DC);
7441 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007442 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007443 }
7444
Guy Benyei11169dd2012-12-18 14:30:41 +00007445 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007446}
7447
7448namespace {
7449
7450class DeclIDComp {
7451 ASTReader &Reader;
7452 ModuleFile &Mod;
7453
7454public:
7455 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7456
7457 bool operator()(LocalDeclID L, LocalDeclID R) const {
7458 SourceLocation LHS = getLocation(L);
7459 SourceLocation RHS = getLocation(R);
7460 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7461 }
7462
7463 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7464 SourceLocation RHS = getLocation(R);
7465 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7466 }
7467
7468 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7469 SourceLocation LHS = getLocation(L);
7470 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7471 }
7472
7473 SourceLocation getLocation(LocalDeclID ID) const {
7474 return Reader.getSourceManager().getFileLoc(
7475 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7476 }
7477};
7478
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007479} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007480
7481void ASTReader::FindFileRegionDecls(FileID File,
7482 unsigned Offset, unsigned Length,
7483 SmallVectorImpl<Decl *> &Decls) {
7484 SourceManager &SM = getSourceManager();
7485
7486 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7487 if (I == FileDeclIDs.end())
7488 return;
7489
7490 FileDeclsInfo &DInfo = I->second;
7491 if (DInfo.Decls.empty())
7492 return;
7493
7494 SourceLocation
7495 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7496 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7497
7498 DeclIDComp DIDComp(*this, *DInfo.Mod);
7499 ArrayRef<serialization::LocalDeclID>::iterator
7500 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7501 BeginLoc, DIDComp);
7502 if (BeginIt != DInfo.Decls.begin())
7503 --BeginIt;
7504
7505 // If we are pointing at a top-level decl inside an objc container, we need
7506 // to backtrack until we find it otherwise we will fail to report that the
7507 // region overlaps with an objc container.
7508 while (BeginIt != DInfo.Decls.begin() &&
7509 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7510 ->isTopLevelDeclInObjCContainer())
7511 --BeginIt;
7512
7513 ArrayRef<serialization::LocalDeclID>::iterator
7514 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7515 EndLoc, DIDComp);
7516 if (EndIt != DInfo.Decls.end())
7517 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007518
Guy Benyei11169dd2012-12-18 14:30:41 +00007519 for (ArrayRef<serialization::LocalDeclID>::iterator
7520 DIt = BeginIt; DIt != EndIt; ++DIt)
7521 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7522}
7523
Richard Smith9ce12e32013-02-07 03:30:24 +00007524bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007525ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7526 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007527 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007528 "DeclContext has no visible decls in storage");
7529 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007530 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007531
Richard Smithd88a7f12015-09-01 20:35:42 +00007532 auto It = Lookups.find(DC);
7533 if (It == Lookups.end())
7534 return false;
7535
Richard Smith8c913ec2014-08-14 02:21:01 +00007536 Deserializing LookupResults(this);
7537
Richard Smithd88a7f12015-09-01 20:35:42 +00007538 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007539 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007540 for (DeclID ID : It->second.Table.find(Name)) {
7541 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007542 if (ND->getDeclName() == Name)
7543 Decls.push_back(ND);
7544 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007545
Guy Benyei11169dd2012-12-18 14:30:41 +00007546 ++NumVisibleDeclContextsRead;
7547 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007548 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007549}
7550
Guy Benyei11169dd2012-12-18 14:30:41 +00007551void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7552 if (!DC->hasExternalVisibleStorage())
7553 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007554
7555 auto It = Lookups.find(DC);
7556 assert(It != Lookups.end() &&
7557 "have external visible storage but no lookup tables");
7558
Craig Topper79be4cd2013-07-05 04:33:53 +00007559 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007560
Vedant Kumar48b4f762018-04-14 01:40:48 +00007561 for (DeclID ID : It->second.Table.findAll()) {
7562 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007563 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007564 }
7565
Guy Benyei11169dd2012-12-18 14:30:41 +00007566 ++NumVisibleDeclContextsRead;
7567
Vedant Kumar48b4f762018-04-14 01:40:48 +00007568 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7569 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7570 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007571 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7572}
7573
Richard Smithd88a7f12015-09-01 20:35:42 +00007574const serialization::reader::DeclContextLookupTable *
7575ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7576 auto I = Lookups.find(Primary);
7577 return I == Lookups.end() ? nullptr : &I->second;
7578}
7579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007580/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007581/// before receiving the implementation, and codegen depends on this.
7582/// We simulate this by deserializing and passing to consumer the methods of the
7583/// implementation before passing the deserialized implementation decl.
7584static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7585 ASTConsumer *Consumer) {
7586 assert(ImplD && Consumer);
7587
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007588 for (auto *I : ImplD->methods())
7589 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007590
7591 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7592}
7593
Guy Benyei11169dd2012-12-18 14:30:41 +00007594void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007595 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007596 PassObjCImplDeclToConsumer(ImplD, Consumer);
7597 else
7598 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7599}
7600
7601void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7602 this->Consumer = Consumer;
7603
Richard Smith9e2341d2015-03-23 03:25:59 +00007604 if (Consumer)
7605 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007606
7607 if (DeserializationListener)
7608 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007609}
7610
7611void ASTReader::PrintStats() {
7612 std::fprintf(stderr, "*** AST File Statistics:\n");
7613
7614 unsigned NumTypesLoaded
7615 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7616 QualType());
7617 unsigned NumDeclsLoaded
7618 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007619 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007620 unsigned NumIdentifiersLoaded
7621 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7622 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007623 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 unsigned NumMacrosLoaded
7625 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7626 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007627 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007628 unsigned NumSelectorsLoaded
7629 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7630 SelectorsLoaded.end(),
7631 Selector());
7632
7633 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7634 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7635 NumSLocEntriesRead, TotalNumSLocEntries,
7636 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7637 if (!TypesLoaded.empty())
7638 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7639 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7640 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7641 if (!DeclsLoaded.empty())
7642 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7643 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7644 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7645 if (!IdentifiersLoaded.empty())
7646 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7647 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7648 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7649 if (!MacrosLoaded.empty())
7650 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7651 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7652 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7653 if (!SelectorsLoaded.empty())
7654 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7655 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7656 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7657 if (TotalNumStatements)
7658 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7659 NumStatementsRead, TotalNumStatements,
7660 ((float)NumStatementsRead/TotalNumStatements * 100));
7661 if (TotalNumMacros)
7662 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7663 NumMacrosRead, TotalNumMacros,
7664 ((float)NumMacrosRead/TotalNumMacros * 100));
7665 if (TotalLexicalDeclContexts)
7666 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7667 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7668 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7669 * 100));
7670 if (TotalVisibleDeclContexts)
7671 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7672 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7673 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7674 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007675 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007676 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7677 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7678 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7679 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007680 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007681 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7682 NumMethodPoolHits, NumMethodPoolLookups,
7683 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007684 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007685 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7686 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7687 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7688 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007689 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007690 std::fprintf(stderr,
7691 " %u / %u identifier table lookups succeeded (%f%%)\n",
7692 NumIdentifierLookupHits, NumIdentifierLookups,
7693 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007694
Douglas Gregore060e572013-01-25 01:03:03 +00007695 if (GlobalIndex) {
7696 std::fprintf(stderr, "\n");
7697 GlobalIndex->printStats();
7698 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007699
Guy Benyei11169dd2012-12-18 14:30:41 +00007700 std::fprintf(stderr, "\n");
7701 dump();
7702 std::fprintf(stderr, "\n");
7703}
7704
7705template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007706LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007707dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007708 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007709 InitialCapacity> &Map) {
7710 if (Map.begin() == Map.end())
7711 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007712
Vedant Kumar48b4f762018-04-14 01:40:48 +00007713 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7714
Guy Benyei11169dd2012-12-18 14:30:41 +00007715 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007716 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7717 I != IEnd; ++I) {
7718 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7719 << "\n";
7720 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007721}
7722
Yaron Kerencdae9412016-01-29 19:38:18 +00007723LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007724 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7725 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7726 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7727 dumpModuleIDMap("Global type map", GlobalTypeMap);
7728 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7729 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7730 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7731 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7732 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007733 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007735
Guy Benyei11169dd2012-12-18 14:30:41 +00007736 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007737 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007738 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007739}
7740
7741/// Return the amount of memory used by memory buffers, breaking down
7742/// by heap-backed versus mmap'ed memory.
7743void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007744 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007745 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007746 size_t bytes = buf->getBufferSize();
7747 switch (buf->getBufferKind()) {
7748 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7749 sizes.malloc_bytes += bytes;
7750 break;
7751 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7752 sizes.mmap_bytes += bytes;
7753 break;
7754 }
7755 }
7756 }
7757}
7758
7759void ASTReader::InitializeSema(Sema &S) {
7760 SemaObj = &S;
7761 S.addExternalSource(this);
7762
7763 // Makes sure any declarations that were deserialized "too early"
7764 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007765 for (uint64_t ID : PreloadedDeclIDs) {
7766 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007767 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007769 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007770
Richard Smith3d8e97e2013-10-18 06:54:39 +00007771 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007772 if (!FPPragmaOptions.empty()) {
7773 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007774 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007775 }
7776
Yaxun Liu5b746652016-12-18 05:18:55 +00007777 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7778 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7779 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007780
7781 UpdateSema();
7782}
7783
7784void ASTReader::UpdateSema() {
7785 assert(SemaObj && "no Sema to update");
7786
7787 // Load the offsets of the declarations that Sema references.
7788 // They will be lazily deserialized when needed.
7789 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007790 assert(SemaDeclRefs.size() % 3 == 0);
7791 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007792 if (!SemaObj->StdNamespace)
7793 SemaObj->StdNamespace = SemaDeclRefs[I];
7794 if (!SemaObj->StdBadAlloc)
7795 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007796 if (!SemaObj->StdAlignValT)
7797 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007798 }
7799 SemaDeclRefs.clear();
7800 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007801
Nico Weber779355f2016-03-02 23:22:00 +00007802 // Update the state of pragmas. Use the same API as if we had encountered the
7803 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007804 if(OptimizeOffPragmaLocation.isValid())
7805 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007806 if (PragmaMSStructState != -1)
7807 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007808 if (PointersToMembersPragmaLocation.isValid()) {
7809 SemaObj->ActOnPragmaMSPointersToMembers(
7810 (LangOptions::PragmaMSPointersToMembersKind)
7811 PragmaMSPointersToMembersState,
7812 PointersToMembersPragmaLocation);
7813 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007814 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007815
7816 if (PragmaPackCurrentValue) {
7817 // The bottom of the stack might have a default value. It must be adjusted
7818 // to the current value to ensure that the packing state is preserved after
7819 // popping entries that were included/imported from a PCH/module.
7820 bool DropFirst = false;
7821 if (!PragmaPackStack.empty() &&
7822 PragmaPackStack.front().Location.isInvalid()) {
7823 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7824 "Expected a default alignment value");
7825 SemaObj->PackStack.Stack.emplace_back(
7826 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007827 SemaObj->PackStack.CurrentPragmaLocation,
7828 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007829 DropFirst = true;
7830 }
7831 for (const auto &Entry :
7832 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7833 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007834 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007835 if (PragmaPackCurrentLocation.isInvalid()) {
7836 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7837 "Expected a default alignment value");
7838 // Keep the current values.
7839 } else {
7840 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7841 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7842 }
7843 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007844}
7845
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007846IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 // Note that we are loading an identifier.
7848 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007849
Douglas Gregor7211ac12013-01-25 23:32:03 +00007850 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007851 NumIdentifierLookups,
7852 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007853
7854 // We don't need to do identifier table lookups in C++ modules (we preload
7855 // all interesting declarations, and don't need to use the scope for name
7856 // lookups). Perform the lookup in PCH files, though, since we don't build
7857 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007858 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007859 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007860 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007861 break;
7862 } else {
7863 // If there is a global index, look there first to determine which modules
7864 // provably do not have any results for this identifier.
7865 GlobalModuleIndex::HitSet Hits;
7866 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7867 if (!loadGlobalIndex()) {
7868 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7869 HitsPtr = &Hits;
7870 }
7871 }
7872
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007873 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007874 }
7875
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 IdentifierInfo *II = Visitor.getIdentifierInfo();
7877 markIdentifierUpToDate(II);
7878 return II;
7879}
7880
7881namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007882
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007883 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 /// identifiers stored within a set of AST files.
7885 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007886 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 const ASTReader &Reader;
7888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007889 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 /// the AST reader.
7891 unsigned Index;
7892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007893 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007894 /// of the current AST file.
7895 ASTIdentifierLookupTable::key_iterator Current;
7896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007897 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007898 /// the current AST file.
7899 ASTIdentifierLookupTable::key_iterator End;
7900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007901 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007902 bool SkipModules;
7903
Guy Benyei11169dd2012-12-18 14:30:41 +00007904 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007905 explicit ASTIdentifierIterator(const ASTReader &Reader,
7906 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007907
Craig Topper3e89dfe2014-03-13 02:13:41 +00007908 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007909 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007910
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007911} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007912
Ben Langmuir537c5b52016-05-04 00:53:13 +00007913ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7914 bool SkipModules)
7915 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007916}
7917
7918StringRef ASTIdentifierIterator::Next() {
7919 while (Current == End) {
7920 // If we have exhausted all of our AST files, we're done.
7921 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007922 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007923
7924 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007925 ModuleFile &F = Reader.ModuleMgr[Index];
7926 if (SkipModules && F.isModule())
7927 continue;
7928
Vedant Kumar48b4f762018-04-14 01:40:48 +00007929 ASTIdentifierLookupTable *IdTable =
7930 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007931 Current = IdTable->key_begin();
7932 End = IdTable->key_end();
7933 }
7934
7935 // We have any identifiers remaining in the current AST file; return
7936 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007937 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007938 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007939 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007940}
7941
Ben Langmuir537c5b52016-05-04 00:53:13 +00007942namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007943
Ben Langmuir537c5b52016-05-04 00:53:13 +00007944/// A utility for appending two IdentifierIterators.
7945class ChainedIdentifierIterator : public IdentifierIterator {
7946 std::unique_ptr<IdentifierIterator> Current;
7947 std::unique_ptr<IdentifierIterator> Queued;
7948
7949public:
7950 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7951 std::unique_ptr<IdentifierIterator> Second)
7952 : Current(std::move(First)), Queued(std::move(Second)) {}
7953
7954 StringRef Next() override {
7955 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007956 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007957
7958 StringRef result = Current->Next();
7959 if (!result.empty())
7960 return result;
7961
7962 // Try the queued iterator, which may itself be empty.
7963 Current.reset();
7964 std::swap(Current, Queued);
7965 return Next();
7966 }
7967};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007968
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007969} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007970
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007971IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007972 if (!loadGlobalIndex()) {
7973 std::unique_ptr<IdentifierIterator> ReaderIter(
7974 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7975 std::unique_ptr<IdentifierIterator> ModulesIter(
7976 GlobalIndex->createIdentifierIterator());
7977 return new ChainedIdentifierIterator(std::move(ReaderIter),
7978 std::move(ModulesIter));
7979 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007980
Guy Benyei11169dd2012-12-18 14:30:41 +00007981 return new ASTIdentifierIterator(*this);
7982}
7983
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007984namespace clang {
7985namespace serialization {
7986
Guy Benyei11169dd2012-12-18 14:30:41 +00007987 class ReadMethodPoolVisitor {
7988 ASTReader &Reader;
7989 Selector Sel;
7990 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007991 unsigned InstanceBits = 0;
7992 unsigned FactoryBits = 0;
7993 bool InstanceHasMoreThanOneDecl = false;
7994 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007995 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7996 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007997
7998 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007999 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00008000 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008001 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00008002
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008003 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008004 if (!M.SelectorLookupTable)
8005 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008006
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00008008 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00008009 return true;
8010
Richard Smithbdf2d932015-07-30 03:37:16 +00008011 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00008012 ASTSelectorLookupTable *PoolTable
8013 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00008014 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00008015 if (Pos == PoolTable->end())
8016 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008017
Richard Smithbdf2d932015-07-30 03:37:16 +00008018 ++Reader.NumMethodPoolTableHits;
8019 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 // FIXME: Not quite happy with the statistics here. We probably should
8021 // disable this tracking when called via LoadSelector.
8022 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00008023 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00008024 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00008025 if (Reader.DeserializationListener)
8026 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008027
Richard Smithbdf2d932015-07-30 03:37:16 +00008028 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
8029 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
8030 InstanceBits = Data.InstanceBits;
8031 FactoryBits = Data.FactoryBits;
8032 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
8033 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00008034 return true;
8035 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008036
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008037 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008038 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
8039 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00008040 }
8041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008042 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008043 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008044 return FactoryMethods;
8045 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008046
8047 unsigned getInstanceBits() const { return InstanceBits; }
8048 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008049
Nico Weberff4b35e2014-12-27 22:14:15 +00008050 bool instanceHasMoreThanOneDecl() const {
8051 return InstanceHasMoreThanOneDecl;
8052 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008053
Nico Weberff4b35e2014-12-27 22:14:15 +00008054 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00008055 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008056
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008057} // namespace serialization
8058} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00008059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008060/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00008061static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
8062 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008063 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
8064 S.addMethodToGlobalList(&List, Methods[I]);
8065 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008066}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008067
Guy Benyei11169dd2012-12-18 14:30:41 +00008068void ASTReader::ReadMethodPool(Selector Sel) {
8069 // Get the selector generation and update it to the current generation.
8070 unsigned &Generation = SelectorGeneration[Sel];
8071 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00008072 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00008073 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008074
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008076 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00008077 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00008078 ModuleMgr.visit(Visitor);
8079
Guy Benyei11169dd2012-12-18 14:30:41 +00008080 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008081 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008083
8084 ++NumMethodPoolHits;
8085
Guy Benyei11169dd2012-12-18 14:30:41 +00008086 if (!getSema())
8087 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008088
Guy Benyei11169dd2012-12-18 14:30:41 +00008089 Sema &S = *getSema();
8090 Sema::GlobalMethodPool::iterator Pos
8091 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008092
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008093 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008094 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008095 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008096 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008097
8098 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8099 // when building a module we keep every method individually and may need to
8100 // update hasMoreThanOneDecl as we add the methods.
8101 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8102 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008103}
8104
Manman Rena0f31a02016-04-29 19:04:05 +00008105void ASTReader::updateOutOfDateSelector(Selector Sel) {
8106 if (SelectorOutOfDate[Sel])
8107 ReadMethodPool(Sel);
8108}
8109
Guy Benyei11169dd2012-12-18 14:30:41 +00008110void ASTReader::ReadKnownNamespaces(
8111 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8112 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008113
Vedant Kumar48b4f762018-04-14 01:40:48 +00008114 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8115 if (NamespaceDecl *Namespace
8116 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008117 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008118 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008119}
8120
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008121void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008122 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008123 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008124 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008125 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008126 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008127 Undefined.insert(std::make_pair(D, Loc));
8128 }
8129}
Nick Lewycky8334af82013-01-26 00:35:08 +00008130
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008131void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8132 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8133 Exprs) {
8134 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008135 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008136 uint64_t Count = DelayedDeleteExprs[Idx++];
8137 for (uint64_t C = 0; C < Count; ++C) {
8138 SourceLocation DeleteLoc =
8139 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8140 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8141 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8142 }
8143 }
8144}
8145
Guy Benyei11169dd2012-12-18 14:30:41 +00008146void ASTReader::ReadTentativeDefinitions(
8147 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008148 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8149 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 if (Var)
8151 TentativeDefs.push_back(Var);
8152 }
8153 TentativeDefinitions.clear();
8154}
8155
8156void ASTReader::ReadUnusedFileScopedDecls(
8157 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008158 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8159 DeclaratorDecl *D
8160 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008161 if (D)
8162 Decls.push_back(D);
8163 }
8164 UnusedFileScopedDecls.clear();
8165}
8166
8167void ASTReader::ReadDelegatingConstructors(
8168 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008169 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8170 CXXConstructorDecl *D
8171 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008172 if (D)
8173 Decls.push_back(D);
8174 }
8175 DelegatingCtorDecls.clear();
8176}
8177
8178void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008179 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8180 TypedefNameDecl *D
8181 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 if (D)
8183 Decls.push_back(D);
8184 }
8185 ExtVectorDecls.clear();
8186}
8187
Nico Weber72889432014-09-06 01:25:55 +00008188void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8189 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008190 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8191 ++I) {
8192 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8193 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008194 if (D)
8195 Decls.insert(D);
8196 }
8197 UnusedLocalTypedefNameCandidates.clear();
8198}
8199
Guy Benyei11169dd2012-12-18 14:30:41 +00008200void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008201 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 if (ReferencedSelectorsData.empty())
8203 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008204
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 // If there are @selector references added them to its pool. This is for
8206 // implementation of -Wselector.
8207 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8208 unsigned I = 0;
8209 while (I < DataSize) {
8210 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8211 SourceLocation SelLoc
8212 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8213 Sels.push_back(std::make_pair(Sel, SelLoc));
8214 }
8215 ReferencedSelectorsData.clear();
8216}
8217
8218void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008219 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 if (WeakUndeclaredIdentifiers.empty())
8221 return;
8222
8223 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008224 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008225 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008226 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008227 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8228 SourceLocation Loc
8229 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8230 bool Used = WeakUndeclaredIdentifiers[I++];
8231 WeakInfo WI(AliasId, Loc);
8232 WI.setUsed(Used);
8233 WeakIDs.push_back(std::make_pair(WeakId, WI));
8234 }
8235 WeakUndeclaredIdentifiers.clear();
8236}
8237
8238void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8239 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8240 ExternalVTableUse VT;
8241 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8242 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8243 VT.DefinitionRequired = VTableUses[Idx++];
8244 VTables.push_back(VT);
8245 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008246
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 VTableUses.clear();
8248}
8249
8250void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008251 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008253 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008254 SourceLocation Loc
8255 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8256
8257 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008259 PendingInstantiations.clear();
8260}
8261
Richard Smithe40f2ba2013-08-07 21:41:30 +00008262void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008263 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8264 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008265 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8266 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008267 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008268
Justin Lebar28f09c52016-10-10 16:26:08 +00008269 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008270 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8271
8272 ModuleFile *F = getOwningModuleFile(LT->D);
8273 assert(F && "No module");
8274
8275 unsigned TokN = LateParsedTemplates[Idx++];
8276 LT->Toks.reserve(TokN);
8277 for (unsigned T = 0; T < TokN; ++T)
8278 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8279
Justin Lebar28f09c52016-10-10 16:26:08 +00008280 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008281 }
8282
8283 LateParsedTemplates.clear();
8284}
8285
Guy Benyei11169dd2012-12-18 14:30:41 +00008286void ASTReader::LoadSelector(Selector Sel) {
8287 // It would be complicated to avoid reading the methods anyway. So don't.
8288 ReadMethodPool(Sel);
8289}
8290
8291void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8292 assert(ID && "Non-zero identifier ID required");
8293 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8294 IdentifiersLoaded[ID - 1] = II;
8295 if (DeserializationListener)
8296 DeserializationListener->IdentifierRead(ID, II);
8297}
8298
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008299/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008300/// identifier.
8301///
8302/// If the AST reader is currently in a state where the given declaration IDs
8303/// cannot safely be resolved, they are queued until it is safe to resolve
8304/// them.
8305///
8306/// \param II an IdentifierInfo that refers to one or more globally-visible
8307/// declarations.
8308///
8309/// \param DeclIDs the set of declaration IDs with the name @p II that are
8310/// visible at global scope.
8311///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008312/// \param Decls if non-null, this vector will be populated with the set of
8313/// deserialized declarations. These declarations will not be pushed into
8314/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008315void
8316ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8317 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008318 SmallVectorImpl<Decl *> *Decls) {
8319 if (NumCurrentElementsDeserializing && !Decls) {
8320 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008321 return;
8322 }
8323
Vedant Kumar48b4f762018-04-14 01:40:48 +00008324 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008325 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 // Queue this declaration so that it will be added to the
8327 // translation unit scope and identifier's declaration chain
8328 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008329 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008330 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008331 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008332
Vedant Kumar48b4f762018-04-14 01:40:48 +00008333 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008334
8335 // If we're simply supposed to record the declarations, do so now.
8336 if (Decls) {
8337 Decls->push_back(D);
8338 continue;
8339 }
8340
8341 // Introduce this declaration into the translation-unit scope
8342 // and add it to the declaration chain for this identifier, so
8343 // that (unqualified) name lookup will find it.
8344 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 }
8346}
8347
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008348IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008349 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008350 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008351
8352 if (IdentifiersLoaded.empty()) {
8353 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008354 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008355 }
8356
8357 ID -= 1;
8358 if (!IdentifiersLoaded[ID]) {
8359 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8360 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8361 ModuleFile *M = I->second;
8362 unsigned Index = ID - M->BaseIdentifierID;
8363 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8364
8365 // All of the strings in the AST file are preceded by a 16-bit length.
8366 // Extract that 16-bit length to avoid having to execute strlen().
8367 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8368 // unsigned integers. This is important to avoid integer overflow when
8369 // we cast them to 'unsigned'.
8370 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8371 unsigned StrLen = (((unsigned) StrLenPtr[0])
8372 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008373 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8374 IdentifiersLoaded[ID] = &II;
8375 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008377 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 }
8379
8380 return IdentifiersLoaded[ID];
8381}
8382
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008383IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8384 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008385}
8386
8387IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8388 if (LocalID < NUM_PREDEF_IDENT_IDS)
8389 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008390
Richard Smith37a93df2017-02-18 00:32:02 +00008391 if (!M.ModuleOffsetMap.empty())
8392 ReadModuleOffsetMap(M);
8393
Guy Benyei11169dd2012-12-18 14:30:41 +00008394 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8395 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008396 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008397 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008398
Guy Benyei11169dd2012-12-18 14:30:41 +00008399 return LocalID + I->second;
8400}
8401
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008402MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008403 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008404 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008405
8406 if (MacrosLoaded.empty()) {
8407 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008408 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008409 }
8410
8411 ID -= NUM_PREDEF_MACRO_IDS;
8412 if (!MacrosLoaded[ID]) {
8413 GlobalMacroMapType::iterator I
8414 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8415 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8416 ModuleFile *M = I->second;
8417 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008418 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008419
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008420 if (DeserializationListener)
8421 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8422 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008423 }
8424
8425 return MacrosLoaded[ID];
8426}
8427
8428MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8429 if (LocalID < NUM_PREDEF_MACRO_IDS)
8430 return LocalID;
8431
Richard Smith37a93df2017-02-18 00:32:02 +00008432 if (!M.ModuleOffsetMap.empty())
8433 ReadModuleOffsetMap(M);
8434
Guy Benyei11169dd2012-12-18 14:30:41 +00008435 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8436 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8437 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8438
8439 return LocalID + I->second;
8440}
8441
8442serialization::SubmoduleID
8443ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8444 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8445 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008446
Richard Smith37a93df2017-02-18 00:32:02 +00008447 if (!M.ModuleOffsetMap.empty())
8448 ReadModuleOffsetMap(M);
8449
Guy Benyei11169dd2012-12-18 14:30:41 +00008450 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8451 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008452 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008453 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008454
Guy Benyei11169dd2012-12-18 14:30:41 +00008455 return LocalID + I->second;
8456}
8457
8458Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8459 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8460 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008461 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008462 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008463
Guy Benyei11169dd2012-12-18 14:30:41 +00008464 if (GlobalID > SubmodulesLoaded.size()) {
8465 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008466 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008467 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008468
Guy Benyei11169dd2012-12-18 14:30:41 +00008469 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8470}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008471
8472Module *ASTReader::getModule(unsigned ID) {
8473 return getSubmodule(ID);
8474}
8475
Hans Wennborg08c5a7b2018-06-25 13:23:49 +00008476bool ASTReader::DeclIsFromPCHWithObjectFile(const Decl *D) {
8477 ModuleFile *MF = getOwningModuleFile(D);
8478 return MF && MF->PCHHasObjectFile;
8479}
8480
Richard Smithd88a7f12015-09-01 20:35:42 +00008481ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8482 if (ID & 1) {
8483 // It's a module, look it up by submodule ID.
8484 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8485 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8486 } else {
8487 // It's a prefix (preamble, PCH, ...). Look it up by index.
8488 unsigned IndexFromEnd = ID >> 1;
8489 assert(IndexFromEnd && "got reference to unknown module file");
8490 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8491 }
8492}
8493
8494unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8495 if (!F)
8496 return 1;
8497
8498 // For a file representing a module, use the submodule ID of the top-level
8499 // module as the file ID. For any other kind of file, the number of such
8500 // files loaded beforehand will be the same on reload.
8501 // FIXME: Is this true even if we have an explicit module file and a PCH?
8502 if (F->isModule())
8503 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8504
8505 auto PCHModules = getModuleManager().pch_modules();
8506 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8507 assert(I != PCHModules.end() && "emitting reference to unknown file");
8508 return (I - PCHModules.end()) << 1;
8509}
8510
Adrian Prantl15bcf702015-06-30 17:39:43 +00008511llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8512ASTReader::getSourceDescriptor(unsigned ID) {
8513 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008514 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008515
8516 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008517 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008518 const auto &PCHChain = ModuleMgr.pch_modules();
8519 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008520 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008521 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008522 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8523 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8524 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008525 }
8526 return None;
8527}
8528
David Blaikie1ac9c982017-04-11 21:13:37 +00008529ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008530 auto I = DefinitionSource.find(FD);
8531 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008532 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008533 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008534}
8535
Guy Benyei11169dd2012-12-18 14:30:41 +00008536Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8537 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8538}
8539
8540Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8541 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008542 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008543
8544 if (ID > SelectorsLoaded.size()) {
8545 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008546 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008547 }
8548
Craig Toppera13603a2014-05-22 05:54:18 +00008549 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008550 // Load this selector from the selector table.
8551 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8552 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8553 ModuleFile &M = *I->second;
8554 ASTSelectorLookupTrait Trait(*this, M);
8555 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8556 SelectorsLoaded[ID - 1] =
8557 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8558 if (DeserializationListener)
8559 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8560 }
8561
8562 return SelectorsLoaded[ID - 1];
8563}
8564
8565Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8566 return DecodeSelector(ID);
8567}
8568
8569uint32_t ASTReader::GetNumExternalSelectors() {
8570 // ID 0 (the null selector) is considered an external selector.
8571 return getTotalNumSelectors() + 1;
8572}
8573
8574serialization::SelectorID
8575ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8576 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8577 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008578
Richard Smith37a93df2017-02-18 00:32:02 +00008579 if (!M.ModuleOffsetMap.empty())
8580 ReadModuleOffsetMap(M);
8581
Guy Benyei11169dd2012-12-18 14:30:41 +00008582 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8583 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008584 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008585 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008586
Guy Benyei11169dd2012-12-18 14:30:41 +00008587 return LocalID + I->second;
8588}
8589
8590DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008591ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008592 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008593 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008594 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008595 switch (Kind) {
8596 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008597 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008598
8599 case DeclarationName::ObjCZeroArgSelector:
8600 case DeclarationName::ObjCOneArgSelector:
8601 case DeclarationName::ObjCMultiArgSelector:
8602 return DeclarationName(ReadSelector(F, Record, Idx));
8603
8604 case DeclarationName::CXXConstructorName:
8605 return Context.DeclarationNames.getCXXConstructorName(
8606 Context.getCanonicalType(readType(F, Record, Idx)));
8607
8608 case DeclarationName::CXXDestructorName:
8609 return Context.DeclarationNames.getCXXDestructorName(
8610 Context.getCanonicalType(readType(F, Record, Idx)));
8611
Richard Smith35845152017-02-07 01:37:30 +00008612 case DeclarationName::CXXDeductionGuideName:
8613 return Context.DeclarationNames.getCXXDeductionGuideName(
8614 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8615
Guy Benyei11169dd2012-12-18 14:30:41 +00008616 case DeclarationName::CXXConversionFunctionName:
8617 return Context.DeclarationNames.getCXXConversionFunctionName(
8618 Context.getCanonicalType(readType(F, Record, Idx)));
8619
8620 case DeclarationName::CXXOperatorName:
8621 return Context.DeclarationNames.getCXXOperatorName(
8622 (OverloadedOperatorKind)Record[Idx++]);
8623
8624 case DeclarationName::CXXLiteralOperatorName:
8625 return Context.DeclarationNames.getCXXLiteralOperatorName(
8626 GetIdentifierInfo(F, Record, Idx));
8627
8628 case DeclarationName::CXXUsingDirective:
8629 return DeclarationName::getUsingDirectiveName();
8630 }
8631
8632 llvm_unreachable("Invalid NameKind!");
8633}
8634
8635void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8636 DeclarationNameLoc &DNLoc,
8637 DeclarationName Name,
8638 const RecordData &Record, unsigned &Idx) {
8639 switch (Name.getNameKind()) {
8640 case DeclarationName::CXXConstructorName:
8641 case DeclarationName::CXXDestructorName:
8642 case DeclarationName::CXXConversionFunctionName:
8643 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8644 break;
8645
8646 case DeclarationName::CXXOperatorName:
8647 DNLoc.CXXOperatorName.BeginOpNameLoc
8648 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8649 DNLoc.CXXOperatorName.EndOpNameLoc
8650 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8651 break;
8652
8653 case DeclarationName::CXXLiteralOperatorName:
8654 DNLoc.CXXLiteralOperatorName.OpNameLoc
8655 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8656 break;
8657
8658 case DeclarationName::Identifier:
8659 case DeclarationName::ObjCZeroArgSelector:
8660 case DeclarationName::ObjCOneArgSelector:
8661 case DeclarationName::ObjCMultiArgSelector:
8662 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008663 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 break;
8665 }
8666}
8667
8668void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8669 DeclarationNameInfo &NameInfo,
8670 const RecordData &Record, unsigned &Idx) {
8671 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8672 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8673 DeclarationNameLoc DNLoc;
8674 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8675 NameInfo.setInfo(DNLoc);
8676}
8677
8678void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8679 const RecordData &Record, unsigned &Idx) {
8680 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8681 unsigned NumTPLists = Record[Idx++];
8682 Info.NumTemplParamLists = NumTPLists;
8683 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008684 Info.TemplParamLists =
8685 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008686 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8688 }
8689}
8690
8691TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008692ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008693 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008694 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008695 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008696 switch (Kind) {
8697 case TemplateName::Template:
8698 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8699
8700 case TemplateName::OverloadedTemplate: {
8701 unsigned size = Record[Idx++];
8702 UnresolvedSet<8> Decls;
8703 while (size--)
8704 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8705
8706 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8707 }
8708
8709 case TemplateName::QualifiedTemplate: {
8710 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8711 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008712 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008713 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8714 }
8715
8716 case TemplateName::DependentTemplate: {
8717 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8718 if (Record[Idx++]) // isIdentifier
8719 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008720 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008721 Idx));
8722 return Context.getDependentTemplateName(NNS,
8723 (OverloadedOperatorKind)Record[Idx++]);
8724 }
8725
8726 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008727 TemplateTemplateParmDecl *param
8728 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8729 if (!param) return TemplateName();
8730 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8731 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00008732 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008733
Guy Benyei11169dd2012-12-18 14:30:41 +00008734 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008735 TemplateTemplateParmDecl *Param
8736 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008737 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008738 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008739
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8741 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008742 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008743
Guy Benyei11169dd2012-12-18 14:30:41 +00008744 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8745 }
8746 }
8747
8748 llvm_unreachable("Unhandled template name kind!");
8749}
8750
Richard Smith2bb3c342015-08-09 01:05:31 +00008751TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8752 const RecordData &Record,
8753 unsigned &Idx,
8754 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008755 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008756 if (Canonicalize) {
8757 // The caller wants a canonical template argument. Sometimes the AST only
8758 // wants template arguments in canonical form (particularly as the template
8759 // argument lists of template specializations) so ensure we preserve that
8760 // canonical form across serialization.
8761 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8762 return Context.getCanonicalTemplateArgument(Arg);
8763 }
8764
Vedant Kumar48b4f762018-04-14 01:40:48 +00008765 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008766 switch (Kind) {
8767 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00008768 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00008769 case TemplateArgument::Type:
8770 return TemplateArgument(readType(F, Record, Idx));
8771 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008772 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008773 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008774 }
8775 case TemplateArgument::NullPtr:
8776 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8777 case TemplateArgument::Integral: {
8778 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8779 QualType T = readType(F, Record, Idx);
8780 return TemplateArgument(Context, Value, T);
8781 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008782 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8784 case TemplateArgument::TemplateExpansion: {
8785 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008786 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008787 if (unsigned NumExpansions = Record[Idx++])
8788 NumTemplateExpansions = NumExpansions - 1;
8789 return TemplateArgument(Name, NumTemplateExpansions);
8790 }
8791 case TemplateArgument::Expression:
8792 return TemplateArgument(ReadExpr(F));
8793 case TemplateArgument::Pack: {
8794 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008795 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00008796 for (unsigned I = 0; I != NumArgs; ++I)
8797 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008798 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008799 }
8800 }
8801
8802 llvm_unreachable("Unhandled template argument kind!");
8803}
8804
8805TemplateParameterList *
8806ASTReader::ReadTemplateParameterList(ModuleFile &F,
8807 const RecordData &Record, unsigned &Idx) {
8808 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8809 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8810 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8811
8812 unsigned NumParams = Record[Idx++];
8813 SmallVector<NamedDecl *, 16> Params;
8814 Params.reserve(NumParams);
8815 while (NumParams--)
8816 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8817
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008818 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008819 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8820 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008821 return TemplateParams;
8822}
8823
8824void
8825ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008826ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008827 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008828 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008829 unsigned NumTemplateArgs = Record[Idx++];
8830 TemplArgs.reserve(NumTemplateArgs);
8831 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008832 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008833}
8834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008835/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008836void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008837 const RecordData &Record, unsigned &Idx) {
8838 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008839 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008840 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008841 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008842 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008843 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008844 }
8845}
8846
8847CXXBaseSpecifier
8848ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8849 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008850 bool isVirtual = static_cast<bool>(Record[Idx++]);
8851 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8852 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8853 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008854 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8855 SourceRange Range = ReadSourceRange(F, Record, Idx);
8856 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008857 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008858 EllipsisLoc);
8859 Result.setInheritConstructors(inheritConstructors);
8860 return Result;
8861}
8862
Richard Smithc2bb8182015-03-24 06:36:48 +00008863CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008864ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8865 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008866 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008867 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008868 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008869 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008870 for (unsigned i = 0; i != NumInitializers; ++i) {
8871 TypeSourceInfo *TInfo = nullptr;
8872 bool IsBaseVirtual = false;
8873 FieldDecl *Member = nullptr;
8874 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008875
Vedant Kumar48b4f762018-04-14 01:40:48 +00008876 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008877 switch (Type) {
8878 case CTOR_INITIALIZER_BASE:
8879 TInfo = GetTypeSourceInfo(F, Record, Idx);
8880 IsBaseVirtual = Record[Idx++];
8881 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008882
Richard Smithc2bb8182015-03-24 06:36:48 +00008883 case CTOR_INITIALIZER_DELEGATING:
8884 TInfo = GetTypeSourceInfo(F, Record, Idx);
8885 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008886
Richard Smithc2bb8182015-03-24 06:36:48 +00008887 case CTOR_INITIALIZER_MEMBER:
8888 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8889 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008890
Richard Smithc2bb8182015-03-24 06:36:48 +00008891 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8892 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8893 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008894 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008895
8896 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8897 Expr *Init = ReadExpr(F);
8898 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8899 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008900
8901 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008902 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008903 BOMInit = new (Context)
8904 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8905 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008906 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008907 BOMInit = new (Context)
8908 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008909 else if (Member)
8910 BOMInit = new (Context)
8911 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8912 Init, RParenLoc);
8913 else
8914 BOMInit = new (Context)
8915 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8916 LParenLoc, Init, RParenLoc);
8917
Richard Smith418ed822016-12-14 19:45:03 +00008918 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008919 unsigned SourceOrder = Record[Idx++];
8920 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008921 }
8922
Richard Smithc2bb8182015-03-24 06:36:48 +00008923 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008924 }
8925
Richard Smithc2bb8182015-03-24 06:36:48 +00008926 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008927}
8928
8929NestedNameSpecifier *
8930ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8931 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008932 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008933 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008934 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008935 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008936 NestedNameSpecifier::SpecifierKind Kind
8937 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008938 switch (Kind) {
8939 case NestedNameSpecifier::Identifier: {
8940 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8941 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8942 break;
8943 }
8944
8945 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008946 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008947 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8948 break;
8949 }
8950
8951 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008952 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008953 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8954 break;
8955 }
8956
8957 case NestedNameSpecifier::TypeSpec:
8958 case NestedNameSpecifier::TypeSpecWithTemplate: {
8959 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8960 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008961 return nullptr;
8962
Guy Benyei11169dd2012-12-18 14:30:41 +00008963 bool Template = Record[Idx++];
8964 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8965 break;
8966 }
8967
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008968 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008969 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8970 // No associated value, and there can't be a prefix.
8971 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008972
8973 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008974 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008975 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8976 break;
8977 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008978 }
8979 Prev = NNS;
8980 }
8981 return NNS;
8982}
8983
8984NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008985ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008986 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008987 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 unsigned N = Record[Idx++];
8989 NestedNameSpecifierLocBuilder Builder;
8990 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008991 NestedNameSpecifier::SpecifierKind Kind
8992 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008993 switch (Kind) {
8994 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008995 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008996 SourceRange Range = ReadSourceRange(F, Record, Idx);
8997 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8998 break;
8999 }
9000
9001 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009002 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009003 SourceRange Range = ReadSourceRange(F, Record, Idx);
9004 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
9005 break;
9006 }
9007
9008 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009009 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00009010 SourceRange Range = ReadSourceRange(F, Record, Idx);
9011 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
9012 break;
9013 }
9014
9015 case NestedNameSpecifier::TypeSpec:
9016 case NestedNameSpecifier::TypeSpecWithTemplate: {
9017 bool Template = Record[Idx++];
9018 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
9019 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009020 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00009021 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9022
9023 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009024 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00009025 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
9026 T->getTypeLoc(), ColonColonLoc);
9027 break;
9028 }
9029
9030 case NestedNameSpecifier::Global: {
9031 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
9032 Builder.MakeGlobal(Context, ColonColonLoc);
9033 break;
9034 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009035
9036 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009037 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00009038 SourceRange Range = ReadSourceRange(F, Record, Idx);
9039 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
9040 break;
9041 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009042 }
9043 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00009044
Guy Benyei11169dd2012-12-18 14:30:41 +00009045 return Builder.getWithLocInContext(Context);
9046}
9047
9048SourceRange
9049ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
9050 unsigned &Idx) {
9051 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
9052 SourceLocation end = ReadSourceLocation(F, Record, Idx);
9053 return SourceRange(beg, end);
9054}
9055
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009056/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009057llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
9058 unsigned BitWidth = Record[Idx++];
9059 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
9060 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
9061 Idx += NumWords;
9062 return Result;
9063}
9064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009065/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00009066llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
9067 bool isUnsigned = Record[Idx++];
9068 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
9069}
9070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009071/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00009072llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
9073 const llvm::fltSemantics &Sem,
9074 unsigned &Idx) {
9075 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00009076}
9077
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009078// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00009079std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
9080 unsigned Len = Record[Idx++];
9081 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
9082 Idx += Len;
9083 return Result;
9084}
9085
Richard Smith7ed1bc92014-12-05 22:42:13 +00009086std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9087 unsigned &Idx) {
9088 std::string Filename = ReadString(Record, Idx);
9089 ResolveImportedPath(F, Filename);
9090 return Filename;
9091}
9092
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009093VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009094 unsigned &Idx) {
9095 unsigned Major = Record[Idx++];
9096 unsigned Minor = Record[Idx++];
9097 unsigned Subminor = Record[Idx++];
9098 if (Minor == 0)
9099 return VersionTuple(Major);
9100 if (Subminor == 0)
9101 return VersionTuple(Major, Minor - 1);
9102 return VersionTuple(Major, Minor - 1, Subminor - 1);
9103}
9104
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009105CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009106 const RecordData &Record,
9107 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009108 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009109 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009110}
9111
Richard Smith37a93df2017-02-18 00:32:02 +00009112DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009113 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009114}
9115
Richard Smith37a93df2017-02-18 00:32:02 +00009116DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009117 return Diags.Report(Loc, DiagID);
9118}
9119
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009120/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009121/// preprocessor.
9122IdentifierTable &ASTReader::getIdentifierTable() {
9123 return PP.getIdentifierTable();
9124}
9125
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009126/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009127/// statement.
9128void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009129 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009130 "Already have a SwitchCase with this ID");
9131 (*CurrSwitchCaseStmts)[ID] = SC;
9132}
9133
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009134/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009135SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009136 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009137 return (*CurrSwitchCaseStmts)[ID];
9138}
9139
9140void ASTReader::ClearSwitchCaseIDs() {
9141 CurrSwitchCaseStmts->clear();
9142}
9143
9144void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009145 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009146 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009147 for (SmallVectorImpl<std::pair<BitstreamCursor,
9148 serialization::ModuleFile *>>::iterator
9149 I = CommentsCursors.begin(),
9150 E = CommentsCursors.end();
9151 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009152 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009153 BitstreamCursor &Cursor = I->first;
9154 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009155 SavedStreamPosition SavedPosition(Cursor);
9156
9157 RecordData Record;
9158 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009159 llvm::BitstreamEntry Entry =
9160 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009161
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009162 switch (Entry.Kind) {
9163 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9164 case llvm::BitstreamEntry::Error:
9165 Error("malformed block record in AST file");
9166 return;
9167 case llvm::BitstreamEntry::EndBlock:
9168 goto NextCursor;
9169 case llvm::BitstreamEntry::Record:
9170 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009171 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009172 }
9173
9174 // Read a record.
9175 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009176 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009177 case COMMENTS_RAW_COMMENT: {
9178 unsigned Idx = 0;
9179 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009180 RawComment::CommentKind Kind =
9181 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009182 bool IsTrailingComment = Record[Idx++];
9183 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009184 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009185 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009186 break;
9187 }
9188 }
9189 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009190 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009191 // De-serialized SourceLocations get negative FileIDs for other modules,
9192 // potentially invalidating the original order. Sort it again.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00009193 llvm::sort(Comments.begin(), Comments.end(),
9194 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009195 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009196 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009197}
9198
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009199void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9200 bool IncludeSystem, bool Complain,
9201 llvm::function_ref<void(const serialization::InputFile &IF,
9202 bool isSystem)> Visitor) {
9203 unsigned NumUserInputs = MF.NumUserInputFiles;
9204 unsigned NumInputs = MF.InputFilesLoaded.size();
9205 assert(NumUserInputs <= NumInputs);
9206 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9207 for (unsigned I = 0; I < N; ++I) {
9208 bool IsSystem = I >= NumUserInputs;
9209 InputFile IF = getInputFile(MF, I+1, Complain);
9210 Visitor(IF, IsSystem);
9211 }
9212}
9213
Richard Smithf3f84612017-06-29 02:19:42 +00009214void ASTReader::visitTopLevelModuleMaps(
9215 serialization::ModuleFile &MF,
9216 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9217 unsigned NumInputs = MF.InputFilesLoaded.size();
9218 for (unsigned I = 0; I < NumInputs; ++I) {
9219 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9220 if (IFI.TopLevelModuleMap)
9221 // FIXME: This unnecessarily re-reads the InputFileInfo.
9222 if (auto *FE = getInputFile(MF, I + 1).getFile())
9223 Visitor(FE);
9224 }
9225}
9226
Richard Smithcd45dbc2014-04-19 03:48:30 +00009227std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9228 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009229 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009230 return M->getFullModuleName();
9231
9232 // Otherwise, use the name of the top-level module the decl is within.
9233 if (ModuleFile *M = getOwningModuleFile(D))
9234 return M->ModuleName;
9235
9236 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009237 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009238}
9239
Guy Benyei11169dd2012-12-18 14:30:41 +00009240void ASTReader::finishPendingActions() {
Richard Smitha62d1982018-08-03 01:00:01 +00009241 while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
Richard Smith851072e2014-05-19 20:59:20 +00009242 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009243 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009244 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009245 // If any identifiers with corresponding top-level declarations have
9246 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009247 using TopLevelDeclsMap =
9248 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009249 TopLevelDeclsMap TopLevelDecls;
9250
Guy Benyei11169dd2012-12-18 14:30:41 +00009251 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009252 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009253 SmallVector<uint32_t, 4> DeclIDs =
9254 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009255 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009256
9257 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009258 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009259
Richard Smitha62d1982018-08-03 01:00:01 +00009260 // Load each function type that we deferred loading because it was a
9261 // deduced type that might refer to a local type declared within itself.
9262 for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
9263 auto *FD = PendingFunctionTypes[I].first;
9264 FD->setType(GetType(PendingFunctionTypes[I].second));
9265
9266 // If we gave a function a deduced return type, remember that we need to
9267 // propagate that along the redeclaration chain.
9268 auto *DT = FD->getReturnType()->getContainedDeducedType();
9269 if (DT && DT->isDeduced())
9270 PendingDeducedTypeUpdates.insert(
9271 {FD->getCanonicalDecl(), FD->getReturnType()});
9272 }
9273 PendingFunctionTypes.clear();
9274
Richard Smith851072e2014-05-19 20:59:20 +00009275 // For each decl chain that we wanted to complete while deserializing, mark
9276 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009277 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9278 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9279 }
Richard Smith851072e2014-05-19 20:59:20 +00009280 PendingIncompleteDeclChains.clear();
9281
Guy Benyei11169dd2012-12-18 14:30:41 +00009282 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009283 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smitha62d1982018-08-03 01:00:01 +00009284 loadPendingDeclChain(PendingDeclChains[I].first,
9285 PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009286 PendingDeclChains.clear();
9287
Douglas Gregor6168bd22013-02-18 15:53:43 +00009288 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009289 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9290 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9291 IdentifierInfo *II = TLD->first;
9292 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9293 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009294 }
9295 }
9296
Guy Benyei11169dd2012-12-18 14:30:41 +00009297 // Load any pending macro definitions.
9298 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009299 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9300 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9301 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9302 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009303 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009304 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009305 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009306 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009307 resolvePendingMacro(II, Info);
9308 }
9309 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009310 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009311 ++IDIdx) {
9312 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009313 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009314 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009315 }
9316 }
9317 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009318
9319 // Wire up the DeclContexts for Decls that we delayed setting until
9320 // recursive loading is completed.
9321 while (!PendingDeclContextInfos.empty()) {
9322 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9323 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009324 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9325 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009326 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9327 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009328
Richard Smithd1c46742014-04-30 02:24:17 +00009329 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009330 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009331 auto Update = PendingUpdateRecords.pop_back_val();
9332 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009333 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009334 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009335 }
Richard Smith8a639892015-01-24 01:07:20 +00009336
9337 // At this point, all update records for loaded decls are in place, so any
9338 // fake class definitions should have become real.
9339 assert(PendingFakeDefinitionData.empty() &&
9340 "faked up a class definition but never saw the real one");
9341
Guy Benyei11169dd2012-12-18 14:30:41 +00009342 // If we deserialized any C++ or Objective-C class definitions, any
9343 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009344 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009345 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009346 for (Decl *D : PendingDefinitions) {
9347 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9348 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009349 // Make sure that the TagType points at the definition.
9350 const_cast<TagType*>(TagT)->decl = TD;
9351 }
Richard Smith8ce51082015-03-11 01:44:51 +00009352
Vedant Kumar48b4f762018-04-14 01:40:48 +00009353 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009354 for (auto *R = getMostRecentExistingDecl(RD); R;
9355 R = R->getPreviousDecl()) {
9356 assert((R == D) ==
9357 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009358 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009359 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009360 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009361 }
9362
9363 continue;
9364 }
Richard Smith8ce51082015-03-11 01:44:51 +00009365
Vedant Kumar48b4f762018-04-14 01:40:48 +00009366 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009367 // Make sure that the ObjCInterfaceType points at the definition.
9368 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9369 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009370
9371 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9372 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9373
Guy Benyei11169dd2012-12-18 14:30:41 +00009374 continue;
9375 }
Richard Smith8ce51082015-03-11 01:44:51 +00009376
Vedant Kumar48b4f762018-04-14 01:40:48 +00009377 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009378 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9379 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9380
Guy Benyei11169dd2012-12-18 14:30:41 +00009381 continue;
9382 }
Richard Smith8ce51082015-03-11 01:44:51 +00009383
Vedant Kumar48b4f762018-04-14 01:40:48 +00009384 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009385 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9386 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009387 }
9388 PendingDefinitions.clear();
9389
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009390 // Load the bodies of any functions or methods we've encountered. We do
9391 // this now (delayed) so that we can be sure that the declaration chains
9392 // have been fully wired up (hasBody relies on this).
9393 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009394 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9395 PBEnd = PendingBodies.end();
9396 PB != PBEnd; ++PB) {
9397 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Richard Smith0b70de12018-06-28 01:07:28 +00009398 // For a function defined inline within a class template, force the
9399 // canonical definition to be the one inside the canonical definition of
9400 // the template. This ensures that we instantiate from a correct view
9401 // of the template.
9402 //
9403 // Sadly we can't do this more generally: we can't be sure that all
9404 // copies of an arbitrary class definition will have the same members
9405 // defined (eg, some member functions may not be instantiated, and some
9406 // special members may or may not have been implicitly defined).
9407 if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
9408 if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
9409 continue;
9410
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009411 // FIXME: Check for =delete/=default?
9412 // FIXME: Complain about ODR violations here?
9413 const FunctionDecl *Defn = nullptr;
9414 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009415 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009416 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009417 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009418 mergeDefinitionVisibility(NonConstDefn, FD);
9419
9420 if (!FD->isLateTemplateParsed() &&
9421 !NonConstDefn->isLateTemplateParsed() &&
9422 FD->getODRHash() != NonConstDefn->getODRHash()) {
Richard Trieu27c1b1a2018-07-10 01:40:50 +00009423 if (!isa<CXXMethodDecl>(FD)) {
9424 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9425 } else if (FD->getLexicalParent()->isFileContext() &&
9426 NonConstDefn->getLexicalParent()->isFileContext()) {
9427 // Only diagnose out-of-line method definitions. If they are
9428 // in class definitions, then an error will be generated when
9429 // processing the class bodies.
9430 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9431 }
Richard Trieue6caa262017-12-23 00:41:01 +00009432 }
9433 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009434 continue;
9435 }
9436
Vedant Kumar48b4f762018-04-14 01:40:48 +00009437 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009438 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009439 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009440 }
9441 PendingBodies.clear();
9442
Richard Smith42413142015-05-15 20:05:43 +00009443 // Do some cleanup.
9444 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9445 getContext().deduplicateMergedDefinitonsFor(ND);
9446 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009447}
9448
9449void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009450 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
Richard Trieuab4d7302018-07-25 22:52:05 +00009451 PendingFunctionOdrMergeFailures.empty() &&
9452 PendingEnumOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009453 return;
9454
Richard Smitha0ce9c42014-07-29 23:23:27 +00009455 // Trigger the import of the full definition of each class that had any
9456 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009457 // These updates may in turn find and diagnose some ODR failures, so take
9458 // ownership of the set first.
9459 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9460 PendingOdrMergeFailures.clear();
9461 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009462 Merge.first->buildLookup();
9463 Merge.first->decls_begin();
9464 Merge.first->bases_begin();
9465 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009466 for (auto &RecordPair : Merge.second) {
9467 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009468 RD->decls_begin();
9469 RD->bases_begin();
9470 RD->vbases_begin();
9471 }
9472 }
9473
Richard Trieue6caa262017-12-23 00:41:01 +00009474 // Trigger the import of functions.
9475 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9476 PendingFunctionOdrMergeFailures.clear();
9477 for (auto &Merge : FunctionOdrMergeFailures) {
9478 Merge.first->buildLookup();
9479 Merge.first->decls_begin();
9480 Merge.first->getBody();
9481 for (auto &FD : Merge.second) {
9482 FD->buildLookup();
9483 FD->decls_begin();
9484 FD->getBody();
9485 }
9486 }
9487
Richard Trieuab4d7302018-07-25 22:52:05 +00009488 // Trigger the import of enums.
9489 auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
9490 PendingEnumOdrMergeFailures.clear();
9491 for (auto &Merge : EnumOdrMergeFailures) {
9492 Merge.first->decls_begin();
9493 for (auto &Enum : Merge.second) {
9494 Enum->decls_begin();
9495 }
9496 }
9497
Richard Smitha0ce9c42014-07-29 23:23:27 +00009498 // For each declaration from a merged context, check that the canonical
9499 // definition of that context also contains a declaration of the same
9500 // entity.
9501 //
9502 // Caution: this loop does things that might invalidate iterators into
9503 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9504 while (!PendingOdrMergeChecks.empty()) {
9505 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9506
9507 // FIXME: Skip over implicit declarations for now. This matters for things
9508 // like implicitly-declared special member functions. This isn't entirely
9509 // correct; we can end up with multiple unmerged declarations of the same
9510 // implicit entity.
9511 if (D->isImplicit())
9512 continue;
9513
9514 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009515
9516 bool Found = false;
9517 const Decl *DCanon = D->getCanonicalDecl();
9518
Richard Smith01bdb7a2014-08-28 05:44:07 +00009519 for (auto RI : D->redecls()) {
9520 if (RI->getLexicalDeclContext() == CanonDef) {
9521 Found = true;
9522 break;
9523 }
9524 }
9525 if (Found)
9526 continue;
9527
Richard Smith0f4e2c42015-08-06 04:23:48 +00009528 // Quick check failed, time to do the slow thing. Note, we can't just
9529 // look up the name of D in CanonDef here, because the member that is
9530 // in CanonDef might not be found by name lookup (it might have been
9531 // replaced by a more recent declaration in the lookup table), and we
9532 // can't necessarily find it in the redeclaration chain because it might
9533 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009534 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009535 for (auto *CanonMember : CanonDef->decls()) {
9536 if (CanonMember->getCanonicalDecl() == DCanon) {
9537 // This can happen if the declaration is merely mergeable and not
9538 // actually redeclarable (we looked for redeclarations earlier).
9539 //
9540 // FIXME: We should be able to detect this more efficiently, without
9541 // pulling in all of the members of CanonDef.
9542 Found = true;
9543 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009544 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009545 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9546 if (ND->getDeclName() == D->getDeclName())
9547 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009548 }
9549
9550 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009551 // The AST doesn't like TagDecls becoming invalid after they've been
9552 // completed. We only really need to mark FieldDecls as invalid here.
9553 if (!isa<TagDecl>(D))
9554 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009555
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009556 // Ensure we don't accidentally recursively enter deserialization while
9557 // we're producing our diagnostic.
9558 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009559
9560 std::string CanonDefModule =
9561 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9562 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9563 << D << getOwningModuleNameForDiagnostic(D)
9564 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9565
9566 if (Candidates.empty())
9567 Diag(cast<Decl>(CanonDef)->getLocation(),
9568 diag::note_module_odr_violation_no_possible_decls) << D;
9569 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009570 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9571 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009572 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009573 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009574 }
9575
9576 DiagnosedOdrMergeFailures.insert(CanonDef);
9577 }
9578 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009579
Richard Trieuab4d7302018-07-25 22:52:05 +00009580 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
9581 EnumOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009582 return;
9583
9584 // Ensure we don't accidentally recursively enter deserialization while
9585 // we're producing our diagnostics.
9586 Deserializing RecursionGuard(this);
9587
Richard Trieue6caa262017-12-23 00:41:01 +00009588 // Common code for hashing helpers.
9589 ODRHash Hash;
9590 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9591 Hash.clear();
9592 Hash.AddQualType(Ty);
9593 return Hash.CalculateHash();
9594 };
9595
9596 auto ComputeODRHash = [&Hash](const Stmt *S) {
9597 assert(S);
9598 Hash.clear();
9599 Hash.AddStmt(S);
9600 return Hash.CalculateHash();
9601 };
9602
9603 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9604 assert(D);
9605 Hash.clear();
9606 Hash.AddSubDecl(D);
9607 return Hash.CalculateHash();
9608 };
9609
Richard Trieu7282d322018-04-25 00:31:15 +00009610 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9611 Hash.clear();
9612 Hash.AddTemplateArgument(TA);
9613 return Hash.CalculateHash();
9614 };
9615
Richard Trieu9359e8f2018-05-30 01:12:26 +00009616 auto ComputeTemplateParameterListODRHash =
9617 [&Hash](const TemplateParameterList *TPL) {
9618 assert(TPL);
9619 Hash.clear();
9620 Hash.AddTemplateParameterList(TPL);
9621 return Hash.CalculateHash();
9622 };
9623
Richard Smithcd45dbc2014-04-19 03:48:30 +00009624 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009625 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009626 // If we've already pointed out a specific problem with this class, don't
9627 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009628 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009629 continue;
9630
9631 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009632 CXXRecordDecl *FirstRecord = Merge.first;
9633 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009634 for (auto &RecordPair : Merge.second) {
9635 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009636 // Multiple different declarations got merged together; tell the user
9637 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009638 if (FirstRecord == SecondRecord)
9639 continue;
9640
9641 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009642
9643 auto *FirstDD = FirstRecord->DefinitionData;
9644 auto *SecondDD = RecordPair.second;
9645
9646 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9647
9648 // Diagnostics from DefinitionData are emitted here.
9649 if (FirstDD != SecondDD) {
9650 enum ODRDefinitionDataDifference {
9651 NumBases,
9652 NumVBases,
9653 BaseType,
9654 BaseVirtual,
9655 BaseAccess,
9656 };
9657 auto ODRDiagError = [FirstRecord, &FirstModule,
9658 this](SourceLocation Loc, SourceRange Range,
9659 ODRDefinitionDataDifference DiffType) {
9660 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9661 << FirstRecord << FirstModule.empty() << FirstModule << Range
9662 << DiffType;
9663 };
9664 auto ODRDiagNote = [&SecondModule,
9665 this](SourceLocation Loc, SourceRange Range,
9666 ODRDefinitionDataDifference DiffType) {
9667 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9668 << SecondModule << Range << DiffType;
9669 };
9670
Richard Trieue13eabe2017-09-30 02:19:17 +00009671 unsigned FirstNumBases = FirstDD->NumBases;
9672 unsigned FirstNumVBases = FirstDD->NumVBases;
9673 unsigned SecondNumBases = SecondDD->NumBases;
9674 unsigned SecondNumVBases = SecondDD->NumVBases;
9675
9676 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9677 unsigned NumBases = DD->NumBases;
9678 if (NumBases == 0) return SourceRange();
9679 auto bases = DD->bases();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009680 return SourceRange(bases[0].getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009681 bases[NumBases - 1].getEndLoc());
Richard Trieue13eabe2017-09-30 02:19:17 +00009682 };
9683
9684 if (FirstNumBases != SecondNumBases) {
9685 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9686 NumBases)
9687 << FirstNumBases;
9688 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9689 NumBases)
9690 << SecondNumBases;
9691 Diagnosed = true;
9692 break;
9693 }
9694
9695 if (FirstNumVBases != SecondNumVBases) {
9696 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9697 NumVBases)
9698 << FirstNumVBases;
9699 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9700 NumVBases)
9701 << SecondNumVBases;
9702 Diagnosed = true;
9703 break;
9704 }
9705
9706 auto FirstBases = FirstDD->bases();
9707 auto SecondBases = SecondDD->bases();
9708 unsigned i = 0;
9709 for (i = 0; i < FirstNumBases; ++i) {
9710 auto FirstBase = FirstBases[i];
9711 auto SecondBase = SecondBases[i];
9712 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9713 ComputeQualTypeODRHash(SecondBase.getType())) {
9714 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9715 BaseType)
9716 << (i + 1) << FirstBase.getType();
9717 ODRDiagNote(SecondRecord->getLocation(),
9718 SecondBase.getSourceRange(), BaseType)
9719 << (i + 1) << SecondBase.getType();
9720 break;
9721 }
9722
9723 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9724 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9725 BaseVirtual)
9726 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9727 ODRDiagNote(SecondRecord->getLocation(),
9728 SecondBase.getSourceRange(), BaseVirtual)
9729 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9730 break;
9731 }
9732
9733 if (FirstBase.getAccessSpecifierAsWritten() !=
9734 SecondBase.getAccessSpecifierAsWritten()) {
9735 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9736 BaseAccess)
9737 << (i + 1) << FirstBase.getType()
9738 << (int)FirstBase.getAccessSpecifierAsWritten();
9739 ODRDiagNote(SecondRecord->getLocation(),
9740 SecondBase.getSourceRange(), BaseAccess)
9741 << (i + 1) << SecondBase.getType()
9742 << (int)SecondBase.getAccessSpecifierAsWritten();
9743 break;
9744 }
9745 }
9746
9747 if (i != FirstNumBases) {
9748 Diagnosed = true;
9749 break;
9750 }
9751 }
9752
Richard Trieue7f7ed22017-02-22 01:11:25 +00009753 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009754
9755 const ClassTemplateDecl *FirstTemplate =
9756 FirstRecord->getDescribedClassTemplate();
9757 const ClassTemplateDecl *SecondTemplate =
9758 SecondRecord->getDescribedClassTemplate();
9759
9760 assert(!FirstTemplate == !SecondTemplate &&
9761 "Both pointers should be null or non-null");
9762
9763 enum ODRTemplateDifference {
9764 ParamEmptyName,
9765 ParamName,
9766 ParamSingleDefaultArgument,
9767 ParamDifferentDefaultArgument,
9768 };
9769
9770 if (FirstTemplate && SecondTemplate) {
9771 DeclHashes FirstTemplateHashes;
9772 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009773
9774 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009775 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9776 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009777 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009778 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009779 }
9780 };
9781
9782 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9783 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9784
9785 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9786 "Number of template parameters should be equal.");
9787
9788 auto FirstIt = FirstTemplateHashes.begin();
9789 auto FirstEnd = FirstTemplateHashes.end();
9790 auto SecondIt = SecondTemplateHashes.begin();
9791 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9792 if (FirstIt->second == SecondIt->second)
9793 continue;
9794
9795 auto ODRDiagError = [FirstRecord, &FirstModule,
9796 this](SourceLocation Loc, SourceRange Range,
9797 ODRTemplateDifference DiffType) {
9798 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9799 << FirstRecord << FirstModule.empty() << FirstModule << Range
9800 << DiffType;
9801 };
9802 auto ODRDiagNote = [&SecondModule,
9803 this](SourceLocation Loc, SourceRange Range,
9804 ODRTemplateDifference DiffType) {
9805 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9806 << SecondModule << Range << DiffType;
9807 };
9808
Vedant Kumar48b4f762018-04-14 01:40:48 +00009809 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9810 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009811
9812 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9813 "Parameter Decl's should be the same kind.");
9814
9815 DeclarationName FirstName = FirstDecl->getDeclName();
9816 DeclarationName SecondName = SecondDecl->getDeclName();
9817
9818 if (FirstName != SecondName) {
9819 const bool FirstNameEmpty =
9820 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9821 const bool SecondNameEmpty =
9822 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9823 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9824 "Both template parameters cannot be unnamed.");
9825 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9826 FirstNameEmpty ? ParamEmptyName : ParamName)
9827 << FirstName;
9828 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9829 SecondNameEmpty ? ParamEmptyName : ParamName)
9830 << SecondName;
9831 break;
9832 }
9833
9834 switch (FirstDecl->getKind()) {
9835 default:
9836 llvm_unreachable("Invalid template parameter type.");
9837 case Decl::TemplateTypeParm: {
9838 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9839 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9840 const bool HasFirstDefaultArgument =
9841 FirstParam->hasDefaultArgument() &&
9842 !FirstParam->defaultArgumentWasInherited();
9843 const bool HasSecondDefaultArgument =
9844 SecondParam->hasDefaultArgument() &&
9845 !SecondParam->defaultArgumentWasInherited();
9846
9847 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9848 ODRDiagError(FirstDecl->getLocation(),
9849 FirstDecl->getSourceRange(),
9850 ParamSingleDefaultArgument)
9851 << HasFirstDefaultArgument;
9852 ODRDiagNote(SecondDecl->getLocation(),
9853 SecondDecl->getSourceRange(),
9854 ParamSingleDefaultArgument)
9855 << HasSecondDefaultArgument;
9856 break;
9857 }
9858
9859 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9860 "Expecting default arguments.");
9861
9862 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9863 ParamDifferentDefaultArgument);
9864 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9865 ParamDifferentDefaultArgument);
9866
9867 break;
9868 }
9869 case Decl::NonTypeTemplateParm: {
9870 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9871 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9872 const bool HasFirstDefaultArgument =
9873 FirstParam->hasDefaultArgument() &&
9874 !FirstParam->defaultArgumentWasInherited();
9875 const bool HasSecondDefaultArgument =
9876 SecondParam->hasDefaultArgument() &&
9877 !SecondParam->defaultArgumentWasInherited();
9878
9879 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9880 ODRDiagError(FirstDecl->getLocation(),
9881 FirstDecl->getSourceRange(),
9882 ParamSingleDefaultArgument)
9883 << HasFirstDefaultArgument;
9884 ODRDiagNote(SecondDecl->getLocation(),
9885 SecondDecl->getSourceRange(),
9886 ParamSingleDefaultArgument)
9887 << HasSecondDefaultArgument;
9888 break;
9889 }
9890
9891 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9892 "Expecting default arguments.");
9893
9894 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9895 ParamDifferentDefaultArgument);
9896 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9897 ParamDifferentDefaultArgument);
9898
9899 break;
9900 }
9901 case Decl::TemplateTemplateParm: {
9902 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9903 const auto *SecondParam =
9904 cast<TemplateTemplateParmDecl>(SecondDecl);
9905 const bool HasFirstDefaultArgument =
9906 FirstParam->hasDefaultArgument() &&
9907 !FirstParam->defaultArgumentWasInherited();
9908 const bool HasSecondDefaultArgument =
9909 SecondParam->hasDefaultArgument() &&
9910 !SecondParam->defaultArgumentWasInherited();
9911
9912 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9913 ODRDiagError(FirstDecl->getLocation(),
9914 FirstDecl->getSourceRange(),
9915 ParamSingleDefaultArgument)
9916 << HasFirstDefaultArgument;
9917 ODRDiagNote(SecondDecl->getLocation(),
9918 SecondDecl->getSourceRange(),
9919 ParamSingleDefaultArgument)
9920 << HasSecondDefaultArgument;
9921 break;
9922 }
9923
9924 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9925 "Expecting default arguments.");
9926
9927 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9928 ParamDifferentDefaultArgument);
9929 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9930 ParamDifferentDefaultArgument);
9931
9932 break;
9933 }
9934 }
9935
9936 break;
9937 }
9938
9939 if (FirstIt != FirstEnd) {
9940 Diagnosed = true;
9941 break;
9942 }
9943 }
9944
Richard Trieue7f7ed22017-02-22 01:11:25 +00009945 DeclHashes FirstHashes;
9946 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009947
Richard Trieue6caa262017-12-23 00:41:01 +00009948 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9949 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009950 for (auto *D : Record->decls()) {
9951 // Due to decl merging, the first CXXRecordDecl is the parent of
9952 // Decls in both records.
9953 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9954 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009955 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009956 }
9957 };
9958 PopulateHashes(FirstHashes, FirstRecord);
9959 PopulateHashes(SecondHashes, SecondRecord);
9960
9961 // Used with err_module_odr_violation_mismatch_decl and
9962 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009963 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009964 enum {
9965 EndOfClass,
9966 PublicSpecifer,
9967 PrivateSpecifer,
9968 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009969 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009970 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009971 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009972 TypeAlias,
9973 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009974 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009975 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009976 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009977 Other
9978 } FirstDiffType = Other,
9979 SecondDiffType = Other;
9980
9981 auto DifferenceSelector = [](Decl *D) {
9982 assert(D && "valid Decl required");
9983 switch (D->getKind()) {
9984 default:
9985 return Other;
9986 case Decl::AccessSpec:
9987 switch (D->getAccess()) {
9988 case AS_public:
9989 return PublicSpecifer;
9990 case AS_private:
9991 return PrivateSpecifer;
9992 case AS_protected:
9993 return ProtectedSpecifer;
9994 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009995 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009996 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009997 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009998 case Decl::StaticAssert:
9999 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +000010000 case Decl::Field:
10001 return Field;
Richard Trieu48143742017-02-28 21:24:38 +000010002 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +000010003 case Decl::CXXConstructor:
10004 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +000010005 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +000010006 case Decl::TypeAlias:
10007 return TypeAlias;
10008 case Decl::Typedef:
10009 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +000010010 case Decl::Var:
10011 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +000010012 case Decl::Friend:
10013 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +000010014 case Decl::FunctionTemplate:
10015 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +000010016 }
10017 };
10018
10019 Decl *FirstDecl = nullptr;
10020 Decl *SecondDecl = nullptr;
10021 auto FirstIt = FirstHashes.begin();
10022 auto SecondIt = SecondHashes.begin();
10023
10024 // If there is a diagnoseable difference, FirstDiffType and
10025 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
10026 // filled in if not EndOfClass.
10027 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +000010028 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
10029 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +000010030 ++FirstIt;
10031 ++SecondIt;
10032 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +000010033 }
Richard Smithcd45dbc2014-04-19 03:48:30 +000010034
Richard Trieue7f7ed22017-02-22 01:11:25 +000010035 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
10036 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
10037
10038 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
10039 SecondDiffType =
10040 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
10041
10042 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010043 }
Richard Trieue7f7ed22017-02-22 01:11:25 +000010044
10045 if (FirstDiffType == Other || SecondDiffType == Other) {
10046 // Reaching this point means an unexpected Decl was encountered
10047 // or no difference was detected. This causes a generic error
10048 // message to be emitted.
10049 Diag(FirstRecord->getLocation(),
10050 diag::err_module_odr_violation_different_definitions)
10051 << FirstRecord << FirstModule.empty() << FirstModule;
10052
Richard Trieuca48d362017-06-21 01:43:13 +000010053 if (FirstDecl) {
10054 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
10055 << FirstRecord << FirstDecl->getSourceRange();
10056 }
10057
Richard Trieue7f7ed22017-02-22 01:11:25 +000010058 Diag(SecondRecord->getLocation(),
10059 diag::note_module_odr_violation_different_definitions)
10060 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +000010061
10062 if (SecondDecl) {
10063 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
10064 << SecondDecl->getSourceRange();
10065 }
10066
Richard Trieue7f7ed22017-02-22 01:11:25 +000010067 Diagnosed = true;
10068 break;
10069 }
10070
10071 if (FirstDiffType != SecondDiffType) {
10072 SourceLocation FirstLoc;
10073 SourceRange FirstRange;
10074 if (FirstDiffType == EndOfClass) {
10075 FirstLoc = FirstRecord->getBraceRange().getEnd();
10076 } else {
10077 FirstLoc = FirstIt->first->getLocation();
10078 FirstRange = FirstIt->first->getSourceRange();
10079 }
10080 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
10081 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
10082 << FirstDiffType;
10083
10084 SourceLocation SecondLoc;
10085 SourceRange SecondRange;
10086 if (SecondDiffType == EndOfClass) {
10087 SecondLoc = SecondRecord->getBraceRange().getEnd();
10088 } else {
10089 SecondLoc = SecondDecl->getLocation();
10090 SecondRange = SecondDecl->getSourceRange();
10091 }
10092 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
10093 << SecondModule << SecondRange << SecondDiffType;
10094 Diagnosed = true;
10095 break;
10096 }
10097
Richard Trieu639d7b62017-02-22 22:22:42 +000010098 assert(FirstDiffType == SecondDiffType);
10099
10100 // Used with err_module_odr_violation_mismatch_decl_diff and
10101 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +000010102 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +000010103 StaticAssertCondition,
10104 StaticAssertMessage,
10105 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +000010106 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +000010107 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +000010108 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +000010109 FieldDifferentWidthBitField,
10110 FieldSingleMutable,
10111 FieldSingleInitializer,
10112 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +000010113 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +000010114 MethodDeleted,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010115 MethodDefaulted,
Richard Trieu583e2c12017-03-04 00:08:58 +000010116 MethodVirtual,
10117 MethodStatic,
10118 MethodVolatile,
10119 MethodConst,
10120 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +000010121 MethodNumberParameters,
10122 MethodParameterType,
10123 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010124 MethodParameterSingleDefaultArgument,
10125 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +000010126 MethodNoTemplateArguments,
10127 MethodDifferentNumberTemplateArguments,
10128 MethodDifferentTemplateArgument,
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010129 MethodSingleBody,
10130 MethodDifferentBody,
Richard Trieu11d566a2017-06-12 21:58:22 +000010131 TypedefName,
10132 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +000010133 VarName,
10134 VarType,
10135 VarSingleInitializer,
10136 VarDifferentInitializer,
10137 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010138 FriendTypeFunction,
10139 FriendType,
10140 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010141 FunctionTemplateDifferentNumberParameters,
10142 FunctionTemplateParameterDifferentKind,
10143 FunctionTemplateParameterName,
10144 FunctionTemplateParameterSingleDefaultArgument,
10145 FunctionTemplateParameterDifferentDefaultArgument,
10146 FunctionTemplateParameterDifferentType,
10147 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010148 };
10149
10150 // These lambdas have the common portions of the ODR diagnostics. This
10151 // has the same return as Diag(), so addition parameters can be passed
10152 // in with operator<<
10153 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10154 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10155 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10156 << FirstRecord << FirstModule.empty() << FirstModule << Range
10157 << DiffType;
10158 };
10159 auto ODRDiagNote = [&SecondModule, this](
10160 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10161 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10162 << SecondModule << Range << DiffType;
10163 };
10164
Richard Trieu639d7b62017-02-22 22:22:42 +000010165 switch (FirstDiffType) {
10166 case Other:
10167 case EndOfClass:
10168 case PublicSpecifer:
10169 case PrivateSpecifer:
10170 case ProtectedSpecifer:
10171 llvm_unreachable("Invalid diff type");
10172
10173 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010174 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10175 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010176
10177 Expr *FirstExpr = FirstSA->getAssertExpr();
10178 Expr *SecondExpr = SecondSA->getAssertExpr();
10179 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10180 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10181 if (FirstODRHash != SecondODRHash) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010182 ODRDiagError(FirstExpr->getBeginLoc(), FirstExpr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010183 StaticAssertCondition);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010184 ODRDiagNote(SecondExpr->getBeginLoc(), SecondExpr->getSourceRange(),
10185 StaticAssertCondition);
Richard Trieu639d7b62017-02-22 22:22:42 +000010186 Diagnosed = true;
10187 break;
10188 }
10189
10190 StringLiteral *FirstStr = FirstSA->getMessage();
10191 StringLiteral *SecondStr = SecondSA->getMessage();
10192 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10193 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10194 SourceLocation FirstLoc, SecondLoc;
10195 SourceRange FirstRange, SecondRange;
10196 if (FirstStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010197 FirstLoc = FirstStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010198 FirstRange = FirstStr->getSourceRange();
10199 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010200 FirstLoc = FirstSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010201 FirstRange = FirstSA->getSourceRange();
10202 }
10203 if (SecondStr) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010204 SecondLoc = SecondStr->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010205 SecondRange = SecondStr->getSourceRange();
10206 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010207 SecondLoc = SecondSA->getBeginLoc();
Richard Trieu639d7b62017-02-22 22:22:42 +000010208 SecondRange = SecondSA->getSourceRange();
10209 }
10210 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10211 << (FirstStr == nullptr);
10212 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10213 << (SecondStr == nullptr);
10214 Diagnosed = true;
10215 break;
10216 }
10217
10218 if (FirstStr && SecondStr &&
10219 FirstStr->getString() != SecondStr->getString()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010220 ODRDiagError(FirstStr->getBeginLoc(), FirstStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010221 StaticAssertMessage);
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010222 ODRDiagNote(SecondStr->getBeginLoc(), SecondStr->getSourceRange(),
Richard Trieu639d7b62017-02-22 22:22:42 +000010223 StaticAssertMessage);
10224 Diagnosed = true;
10225 break;
10226 }
10227 break;
10228 }
Richard Trieud0786092017-02-23 00:23:01 +000010229 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010230 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10231 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010232 IdentifierInfo *FirstII = FirstField->getIdentifier();
10233 IdentifierInfo *SecondII = SecondField->getIdentifier();
10234 if (FirstII->getName() != SecondII->getName()) {
10235 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10236 FieldName)
10237 << FirstII;
10238 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10239 FieldName)
10240 << SecondII;
10241
10242 Diagnosed = true;
10243 break;
10244 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010245
Richard Smithdbafb6c2017-06-29 23:23:46 +000010246 assert(getContext().hasSameType(FirstField->getType(),
10247 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010248
10249 QualType FirstType = FirstField->getType();
10250 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010251 if (ComputeQualTypeODRHash(FirstType) !=
10252 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010253 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10254 FieldTypeName)
10255 << FirstII << FirstType;
10256 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10257 FieldTypeName)
10258 << SecondII << SecondType;
10259
10260 Diagnosed = true;
10261 break;
10262 }
10263
Richard Trieu93772fc2017-02-24 20:59:28 +000010264 const bool IsFirstBitField = FirstField->isBitField();
10265 const bool IsSecondBitField = SecondField->isBitField();
10266 if (IsFirstBitField != IsSecondBitField) {
10267 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10268 FieldSingleBitField)
10269 << FirstII << IsFirstBitField;
10270 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10271 FieldSingleBitField)
10272 << SecondII << IsSecondBitField;
10273 Diagnosed = true;
10274 break;
10275 }
10276
10277 if (IsFirstBitField && IsSecondBitField) {
10278 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10279 FieldDifferentWidthBitField)
10280 << FirstII << FirstField->getBitWidth()->getSourceRange();
10281 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10282 FieldDifferentWidthBitField)
10283 << SecondII << SecondField->getBitWidth()->getSourceRange();
10284 Diagnosed = true;
10285 break;
10286 }
10287
Richard Trieu8d543e22017-02-24 23:35:37 +000010288 const bool IsFirstMutable = FirstField->isMutable();
10289 const bool IsSecondMutable = SecondField->isMutable();
10290 if (IsFirstMutable != IsSecondMutable) {
10291 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10292 FieldSingleMutable)
10293 << FirstII << IsFirstMutable;
10294 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10295 FieldSingleMutable)
10296 << SecondII << IsSecondMutable;
10297 Diagnosed = true;
10298 break;
10299 }
10300
10301 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10302 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10303 if ((!FirstInitializer && SecondInitializer) ||
10304 (FirstInitializer && !SecondInitializer)) {
10305 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10306 FieldSingleInitializer)
10307 << FirstII << (FirstInitializer != nullptr);
10308 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10309 FieldSingleInitializer)
10310 << SecondII << (SecondInitializer != nullptr);
10311 Diagnosed = true;
10312 break;
10313 }
10314
10315 if (FirstInitializer && SecondInitializer) {
10316 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10317 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10318 if (FirstInitHash != SecondInitHash) {
10319 ODRDiagError(FirstField->getLocation(),
10320 FirstField->getSourceRange(),
10321 FieldDifferentInitializers)
10322 << FirstII << FirstInitializer->getSourceRange();
10323 ODRDiagNote(SecondField->getLocation(),
10324 SecondField->getSourceRange(),
10325 FieldDifferentInitializers)
10326 << SecondII << SecondInitializer->getSourceRange();
10327 Diagnosed = true;
10328 break;
10329 }
10330 }
10331
Richard Trieud0786092017-02-23 00:23:01 +000010332 break;
10333 }
Richard Trieu48143742017-02-28 21:24:38 +000010334 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010335 enum {
10336 DiagMethod,
10337 DiagConstructor,
10338 DiagDestructor,
10339 } FirstMethodType,
10340 SecondMethodType;
10341 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10342 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10343 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10344 return DiagMethod;
10345 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010346 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10347 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010348 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10349 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010350 auto FirstName = FirstMethod->getDeclName();
10351 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010352 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010353 ODRDiagError(FirstMethod->getLocation(),
10354 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010355 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010356 ODRDiagNote(SecondMethod->getLocation(),
10357 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010358 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010359
10360 Diagnosed = true;
10361 break;
10362 }
10363
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010364 const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
10365 const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
Richard Trieu583e2c12017-03-04 00:08:58 +000010366 if (FirstDeleted != SecondDeleted) {
10367 ODRDiagError(FirstMethod->getLocation(),
10368 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010369 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010370
10371 ODRDiagNote(SecondMethod->getLocation(),
10372 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010373 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010374 Diagnosed = true;
10375 break;
10376 }
10377
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010378 const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
10379 const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
10380 if (FirstDefaulted != SecondDefaulted) {
10381 ODRDiagError(FirstMethod->getLocation(),
10382 FirstMethod->getSourceRange(), MethodDefaulted)
10383 << FirstMethodType << FirstName << FirstDefaulted;
10384
10385 ODRDiagNote(SecondMethod->getLocation(),
10386 SecondMethod->getSourceRange(), MethodDefaulted)
10387 << SecondMethodType << SecondName << SecondDefaulted;
10388 Diagnosed = true;
10389 break;
10390 }
10391
Richard Trieu583e2c12017-03-04 00:08:58 +000010392 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10393 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10394 const bool FirstPure = FirstMethod->isPure();
10395 const bool SecondPure = SecondMethod->isPure();
10396 if ((FirstVirtual || SecondVirtual) &&
10397 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10398 ODRDiagError(FirstMethod->getLocation(),
10399 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010400 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010401 ODRDiagNote(SecondMethod->getLocation(),
10402 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010403 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010404 Diagnosed = true;
10405 break;
10406 }
10407
10408 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10409 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10410 // class needs to be checked instead.
10411 const auto FirstStorage = FirstMethod->getStorageClass();
10412 const auto SecondStorage = SecondMethod->getStorageClass();
10413 const bool FirstStatic = FirstStorage == SC_Static;
10414 const bool SecondStatic = SecondStorage == SC_Static;
10415 if (FirstStatic != SecondStatic) {
10416 ODRDiagError(FirstMethod->getLocation(),
10417 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010418 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010419 ODRDiagNote(SecondMethod->getLocation(),
10420 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010421 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010422 Diagnosed = true;
10423 break;
10424 }
10425
10426 const bool FirstVolatile = FirstMethod->isVolatile();
10427 const bool SecondVolatile = SecondMethod->isVolatile();
10428 if (FirstVolatile != SecondVolatile) {
10429 ODRDiagError(FirstMethod->getLocation(),
10430 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010431 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010432 ODRDiagNote(SecondMethod->getLocation(),
10433 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010434 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010435 Diagnosed = true;
10436 break;
10437 }
10438
10439 const bool FirstConst = FirstMethod->isConst();
10440 const bool SecondConst = SecondMethod->isConst();
10441 if (FirstConst != SecondConst) {
10442 ODRDiagError(FirstMethod->getLocation(),
10443 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010444 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010445 ODRDiagNote(SecondMethod->getLocation(),
10446 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010447 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010448 Diagnosed = true;
10449 break;
10450 }
10451
10452 const bool FirstInline = FirstMethod->isInlineSpecified();
10453 const bool SecondInline = SecondMethod->isInlineSpecified();
10454 if (FirstInline != SecondInline) {
10455 ODRDiagError(FirstMethod->getLocation(),
10456 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010457 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010458 ODRDiagNote(SecondMethod->getLocation(),
10459 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010460 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010461 Diagnosed = true;
10462 break;
10463 }
10464
Richard Trieu02552272017-05-02 23:58:52 +000010465 const unsigned FirstNumParameters = FirstMethod->param_size();
10466 const unsigned SecondNumParameters = SecondMethod->param_size();
10467 if (FirstNumParameters != SecondNumParameters) {
10468 ODRDiagError(FirstMethod->getLocation(),
10469 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010470 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010471 ODRDiagNote(SecondMethod->getLocation(),
10472 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010473 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010474 Diagnosed = true;
10475 break;
10476 }
10477
10478 // Need this status boolean to know when break out of the switch.
10479 bool ParameterMismatch = false;
10480 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10481 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10482 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10483
10484 QualType FirstParamType = FirstParam->getType();
10485 QualType SecondParamType = SecondParam->getType();
10486 if (FirstParamType != SecondParamType &&
10487 ComputeQualTypeODRHash(FirstParamType) !=
10488 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010489 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010490 FirstParamType->getAs<DecayedType>()) {
10491 ODRDiagError(FirstMethod->getLocation(),
10492 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010493 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10494 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010495 } else {
10496 ODRDiagError(FirstMethod->getLocation(),
10497 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010498 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10499 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010500 }
10501
Vedant Kumar48b4f762018-04-14 01:40:48 +000010502 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010503 SecondParamType->getAs<DecayedType>()) {
10504 ODRDiagNote(SecondMethod->getLocation(),
10505 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010506 << SecondMethodType << SecondName << (I + 1)
10507 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010508 << ParamDecayedType->getOriginalType();
10509 } else {
10510 ODRDiagNote(SecondMethod->getLocation(),
10511 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010512 << SecondMethodType << SecondName << (I + 1)
10513 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010514 }
10515 ParameterMismatch = true;
10516 break;
10517 }
10518
10519 DeclarationName FirstParamName = FirstParam->getDeclName();
10520 DeclarationName SecondParamName = SecondParam->getDeclName();
10521 if (FirstParamName != SecondParamName) {
10522 ODRDiagError(FirstMethod->getLocation(),
10523 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010524 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010525 ODRDiagNote(SecondMethod->getLocation(),
10526 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010527 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010528 ParameterMismatch = true;
10529 break;
10530 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010531
10532 const Expr *FirstInit = FirstParam->getInit();
10533 const Expr *SecondInit = SecondParam->getInit();
10534 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10535 ODRDiagError(FirstMethod->getLocation(),
10536 FirstMethod->getSourceRange(),
10537 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010538 << FirstMethodType << FirstName << (I + 1)
10539 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010540 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10541 ODRDiagNote(SecondMethod->getLocation(),
10542 SecondMethod->getSourceRange(),
10543 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010544 << SecondMethodType << SecondName << (I + 1)
10545 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010546 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10547 ParameterMismatch = true;
10548 break;
10549 }
10550
10551 if (FirstInit && SecondInit &&
10552 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10553 ODRDiagError(FirstMethod->getLocation(),
10554 FirstMethod->getSourceRange(),
10555 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010556 << FirstMethodType << FirstName << (I + 1)
10557 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010558 ODRDiagNote(SecondMethod->getLocation(),
10559 SecondMethod->getSourceRange(),
10560 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010561 << SecondMethodType << SecondName << (I + 1)
10562 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010563 ParameterMismatch = true;
10564 break;
10565
10566 }
Richard Trieu02552272017-05-02 23:58:52 +000010567 }
10568
10569 if (ParameterMismatch) {
10570 Diagnosed = true;
10571 break;
10572 }
10573
Richard Trieu7282d322018-04-25 00:31:15 +000010574 const auto *FirstTemplateArgs =
10575 FirstMethod->getTemplateSpecializationArgs();
10576 const auto *SecondTemplateArgs =
10577 SecondMethod->getTemplateSpecializationArgs();
10578
10579 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10580 (!FirstTemplateArgs && SecondTemplateArgs)) {
10581 ODRDiagError(FirstMethod->getLocation(),
10582 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10583 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10584 ODRDiagNote(SecondMethod->getLocation(),
10585 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10586 << SecondMethodType << SecondName
10587 << (SecondTemplateArgs != nullptr);
10588
10589 Diagnosed = true;
10590 break;
10591 }
10592
10593 if (FirstTemplateArgs && SecondTemplateArgs) {
10594 // Remove pack expansions from argument list.
10595 auto ExpandTemplateArgumentList =
10596 [](const TemplateArgumentList *TAL) {
10597 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10598 for (const TemplateArgument &TA : TAL->asArray()) {
10599 if (TA.getKind() != TemplateArgument::Pack) {
10600 ExpandedList.push_back(&TA);
10601 continue;
10602 }
10603 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10604 ExpandedList.push_back(&PackTA);
10605 }
10606 }
10607 return ExpandedList;
10608 };
10609 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10610 ExpandTemplateArgumentList(FirstTemplateArgs);
10611 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10612 ExpandTemplateArgumentList(SecondTemplateArgs);
10613
10614 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10615 ODRDiagError(FirstMethod->getLocation(),
10616 FirstMethod->getSourceRange(),
10617 MethodDifferentNumberTemplateArguments)
10618 << FirstMethodType << FirstName
10619 << (unsigned)FirstExpandedList.size();
10620 ODRDiagNote(SecondMethod->getLocation(),
10621 SecondMethod->getSourceRange(),
10622 MethodDifferentNumberTemplateArguments)
10623 << SecondMethodType << SecondName
10624 << (unsigned)SecondExpandedList.size();
10625
10626 Diagnosed = true;
10627 break;
10628 }
10629
10630 bool TemplateArgumentMismatch = false;
10631 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10632 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10633 &SecondTA = *SecondExpandedList[i];
10634 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10635 ComputeTemplateArgumentODRHash(SecondTA)) {
10636 continue;
10637 }
10638
10639 ODRDiagError(FirstMethod->getLocation(),
10640 FirstMethod->getSourceRange(),
10641 MethodDifferentTemplateArgument)
10642 << FirstMethodType << FirstName << FirstTA << i + 1;
10643 ODRDiagNote(SecondMethod->getLocation(),
10644 SecondMethod->getSourceRange(),
10645 MethodDifferentTemplateArgument)
10646 << SecondMethodType << SecondName << SecondTA << i + 1;
10647
10648 TemplateArgumentMismatch = true;
10649 break;
10650 }
10651
10652 if (TemplateArgumentMismatch) {
10653 Diagnosed = true;
10654 break;
10655 }
10656 }
Richard Trieu27c1b1a2018-07-10 01:40:50 +000010657
10658 // Compute the hash of the method as if it has no body.
10659 auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
10660 Hash.clear();
10661 Hash.AddFunctionDecl(D, true /*SkipBody*/);
10662 return Hash.CalculateHash();
10663 };
10664
10665 // Compare the hash generated to the hash stored. A difference means
10666 // that a body was present in the original source. Due to merging,
10667 // the stardard way of detecting a body will not work.
10668 const bool HasFirstBody =
10669 ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
10670 const bool HasSecondBody =
10671 ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
10672
10673 if (HasFirstBody != HasSecondBody) {
10674 ODRDiagError(FirstMethod->getLocation(),
10675 FirstMethod->getSourceRange(), MethodSingleBody)
10676 << FirstMethodType << FirstName << HasFirstBody;
10677 ODRDiagNote(SecondMethod->getLocation(),
10678 SecondMethod->getSourceRange(), MethodSingleBody)
10679 << SecondMethodType << SecondName << HasSecondBody;
10680 Diagnosed = true;
10681 break;
10682 }
10683
10684 if (HasFirstBody && HasSecondBody) {
10685 ODRDiagError(FirstMethod->getLocation(),
10686 FirstMethod->getSourceRange(), MethodDifferentBody)
10687 << FirstMethodType << FirstName;
10688 ODRDiagNote(SecondMethod->getLocation(),
10689 SecondMethod->getSourceRange(), MethodDifferentBody)
10690 << SecondMethodType << SecondName;
10691 Diagnosed = true;
10692 break;
10693 }
10694
Richard Trieu48143742017-02-28 21:24:38 +000010695 break;
10696 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010697 case TypeAlias:
10698 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010699 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10700 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010701 auto FirstName = FirstTD->getDeclName();
10702 auto SecondName = SecondTD->getDeclName();
10703 if (FirstName != SecondName) {
10704 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10705 TypedefName)
10706 << (FirstDiffType == TypeAlias) << FirstName;
10707 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10708 TypedefName)
10709 << (FirstDiffType == TypeAlias) << SecondName;
10710 Diagnosed = true;
10711 break;
10712 }
10713
10714 QualType FirstType = FirstTD->getUnderlyingType();
10715 QualType SecondType = SecondTD->getUnderlyingType();
10716 if (ComputeQualTypeODRHash(FirstType) !=
10717 ComputeQualTypeODRHash(SecondType)) {
10718 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10719 TypedefType)
10720 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10721 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10722 TypedefType)
10723 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10724 Diagnosed = true;
10725 break;
10726 }
10727 break;
10728 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010729 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010730 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10731 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010732 auto FirstName = FirstVD->getDeclName();
10733 auto SecondName = SecondVD->getDeclName();
10734 if (FirstName != SecondName) {
10735 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10736 VarName)
10737 << FirstName;
10738 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10739 VarName)
10740 << SecondName;
10741 Diagnosed = true;
10742 break;
10743 }
10744
10745 QualType FirstType = FirstVD->getType();
10746 QualType SecondType = SecondVD->getType();
10747 if (ComputeQualTypeODRHash(FirstType) !=
10748 ComputeQualTypeODRHash(SecondType)) {
10749 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10750 VarType)
10751 << FirstName << FirstType;
10752 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10753 VarType)
10754 << SecondName << SecondType;
10755 Diagnosed = true;
10756 break;
10757 }
10758
10759 const Expr *FirstInit = FirstVD->getInit();
10760 const Expr *SecondInit = SecondVD->getInit();
10761 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10762 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10763 VarSingleInitializer)
10764 << FirstName << (FirstInit == nullptr)
10765 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10766 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10767 VarSingleInitializer)
10768 << SecondName << (SecondInit == nullptr)
10769 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10770 Diagnosed = true;
10771 break;
10772 }
10773
10774 if (FirstInit && SecondInit &&
10775 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10776 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10777 VarDifferentInitializer)
10778 << FirstName << FirstInit->getSourceRange();
10779 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10780 VarDifferentInitializer)
10781 << SecondName << SecondInit->getSourceRange();
10782 Diagnosed = true;
10783 break;
10784 }
10785
10786 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10787 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10788 if (FirstIsConstexpr != SecondIsConstexpr) {
10789 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10790 VarConstexpr)
10791 << FirstName << FirstIsConstexpr;
10792 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10793 VarConstexpr)
10794 << SecondName << SecondIsConstexpr;
10795 Diagnosed = true;
10796 break;
10797 }
10798 break;
10799 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010800 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010801 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10802 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010803
10804 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10805 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10806
10807 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10808 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10809
10810 if (FirstND && SecondND) {
10811 ODRDiagError(FirstFriend->getFriendLoc(),
10812 FirstFriend->getSourceRange(), FriendFunction)
10813 << FirstND;
10814 ODRDiagNote(SecondFriend->getFriendLoc(),
10815 SecondFriend->getSourceRange(), FriendFunction)
10816 << SecondND;
10817
10818 Diagnosed = true;
10819 break;
10820 }
10821
10822 if (FirstTSI && SecondTSI) {
10823 QualType FirstFriendType = FirstTSI->getType();
10824 QualType SecondFriendType = SecondTSI->getType();
10825 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10826 ComputeQualTypeODRHash(SecondFriendType));
10827 ODRDiagError(FirstFriend->getFriendLoc(),
10828 FirstFriend->getSourceRange(), FriendType)
10829 << FirstFriendType;
10830 ODRDiagNote(SecondFriend->getFriendLoc(),
10831 SecondFriend->getSourceRange(), FriendType)
10832 << SecondFriendType;
10833 Diagnosed = true;
10834 break;
10835 }
10836
10837 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10838 FriendTypeFunction)
10839 << (FirstTSI == nullptr);
10840 ODRDiagNote(SecondFriend->getFriendLoc(),
10841 SecondFriend->getSourceRange(), FriendTypeFunction)
10842 << (SecondTSI == nullptr);
10843
10844 Diagnosed = true;
10845 break;
10846 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010847 case FunctionTemplate: {
10848 FunctionTemplateDecl *FirstTemplate =
10849 cast<FunctionTemplateDecl>(FirstDecl);
10850 FunctionTemplateDecl *SecondTemplate =
10851 cast<FunctionTemplateDecl>(SecondDecl);
10852
10853 TemplateParameterList *FirstTPL =
10854 FirstTemplate->getTemplateParameters();
10855 TemplateParameterList *SecondTPL =
10856 SecondTemplate->getTemplateParameters();
10857
10858 if (FirstTPL->size() != SecondTPL->size()) {
10859 ODRDiagError(FirstTemplate->getLocation(),
10860 FirstTemplate->getSourceRange(),
10861 FunctionTemplateDifferentNumberParameters)
10862 << FirstTemplate << FirstTPL->size();
10863 ODRDiagNote(SecondTemplate->getLocation(),
10864 SecondTemplate->getSourceRange(),
10865 FunctionTemplateDifferentNumberParameters)
10866 << SecondTemplate << SecondTPL->size();
10867
10868 Diagnosed = true;
10869 break;
10870 }
10871
10872 bool ParameterMismatch = false;
10873 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10874 NamedDecl *FirstParam = FirstTPL->getParam(i);
10875 NamedDecl *SecondParam = SecondTPL->getParam(i);
10876
10877 if (FirstParam->getKind() != SecondParam->getKind()) {
10878 enum {
10879 TemplateTypeParameter,
10880 NonTypeTemplateParameter,
10881 TemplateTemplateParameter,
10882 };
10883 auto GetParamType = [](NamedDecl *D) {
10884 switch (D->getKind()) {
10885 default:
10886 llvm_unreachable("Unexpected template parameter type");
10887 case Decl::TemplateTypeParm:
10888 return TemplateTypeParameter;
10889 case Decl::NonTypeTemplateParm:
10890 return NonTypeTemplateParameter;
10891 case Decl::TemplateTemplateParm:
10892 return TemplateTemplateParameter;
10893 }
10894 };
10895
10896 ODRDiagError(FirstTemplate->getLocation(),
10897 FirstTemplate->getSourceRange(),
10898 FunctionTemplateParameterDifferentKind)
10899 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10900 ODRDiagNote(SecondTemplate->getLocation(),
10901 SecondTemplate->getSourceRange(),
10902 FunctionTemplateParameterDifferentKind)
10903 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10904
10905 ParameterMismatch = true;
10906 break;
10907 }
10908
10909 if (FirstParam->getName() != SecondParam->getName()) {
10910 ODRDiagError(FirstTemplate->getLocation(),
10911 FirstTemplate->getSourceRange(),
10912 FunctionTemplateParameterName)
10913 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10914 << FirstParam;
10915 ODRDiagNote(SecondTemplate->getLocation(),
10916 SecondTemplate->getSourceRange(),
10917 FunctionTemplateParameterName)
10918 << SecondTemplate << (i + 1)
10919 << (bool)SecondParam->getIdentifier() << SecondParam;
10920 ParameterMismatch = true;
10921 break;
10922 }
10923
10924 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10925 isa<TemplateTypeParmDecl>(SecondParam)) {
10926 TemplateTypeParmDecl *FirstTTPD =
10927 cast<TemplateTypeParmDecl>(FirstParam);
10928 TemplateTypeParmDecl *SecondTTPD =
10929 cast<TemplateTypeParmDecl>(SecondParam);
10930 bool HasFirstDefaultArgument =
10931 FirstTTPD->hasDefaultArgument() &&
10932 !FirstTTPD->defaultArgumentWasInherited();
10933 bool HasSecondDefaultArgument =
10934 SecondTTPD->hasDefaultArgument() &&
10935 !SecondTTPD->defaultArgumentWasInherited();
10936 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10937 ODRDiagError(FirstTemplate->getLocation(),
10938 FirstTemplate->getSourceRange(),
10939 FunctionTemplateParameterSingleDefaultArgument)
10940 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10941 ODRDiagNote(SecondTemplate->getLocation(),
10942 SecondTemplate->getSourceRange(),
10943 FunctionTemplateParameterSingleDefaultArgument)
10944 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10945 ParameterMismatch = true;
10946 break;
10947 }
10948
10949 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10950 QualType FirstType = FirstTTPD->getDefaultArgument();
10951 QualType SecondType = SecondTTPD->getDefaultArgument();
10952 if (ComputeQualTypeODRHash(FirstType) !=
10953 ComputeQualTypeODRHash(SecondType)) {
10954 ODRDiagError(FirstTemplate->getLocation(),
10955 FirstTemplate->getSourceRange(),
10956 FunctionTemplateParameterDifferentDefaultArgument)
10957 << FirstTemplate << (i + 1) << FirstType;
10958 ODRDiagNote(SecondTemplate->getLocation(),
10959 SecondTemplate->getSourceRange(),
10960 FunctionTemplateParameterDifferentDefaultArgument)
10961 << SecondTemplate << (i + 1) << SecondType;
10962 ParameterMismatch = true;
10963 break;
10964 }
10965 }
10966
10967 if (FirstTTPD->isParameterPack() !=
10968 SecondTTPD->isParameterPack()) {
10969 ODRDiagError(FirstTemplate->getLocation(),
10970 FirstTemplate->getSourceRange(),
10971 FunctionTemplatePackParameter)
10972 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10973 ODRDiagNote(SecondTemplate->getLocation(),
10974 SecondTemplate->getSourceRange(),
10975 FunctionTemplatePackParameter)
10976 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10977 ParameterMismatch = true;
10978 break;
10979 }
10980 }
10981
10982 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10983 isa<TemplateTemplateParmDecl>(SecondParam)) {
10984 TemplateTemplateParmDecl *FirstTTPD =
10985 cast<TemplateTemplateParmDecl>(FirstParam);
10986 TemplateTemplateParmDecl *SecondTTPD =
10987 cast<TemplateTemplateParmDecl>(SecondParam);
10988
10989 TemplateParameterList *FirstTPL =
10990 FirstTTPD->getTemplateParameters();
10991 TemplateParameterList *SecondTPL =
10992 SecondTTPD->getTemplateParameters();
10993
10994 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10995 ComputeTemplateParameterListODRHash(SecondTPL)) {
10996 ODRDiagError(FirstTemplate->getLocation(),
10997 FirstTemplate->getSourceRange(),
10998 FunctionTemplateParameterDifferentType)
10999 << FirstTemplate << (i + 1);
11000 ODRDiagNote(SecondTemplate->getLocation(),
11001 SecondTemplate->getSourceRange(),
11002 FunctionTemplateParameterDifferentType)
11003 << SecondTemplate << (i + 1);
11004 ParameterMismatch = true;
11005 break;
11006 }
11007
11008 bool HasFirstDefaultArgument =
11009 FirstTTPD->hasDefaultArgument() &&
11010 !FirstTTPD->defaultArgumentWasInherited();
11011 bool HasSecondDefaultArgument =
11012 SecondTTPD->hasDefaultArgument() &&
11013 !SecondTTPD->defaultArgumentWasInherited();
11014 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11015 ODRDiagError(FirstTemplate->getLocation(),
11016 FirstTemplate->getSourceRange(),
11017 FunctionTemplateParameterSingleDefaultArgument)
11018 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11019 ODRDiagNote(SecondTemplate->getLocation(),
11020 SecondTemplate->getSourceRange(),
11021 FunctionTemplateParameterSingleDefaultArgument)
11022 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11023 ParameterMismatch = true;
11024 break;
11025 }
11026
11027 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11028 TemplateArgument FirstTA =
11029 FirstTTPD->getDefaultArgument().getArgument();
11030 TemplateArgument SecondTA =
11031 SecondTTPD->getDefaultArgument().getArgument();
11032 if (ComputeTemplateArgumentODRHash(FirstTA) !=
11033 ComputeTemplateArgumentODRHash(SecondTA)) {
11034 ODRDiagError(FirstTemplate->getLocation(),
11035 FirstTemplate->getSourceRange(),
11036 FunctionTemplateParameterDifferentDefaultArgument)
11037 << FirstTemplate << (i + 1) << FirstTA;
11038 ODRDiagNote(SecondTemplate->getLocation(),
11039 SecondTemplate->getSourceRange(),
11040 FunctionTemplateParameterDifferentDefaultArgument)
11041 << SecondTemplate << (i + 1) << SecondTA;
11042 ParameterMismatch = true;
11043 break;
11044 }
11045 }
11046
11047 if (FirstTTPD->isParameterPack() !=
11048 SecondTTPD->isParameterPack()) {
11049 ODRDiagError(FirstTemplate->getLocation(),
11050 FirstTemplate->getSourceRange(),
11051 FunctionTemplatePackParameter)
11052 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
11053 ODRDiagNote(SecondTemplate->getLocation(),
11054 SecondTemplate->getSourceRange(),
11055 FunctionTemplatePackParameter)
11056 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
11057 ParameterMismatch = true;
11058 break;
11059 }
11060 }
11061
11062 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
11063 isa<NonTypeTemplateParmDecl>(SecondParam)) {
11064 NonTypeTemplateParmDecl *FirstNTTPD =
11065 cast<NonTypeTemplateParmDecl>(FirstParam);
11066 NonTypeTemplateParmDecl *SecondNTTPD =
11067 cast<NonTypeTemplateParmDecl>(SecondParam);
11068
11069 QualType FirstType = FirstNTTPD->getType();
11070 QualType SecondType = SecondNTTPD->getType();
11071 if (ComputeQualTypeODRHash(FirstType) !=
11072 ComputeQualTypeODRHash(SecondType)) {
11073 ODRDiagError(FirstTemplate->getLocation(),
11074 FirstTemplate->getSourceRange(),
11075 FunctionTemplateParameterDifferentType)
11076 << FirstTemplate << (i + 1);
11077 ODRDiagNote(SecondTemplate->getLocation(),
11078 SecondTemplate->getSourceRange(),
11079 FunctionTemplateParameterDifferentType)
11080 << SecondTemplate << (i + 1);
11081 ParameterMismatch = true;
11082 break;
11083 }
11084
11085 bool HasFirstDefaultArgument =
11086 FirstNTTPD->hasDefaultArgument() &&
11087 !FirstNTTPD->defaultArgumentWasInherited();
11088 bool HasSecondDefaultArgument =
11089 SecondNTTPD->hasDefaultArgument() &&
11090 !SecondNTTPD->defaultArgumentWasInherited();
11091 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
11092 ODRDiagError(FirstTemplate->getLocation(),
11093 FirstTemplate->getSourceRange(),
11094 FunctionTemplateParameterSingleDefaultArgument)
11095 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
11096 ODRDiagNote(SecondTemplate->getLocation(),
11097 SecondTemplate->getSourceRange(),
11098 FunctionTemplateParameterSingleDefaultArgument)
11099 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
11100 ParameterMismatch = true;
11101 break;
11102 }
11103
11104 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
11105 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
11106 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
11107 if (ComputeODRHash(FirstDefaultArgument) !=
11108 ComputeODRHash(SecondDefaultArgument)) {
11109 ODRDiagError(FirstTemplate->getLocation(),
11110 FirstTemplate->getSourceRange(),
11111 FunctionTemplateParameterDifferentDefaultArgument)
11112 << FirstTemplate << (i + 1) << FirstDefaultArgument;
11113 ODRDiagNote(SecondTemplate->getLocation(),
11114 SecondTemplate->getSourceRange(),
11115 FunctionTemplateParameterDifferentDefaultArgument)
11116 << SecondTemplate << (i + 1) << SecondDefaultArgument;
11117 ParameterMismatch = true;
11118 break;
11119 }
11120 }
11121
11122 if (FirstNTTPD->isParameterPack() !=
11123 SecondNTTPD->isParameterPack()) {
11124 ODRDiagError(FirstTemplate->getLocation(),
11125 FirstTemplate->getSourceRange(),
11126 FunctionTemplatePackParameter)
11127 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
11128 ODRDiagNote(SecondTemplate->getLocation(),
11129 SecondTemplate->getSourceRange(),
11130 FunctionTemplatePackParameter)
11131 << SecondTemplate << (i + 1)
11132 << SecondNTTPD->isParameterPack();
11133 ParameterMismatch = true;
11134 break;
11135 }
11136 }
11137 }
11138
11139 if (ParameterMismatch) {
11140 Diagnosed = true;
11141 break;
11142 }
11143
11144 break;
11145 }
Richard Trieu639d7b62017-02-22 22:22:42 +000011146 }
11147
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000011148 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000011149 continue;
11150
Richard Trieu708859a2017-06-08 00:56:21 +000011151 Diag(FirstDecl->getLocation(),
11152 diag::err_module_odr_violation_mismatch_decl_unknown)
11153 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
11154 << FirstDecl->getSourceRange();
11155 Diag(SecondDecl->getLocation(),
11156 diag::note_module_odr_violation_mismatch_decl_unknown)
11157 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000011158 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000011159 }
11160
11161 if (!Diagnosed) {
11162 // All definitions are updates to the same declaration. This happens if a
11163 // module instantiates the declaration of a class template specialization
11164 // and two or more other modules instantiate its definition.
11165 //
11166 // FIXME: Indicate which modules had instantiations of this definition.
11167 // FIXME: How can this even happen?
11168 Diag(Merge.first->getLocation(),
11169 diag::err_module_odr_violation_different_instantiations)
11170 << Merge.first;
11171 }
11172 }
Richard Trieue6caa262017-12-23 00:41:01 +000011173
11174 // Issue ODR failures diagnostics for functions.
11175 for (auto &Merge : FunctionOdrMergeFailures) {
11176 enum ODRFunctionDifference {
11177 ReturnType,
11178 ParameterName,
11179 ParameterType,
11180 ParameterSingleDefaultArgument,
11181 ParameterDifferentDefaultArgument,
11182 FunctionBody,
11183 };
11184
11185 FunctionDecl *FirstFunction = Merge.first;
11186 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
11187
11188 bool Diagnosed = false;
11189 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011190
Richard Trieue6caa262017-12-23 00:41:01 +000011191 if (FirstFunction == SecondFunction)
11192 continue;
11193
11194 std::string SecondModule =
11195 getOwningModuleNameForDiagnostic(SecondFunction);
11196
11197 auto ODRDiagError = [FirstFunction, &FirstModule,
11198 this](SourceLocation Loc, SourceRange Range,
11199 ODRFunctionDifference DiffType) {
11200 return Diag(Loc, diag::err_module_odr_violation_function)
11201 << FirstFunction << FirstModule.empty() << FirstModule << Range
11202 << DiffType;
11203 };
11204 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11205 SourceRange Range,
11206 ODRFunctionDifference DiffType) {
11207 return Diag(Loc, diag::note_module_odr_violation_function)
11208 << SecondModule << Range << DiffType;
11209 };
11210
11211 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11212 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11213 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11214 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11215 << FirstFunction->getReturnType();
11216 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11217 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11218 << SecondFunction->getReturnType();
11219 Diagnosed = true;
11220 break;
11221 }
11222
11223 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11224 "Merged functions with different number of parameters");
11225
11226 auto ParamSize = FirstFunction->param_size();
11227 bool ParameterMismatch = false;
11228 for (unsigned I = 0; I < ParamSize; ++I) {
11229 auto *FirstParam = FirstFunction->getParamDecl(I);
11230 auto *SecondParam = SecondFunction->getParamDecl(I);
11231
11232 assert(getContext().hasSameType(FirstParam->getType(),
11233 SecondParam->getType()) &&
11234 "Merged function has different parameter types.");
11235
11236 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11237 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11238 ParameterName)
11239 << I + 1 << FirstParam->getDeclName();
11240 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11241 ParameterName)
11242 << I + 1 << SecondParam->getDeclName();
11243 ParameterMismatch = true;
11244 break;
11245 };
11246
11247 QualType FirstParamType = FirstParam->getType();
11248 QualType SecondParamType = SecondParam->getType();
11249 if (FirstParamType != SecondParamType &&
11250 ComputeQualTypeODRHash(FirstParamType) !=
11251 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011252 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011253 FirstParamType->getAs<DecayedType>()) {
11254 ODRDiagError(FirstParam->getLocation(),
11255 FirstParam->getSourceRange(), ParameterType)
11256 << (I + 1) << FirstParamType << true
11257 << ParamDecayedType->getOriginalType();
11258 } else {
11259 ODRDiagError(FirstParam->getLocation(),
11260 FirstParam->getSourceRange(), ParameterType)
11261 << (I + 1) << FirstParamType << false;
11262 }
11263
Vedant Kumar48b4f762018-04-14 01:40:48 +000011264 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011265 SecondParamType->getAs<DecayedType>()) {
11266 ODRDiagNote(SecondParam->getLocation(),
11267 SecondParam->getSourceRange(), ParameterType)
11268 << (I + 1) << SecondParamType << true
11269 << ParamDecayedType->getOriginalType();
11270 } else {
11271 ODRDiagNote(SecondParam->getLocation(),
11272 SecondParam->getSourceRange(), ParameterType)
11273 << (I + 1) << SecondParamType << false;
11274 }
11275 ParameterMismatch = true;
11276 break;
11277 }
11278
11279 const Expr *FirstInit = FirstParam->getInit();
11280 const Expr *SecondInit = SecondParam->getInit();
11281 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11282 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11283 ParameterSingleDefaultArgument)
11284 << (I + 1) << (FirstInit == nullptr)
11285 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11286 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11287 ParameterSingleDefaultArgument)
11288 << (I + 1) << (SecondInit == nullptr)
11289 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11290 ParameterMismatch = true;
11291 break;
11292 }
11293
11294 if (FirstInit && SecondInit &&
11295 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11296 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11297 ParameterDifferentDefaultArgument)
11298 << (I + 1) << FirstInit->getSourceRange();
11299 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11300 ParameterDifferentDefaultArgument)
11301 << (I + 1) << SecondInit->getSourceRange();
11302 ParameterMismatch = true;
11303 break;
11304 }
11305
11306 assert(ComputeSubDeclODRHash(FirstParam) ==
11307 ComputeSubDeclODRHash(SecondParam) &&
11308 "Undiagnosed parameter difference.");
11309 }
11310
11311 if (ParameterMismatch) {
11312 Diagnosed = true;
11313 break;
11314 }
11315
11316 // If no error has been generated before now, assume the problem is in
11317 // the body and generate a message.
11318 ODRDiagError(FirstFunction->getLocation(),
11319 FirstFunction->getSourceRange(), FunctionBody);
11320 ODRDiagNote(SecondFunction->getLocation(),
11321 SecondFunction->getSourceRange(), FunctionBody);
11322 Diagnosed = true;
11323 break;
11324 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011325 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011326 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11327 }
Richard Trieuab4d7302018-07-25 22:52:05 +000011328
11329 // Issue ODR failures diagnostics for enums.
11330 for (auto &Merge : EnumOdrMergeFailures) {
11331 enum ODREnumDifference {
11332 SingleScopedEnum,
11333 EnumTagKeywordMismatch,
11334 SingleSpecifiedType,
11335 DifferentSpecifiedTypes,
11336 DifferentNumberEnumConstants,
11337 EnumConstantName,
11338 EnumConstantSingleInitilizer,
11339 EnumConstantDifferentInitilizer,
11340 };
11341
11342 // If we've already pointed out a specific problem with this enum, don't
11343 // bother issuing a general "something's different" diagnostic.
11344 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
11345 continue;
11346
11347 EnumDecl *FirstEnum = Merge.first;
11348 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
11349
11350 using DeclHashes =
11351 llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
11352 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
11353 DeclHashes &Hashes, EnumDecl *Enum) {
11354 for (auto *D : Enum->decls()) {
11355 // Due to decl merging, the first EnumDecl is the parent of
11356 // Decls in both records.
11357 if (!ODRHash::isWhitelistedDecl(D, FirstEnum))
11358 continue;
11359 assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
11360 Hashes.emplace_back(cast<EnumConstantDecl>(D),
11361 ComputeSubDeclODRHash(D));
11362 }
11363 };
11364 DeclHashes FirstHashes;
11365 PopulateHashes(FirstHashes, FirstEnum);
11366 bool Diagnosed = false;
11367 for (auto &SecondEnum : Merge.second) {
11368
11369 if (FirstEnum == SecondEnum)
11370 continue;
11371
11372 std::string SecondModule =
11373 getOwningModuleNameForDiagnostic(SecondEnum);
11374
11375 auto ODRDiagError = [FirstEnum, &FirstModule,
11376 this](SourceLocation Loc, SourceRange Range,
11377 ODREnumDifference DiffType) {
11378 return Diag(Loc, diag::err_module_odr_violation_enum)
11379 << FirstEnum << FirstModule.empty() << FirstModule << Range
11380 << DiffType;
11381 };
11382 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11383 SourceRange Range,
11384 ODREnumDifference DiffType) {
11385 return Diag(Loc, diag::note_module_odr_violation_enum)
11386 << SecondModule << Range << DiffType;
11387 };
11388
11389 if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
11390 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11391 SingleScopedEnum)
11392 << FirstEnum->isScoped();
11393 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11394 SingleScopedEnum)
11395 << SecondEnum->isScoped();
11396 Diagnosed = true;
11397 continue;
11398 }
11399
11400 if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
11401 if (FirstEnum->isScopedUsingClassTag() !=
11402 SecondEnum->isScopedUsingClassTag()) {
11403 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11404 EnumTagKeywordMismatch)
11405 << FirstEnum->isScopedUsingClassTag();
11406 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11407 EnumTagKeywordMismatch)
11408 << SecondEnum->isScopedUsingClassTag();
11409 Diagnosed = true;
11410 continue;
11411 }
11412 }
11413
11414 QualType FirstUnderlyingType =
11415 FirstEnum->getIntegerTypeSourceInfo()
11416 ? FirstEnum->getIntegerTypeSourceInfo()->getType()
11417 : QualType();
11418 QualType SecondUnderlyingType =
11419 SecondEnum->getIntegerTypeSourceInfo()
11420 ? SecondEnum->getIntegerTypeSourceInfo()->getType()
11421 : QualType();
11422 if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
11423 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11424 SingleSpecifiedType)
11425 << !FirstUnderlyingType.isNull();
11426 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11427 SingleSpecifiedType)
11428 << !SecondUnderlyingType.isNull();
11429 Diagnosed = true;
11430 continue;
11431 }
11432
11433 if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
11434 if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
11435 ComputeQualTypeODRHash(SecondUnderlyingType)) {
11436 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11437 DifferentSpecifiedTypes)
11438 << FirstUnderlyingType;
11439 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11440 DifferentSpecifiedTypes)
11441 << SecondUnderlyingType;
11442 Diagnosed = true;
11443 continue;
11444 }
11445 }
11446
11447 DeclHashes SecondHashes;
11448 PopulateHashes(SecondHashes, SecondEnum);
11449
11450 if (FirstHashes.size() != SecondHashes.size()) {
11451 ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
11452 DifferentNumberEnumConstants)
11453 << (int)FirstHashes.size();
11454 ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
11455 DifferentNumberEnumConstants)
11456 << (int)SecondHashes.size();
11457 Diagnosed = true;
11458 continue;
11459 }
11460
11461 for (unsigned I = 0; I < FirstHashes.size(); ++I) {
11462 if (FirstHashes[I].second == SecondHashes[I].second)
11463 continue;
11464 const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
11465 const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
11466
11467 if (FirstEnumConstant->getDeclName() !=
11468 SecondEnumConstant->getDeclName()) {
11469
11470 ODRDiagError(FirstEnumConstant->getLocation(),
11471 FirstEnumConstant->getSourceRange(), EnumConstantName)
11472 << I + 1 << FirstEnumConstant;
11473 ODRDiagNote(SecondEnumConstant->getLocation(),
11474 SecondEnumConstant->getSourceRange(), EnumConstantName)
11475 << I + 1 << SecondEnumConstant;
11476 Diagnosed = true;
11477 break;
11478 }
11479
11480 const Expr *FirstInit = FirstEnumConstant->getInitExpr();
11481 const Expr *SecondInit = SecondEnumConstant->getInitExpr();
11482 if (!FirstInit && !SecondInit)
11483 continue;
11484
11485 if (!FirstInit || !SecondInit) {
11486 ODRDiagError(FirstEnumConstant->getLocation(),
11487 FirstEnumConstant->getSourceRange(),
11488 EnumConstantSingleInitilizer)
11489 << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
11490 ODRDiagNote(SecondEnumConstant->getLocation(),
11491 SecondEnumConstant->getSourceRange(),
11492 EnumConstantSingleInitilizer)
11493 << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
11494 Diagnosed = true;
11495 break;
11496 }
11497
11498 if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11499 ODRDiagError(FirstEnumConstant->getLocation(),
11500 FirstEnumConstant->getSourceRange(),
11501 EnumConstantDifferentInitilizer)
11502 << I + 1 << FirstEnumConstant;
11503 ODRDiagNote(SecondEnumConstant->getLocation(),
11504 SecondEnumConstant->getSourceRange(),
11505 EnumConstantDifferentInitilizer)
11506 << I + 1 << SecondEnumConstant;
11507 Diagnosed = true;
11508 break;
11509 }
11510 }
11511 }
11512
11513 (void)Diagnosed;
11514 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11515 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011516}
11517
Richard Smithce18a182015-07-14 00:26:00 +000011518void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011519 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011520 ReadTimer->startTimer();
11521}
11522
Guy Benyei11169dd2012-12-18 14:30:41 +000011523void ASTReader::FinishedDeserializing() {
11524 assert(NumCurrentElementsDeserializing &&
11525 "FinishedDeserializing not paired with StartedDeserializing");
11526 if (NumCurrentElementsDeserializing == 1) {
11527 // We decrease NumCurrentElementsDeserializing only after pending actions
11528 // are finished, to avoid recursively re-calling finishPendingActions().
11529 finishPendingActions();
11530 }
11531 --NumCurrentElementsDeserializing;
11532
Richard Smitha0ce9c42014-07-29 23:23:27 +000011533 if (NumCurrentElementsDeserializing == 0) {
Richard Smitha62d1982018-08-03 01:00:01 +000011534 // Propagate exception specification and deduced type updates along
11535 // redeclaration chains.
11536 //
11537 // We do this now rather than in finishPendingActions because we want to
11538 // be able to walk the complete redeclaration chains of the updated decls.
11539 while (!PendingExceptionSpecUpdates.empty() ||
11540 !PendingDeducedTypeUpdates.empty()) {
11541 auto ESUpdates = std::move(PendingExceptionSpecUpdates);
Richard Smith7226f2a2015-03-23 19:54:56 +000011542 PendingExceptionSpecUpdates.clear();
Richard Smitha62d1982018-08-03 01:00:01 +000011543 for (auto Update : ESUpdates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011544 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011545 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011546 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011547 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011548 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011549 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011550 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011551 }
Richard Smitha62d1982018-08-03 01:00:01 +000011552
11553 auto DTUpdates = std::move(PendingDeducedTypeUpdates);
11554 PendingDeducedTypeUpdates.clear();
11555 for (auto Update : DTUpdates) {
11556 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
11557 // FIXME: If the return type is already deduced, check that it matches.
11558 getContext().adjustDeducedFunctionResultType(Update.first,
11559 Update.second);
11560 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011561 }
11562
Richard Smithce18a182015-07-14 00:26:00 +000011563 if (ReadTimer)
11564 ReadTimer->stopTimer();
11565
Richard Smith0f4e2c42015-08-06 04:23:48 +000011566 diagnoseOdrViolations();
11567
Richard Smith04d05b52014-03-23 00:27:18 +000011568 // We are not in recursive loading, so it's safe to pass the "interesting"
11569 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011570 if (Consumer)
11571 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011572 }
11573}
11574
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011575void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011576 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11577 // Remove any fake results before adding any real ones.
11578 auto It = PendingFakeLookupResults.find(II);
11579 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011580 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011581 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011582 // FIXME: this works around module+PCH performance issue.
11583 // Rather than erase the result from the map, which is O(n), just clear
11584 // the vector of NamedDecls.
11585 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011586 }
11587 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011588
11589 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11590 SemaObj->TUScope->AddDecl(D);
11591 } else if (SemaObj->TUScope) {
11592 // Adding the decl to IdResolver may have failed because it was already in
11593 // (even though it was not added in scope). If it is already in, make sure
11594 // it gets in the scope as well.
11595 if (std::find(SemaObj->IdResolver.begin(Name),
11596 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11597 SemaObj->TUScope->AddDecl(D);
11598 }
11599}
11600
Richard Smithdbafb6c2017-06-29 23:23:46 +000011601ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011602 const PCHContainerReader &PCHContainerRdr,
11603 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11604 StringRef isysroot, bool DisableValidation,
11605 bool AllowASTWithCompilerErrors,
11606 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11607 bool UseGlobalIndex,
11608 std::unique_ptr<llvm::Timer> ReadTimer)
11609 : Listener(DisableValidation
11610 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11611 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011612 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011613 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000011614 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000011615 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
11616 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000011617 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
11618 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011619 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011620 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11621 AllowConfigurationMismatch(AllowConfigurationMismatch),
11622 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011623 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011624 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011625
11626 for (const auto &Ext : Extensions) {
11627 auto BlockName = Ext->getExtensionMetadata().BlockName;
11628 auto Known = ModuleFileExtensions.find(BlockName);
11629 if (Known != ModuleFileExtensions.end()) {
11630 Diags.Report(diag::warn_duplicate_module_file_extension)
11631 << BlockName;
11632 continue;
11633 }
11634
11635 ModuleFileExtensions.insert({BlockName, Ext});
11636 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011637}
11638
11639ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011640 if (OwnsDeserializationListener)
11641 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011642}
Richard Smith10379092016-05-06 23:14:07 +000011643
11644IdentifierResolver &ASTReader::getIdResolver() {
11645 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11646}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011647
11648unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11649 unsigned AbbrevID) {
11650 Idx = 0;
11651 Record.clear();
11652 return Cursor.readRecord(AbbrevID, Record);
11653}
Kelvin Libe286f52018-09-15 13:54:15 +000011654//===----------------------------------------------------------------------===//
11655//// OMPClauseReader implementation
11656////===----------------------------------------------------------------------===//
11657
11658OMPClause *OMPClauseReader::readClause() {
11659 OMPClause *C;
11660 switch (Record.readInt()) {
11661 case OMPC_if:
11662 C = new (Context) OMPIfClause();
11663 break;
11664 case OMPC_final:
11665 C = new (Context) OMPFinalClause();
11666 break;
11667 case OMPC_num_threads:
11668 C = new (Context) OMPNumThreadsClause();
11669 break;
11670 case OMPC_safelen:
11671 C = new (Context) OMPSafelenClause();
11672 break;
11673 case OMPC_simdlen:
11674 C = new (Context) OMPSimdlenClause();
11675 break;
11676 case OMPC_collapse:
11677 C = new (Context) OMPCollapseClause();
11678 break;
11679 case OMPC_default:
11680 C = new (Context) OMPDefaultClause();
11681 break;
11682 case OMPC_proc_bind:
11683 C = new (Context) OMPProcBindClause();
11684 break;
11685 case OMPC_schedule:
11686 C = new (Context) OMPScheduleClause();
11687 break;
11688 case OMPC_ordered:
11689 C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
11690 break;
11691 case OMPC_nowait:
11692 C = new (Context) OMPNowaitClause();
11693 break;
11694 case OMPC_untied:
11695 C = new (Context) OMPUntiedClause();
11696 break;
11697 case OMPC_mergeable:
11698 C = new (Context) OMPMergeableClause();
11699 break;
11700 case OMPC_read:
11701 C = new (Context) OMPReadClause();
11702 break;
11703 case OMPC_write:
11704 C = new (Context) OMPWriteClause();
11705 break;
11706 case OMPC_update:
11707 C = new (Context) OMPUpdateClause();
11708 break;
11709 case OMPC_capture:
11710 C = new (Context) OMPCaptureClause();
11711 break;
11712 case OMPC_seq_cst:
11713 C = new (Context) OMPSeqCstClause();
11714 break;
11715 case OMPC_threads:
11716 C = new (Context) OMPThreadsClause();
11717 break;
11718 case OMPC_simd:
11719 C = new (Context) OMPSIMDClause();
11720 break;
11721 case OMPC_nogroup:
11722 C = new (Context) OMPNogroupClause();
11723 break;
11724 case OMPC_private:
11725 C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
11726 break;
11727 case OMPC_firstprivate:
11728 C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
11729 break;
11730 case OMPC_lastprivate:
11731 C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
11732 break;
11733 case OMPC_shared:
11734 C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
11735 break;
11736 case OMPC_reduction:
11737 C = OMPReductionClause::CreateEmpty(Context, Record.readInt());
11738 break;
11739 case OMPC_task_reduction:
11740 C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
11741 break;
11742 case OMPC_in_reduction:
11743 C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
11744 break;
11745 case OMPC_linear:
11746 C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
11747 break;
11748 case OMPC_aligned:
11749 C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
11750 break;
11751 case OMPC_copyin:
11752 C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
11753 break;
11754 case OMPC_copyprivate:
11755 C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
11756 break;
11757 case OMPC_flush:
11758 C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
11759 break;
11760 case OMPC_depend: {
11761 unsigned NumVars = Record.readInt();
11762 unsigned NumLoops = Record.readInt();
11763 C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
11764 break;
11765 }
11766 case OMPC_device:
11767 C = new (Context) OMPDeviceClause();
11768 break;
11769 case OMPC_map: {
11770 unsigned NumVars = Record.readInt();
11771 unsigned NumDeclarations = Record.readInt();
11772 unsigned NumLists = Record.readInt();
11773 unsigned NumComponents = Record.readInt();
11774 C = OMPMapClause::CreateEmpty(Context, NumVars, NumDeclarations, NumLists,
11775 NumComponents);
11776 break;
11777 }
11778 case OMPC_num_teams:
11779 C = new (Context) OMPNumTeamsClause();
11780 break;
11781 case OMPC_thread_limit:
11782 C = new (Context) OMPThreadLimitClause();
11783 break;
11784 case OMPC_priority:
11785 C = new (Context) OMPPriorityClause();
11786 break;
11787 case OMPC_grainsize:
11788 C = new (Context) OMPGrainsizeClause();
11789 break;
11790 case OMPC_num_tasks:
11791 C = new (Context) OMPNumTasksClause();
11792 break;
11793 case OMPC_hint:
11794 C = new (Context) OMPHintClause();
11795 break;
11796 case OMPC_dist_schedule:
11797 C = new (Context) OMPDistScheduleClause();
11798 break;
11799 case OMPC_defaultmap:
11800 C = new (Context) OMPDefaultmapClause();
11801 break;
11802 case OMPC_to: {
11803 unsigned NumVars = Record.readInt();
11804 unsigned NumDeclarations = Record.readInt();
11805 unsigned NumLists = Record.readInt();
11806 unsigned NumComponents = Record.readInt();
11807 C = OMPToClause::CreateEmpty(Context, NumVars, NumDeclarations, NumLists,
11808 NumComponents);
11809 break;
11810 }
11811 case OMPC_from: {
11812 unsigned NumVars = Record.readInt();
11813 unsigned NumDeclarations = Record.readInt();
11814 unsigned NumLists = Record.readInt();
11815 unsigned NumComponents = Record.readInt();
11816 C = OMPFromClause::CreateEmpty(Context, NumVars, NumDeclarations, NumLists,
11817 NumComponents);
11818 break;
11819 }
11820 case OMPC_use_device_ptr: {
11821 unsigned NumVars = Record.readInt();
11822 unsigned NumDeclarations = Record.readInt();
11823 unsigned NumLists = Record.readInt();
11824 unsigned NumComponents = Record.readInt();
11825 C = OMPUseDevicePtrClause::CreateEmpty(Context, NumVars, NumDeclarations,
11826 NumLists, NumComponents);
11827 break;
11828 }
11829 case OMPC_is_device_ptr: {
11830 unsigned NumVars = Record.readInt();
11831 unsigned NumDeclarations = Record.readInt();
11832 unsigned NumLists = Record.readInt();
11833 unsigned NumComponents = Record.readInt();
11834 C = OMPIsDevicePtrClause::CreateEmpty(Context, NumVars, NumDeclarations,
11835 NumLists, NumComponents);
11836 break;
11837 }
11838 }
11839 Visit(C);
11840 C->setLocStart(Record.readSourceLocation());
11841 C->setLocEnd(Record.readSourceLocation());
11842
11843 return C;
11844}
11845
11846void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
11847 C->setPreInitStmt(Record.readSubStmt(),
11848 static_cast<OpenMPDirectiveKind>(Record.readInt()));
11849}
11850
11851void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
11852 VisitOMPClauseWithPreInit(C);
11853 C->setPostUpdateExpr(Record.readSubExpr());
11854}
11855
11856void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
11857 VisitOMPClauseWithPreInit(C);
11858 C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
11859 C->setNameModifierLoc(Record.readSourceLocation());
11860 C->setColonLoc(Record.readSourceLocation());
11861 C->setCondition(Record.readSubExpr());
11862 C->setLParenLoc(Record.readSourceLocation());
11863}
11864
11865void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
11866 C->setCondition(Record.readSubExpr());
11867 C->setLParenLoc(Record.readSourceLocation());
11868}
11869
11870void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
11871 VisitOMPClauseWithPreInit(C);
11872 C->setNumThreads(Record.readSubExpr());
11873 C->setLParenLoc(Record.readSourceLocation());
11874}
11875
11876void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
11877 C->setSafelen(Record.readSubExpr());
11878 C->setLParenLoc(Record.readSourceLocation());
11879}
11880
11881void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
11882 C->setSimdlen(Record.readSubExpr());
11883 C->setLParenLoc(Record.readSourceLocation());
11884}
11885
11886void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
11887 C->setNumForLoops(Record.readSubExpr());
11888 C->setLParenLoc(Record.readSourceLocation());
11889}
11890
11891void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
11892 C->setDefaultKind(
11893 static_cast<OpenMPDefaultClauseKind>(Record.readInt()));
11894 C->setLParenLoc(Record.readSourceLocation());
11895 C->setDefaultKindKwLoc(Record.readSourceLocation());
11896}
11897
11898void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
11899 C->setProcBindKind(
11900 static_cast<OpenMPProcBindClauseKind>(Record.readInt()));
11901 C->setLParenLoc(Record.readSourceLocation());
11902 C->setProcBindKindKwLoc(Record.readSourceLocation());
11903}
11904
11905void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
11906 VisitOMPClauseWithPreInit(C);
11907 C->setScheduleKind(
11908 static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
11909 C->setFirstScheduleModifier(
11910 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11911 C->setSecondScheduleModifier(
11912 static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
11913 C->setChunkSize(Record.readSubExpr());
11914 C->setLParenLoc(Record.readSourceLocation());
11915 C->setFirstScheduleModifierLoc(Record.readSourceLocation());
11916 C->setSecondScheduleModifierLoc(Record.readSourceLocation());
11917 C->setScheduleKindLoc(Record.readSourceLocation());
11918 C->setCommaLoc(Record.readSourceLocation());
11919}
11920
11921void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
11922 C->setNumForLoops(Record.readSubExpr());
11923 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11924 C->setLoopNumIterations(I, Record.readSubExpr());
11925 for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
11926 C->setLoopCounter(I, Record.readSubExpr());
11927 C->setLParenLoc(Record.readSourceLocation());
11928}
11929
11930void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
11931
11932void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
11933
11934void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
11935
11936void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
11937
11938void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
11939
11940void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *) {}
11941
11942void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
11943
11944void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
11945
11946void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
11947
11948void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
11949
11950void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
11951
11952void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
11953 C->setLParenLoc(Record.readSourceLocation());
11954 unsigned NumVars = C->varlist_size();
11955 SmallVector<Expr *, 16> Vars;
11956 Vars.reserve(NumVars);
11957 for (unsigned i = 0; i != NumVars; ++i)
11958 Vars.push_back(Record.readSubExpr());
11959 C->setVarRefs(Vars);
11960 Vars.clear();
11961 for (unsigned i = 0; i != NumVars; ++i)
11962 Vars.push_back(Record.readSubExpr());
11963 C->setPrivateCopies(Vars);
11964}
11965
11966void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
11967 VisitOMPClauseWithPreInit(C);
11968 C->setLParenLoc(Record.readSourceLocation());
11969 unsigned NumVars = C->varlist_size();
11970 SmallVector<Expr *, 16> Vars;
11971 Vars.reserve(NumVars);
11972 for (unsigned i = 0; i != NumVars; ++i)
11973 Vars.push_back(Record.readSubExpr());
11974 C->setVarRefs(Vars);
11975 Vars.clear();
11976 for (unsigned i = 0; i != NumVars; ++i)
11977 Vars.push_back(Record.readSubExpr());
11978 C->setPrivateCopies(Vars);
11979 Vars.clear();
11980 for (unsigned i = 0; i != NumVars; ++i)
11981 Vars.push_back(Record.readSubExpr());
11982 C->setInits(Vars);
11983}
11984
11985void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
11986 VisitOMPClauseWithPostUpdate(C);
11987 C->setLParenLoc(Record.readSourceLocation());
11988 unsigned NumVars = C->varlist_size();
11989 SmallVector<Expr *, 16> Vars;
11990 Vars.reserve(NumVars);
11991 for (unsigned i = 0; i != NumVars; ++i)
11992 Vars.push_back(Record.readSubExpr());
11993 C->setVarRefs(Vars);
11994 Vars.clear();
11995 for (unsigned i = 0; i != NumVars; ++i)
11996 Vars.push_back(Record.readSubExpr());
11997 C->setPrivateCopies(Vars);
11998 Vars.clear();
11999 for (unsigned i = 0; i != NumVars; ++i)
12000 Vars.push_back(Record.readSubExpr());
12001 C->setSourceExprs(Vars);
12002 Vars.clear();
12003 for (unsigned i = 0; i != NumVars; ++i)
12004 Vars.push_back(Record.readSubExpr());
12005 C->setDestinationExprs(Vars);
12006 Vars.clear();
12007 for (unsigned i = 0; i != NumVars; ++i)
12008 Vars.push_back(Record.readSubExpr());
12009 C->setAssignmentOps(Vars);
12010}
12011
12012void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
12013 C->setLParenLoc(Record.readSourceLocation());
12014 unsigned NumVars = C->varlist_size();
12015 SmallVector<Expr *, 16> Vars;
12016 Vars.reserve(NumVars);
12017 for (unsigned i = 0; i != NumVars; ++i)
12018 Vars.push_back(Record.readSubExpr());
12019 C->setVarRefs(Vars);
12020}
12021
12022void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
12023 VisitOMPClauseWithPostUpdate(C);
12024 C->setLParenLoc(Record.readSourceLocation());
12025 C->setColonLoc(Record.readSourceLocation());
12026 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12027 DeclarationNameInfo DNI;
12028 Record.readDeclarationNameInfo(DNI);
12029 C->setQualifierLoc(NNSL);
12030 C->setNameInfo(DNI);
12031
12032 unsigned NumVars = C->varlist_size();
12033 SmallVector<Expr *, 16> Vars;
12034 Vars.reserve(NumVars);
12035 for (unsigned i = 0; i != NumVars; ++i)
12036 Vars.push_back(Record.readSubExpr());
12037 C->setVarRefs(Vars);
12038 Vars.clear();
12039 for (unsigned i = 0; i != NumVars; ++i)
12040 Vars.push_back(Record.readSubExpr());
12041 C->setPrivates(Vars);
12042 Vars.clear();
12043 for (unsigned i = 0; i != NumVars; ++i)
12044 Vars.push_back(Record.readSubExpr());
12045 C->setLHSExprs(Vars);
12046 Vars.clear();
12047 for (unsigned i = 0; i != NumVars; ++i)
12048 Vars.push_back(Record.readSubExpr());
12049 C->setRHSExprs(Vars);
12050 Vars.clear();
12051 for (unsigned i = 0; i != NumVars; ++i)
12052 Vars.push_back(Record.readSubExpr());
12053 C->setReductionOps(Vars);
12054}
12055
12056void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
12057 VisitOMPClauseWithPostUpdate(C);
12058 C->setLParenLoc(Record.readSourceLocation());
12059 C->setColonLoc(Record.readSourceLocation());
12060 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12061 DeclarationNameInfo DNI;
12062 Record.readDeclarationNameInfo(DNI);
12063 C->setQualifierLoc(NNSL);
12064 C->setNameInfo(DNI);
12065
12066 unsigned NumVars = C->varlist_size();
12067 SmallVector<Expr *, 16> Vars;
12068 Vars.reserve(NumVars);
12069 for (unsigned I = 0; I != NumVars; ++I)
12070 Vars.push_back(Record.readSubExpr());
12071 C->setVarRefs(Vars);
12072 Vars.clear();
12073 for (unsigned I = 0; I != NumVars; ++I)
12074 Vars.push_back(Record.readSubExpr());
12075 C->setPrivates(Vars);
12076 Vars.clear();
12077 for (unsigned I = 0; I != NumVars; ++I)
12078 Vars.push_back(Record.readSubExpr());
12079 C->setLHSExprs(Vars);
12080 Vars.clear();
12081 for (unsigned I = 0; I != NumVars; ++I)
12082 Vars.push_back(Record.readSubExpr());
12083 C->setRHSExprs(Vars);
12084 Vars.clear();
12085 for (unsigned I = 0; I != NumVars; ++I)
12086 Vars.push_back(Record.readSubExpr());
12087 C->setReductionOps(Vars);
12088}
12089
12090void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
12091 VisitOMPClauseWithPostUpdate(C);
12092 C->setLParenLoc(Record.readSourceLocation());
12093 C->setColonLoc(Record.readSourceLocation());
12094 NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
12095 DeclarationNameInfo DNI;
12096 Record.readDeclarationNameInfo(DNI);
12097 C->setQualifierLoc(NNSL);
12098 C->setNameInfo(DNI);
12099
12100 unsigned NumVars = C->varlist_size();
12101 SmallVector<Expr *, 16> Vars;
12102 Vars.reserve(NumVars);
12103 for (unsigned I = 0; I != NumVars; ++I)
12104 Vars.push_back(Record.readSubExpr());
12105 C->setVarRefs(Vars);
12106 Vars.clear();
12107 for (unsigned I = 0; I != NumVars; ++I)
12108 Vars.push_back(Record.readSubExpr());
12109 C->setPrivates(Vars);
12110 Vars.clear();
12111 for (unsigned I = 0; I != NumVars; ++I)
12112 Vars.push_back(Record.readSubExpr());
12113 C->setLHSExprs(Vars);
12114 Vars.clear();
12115 for (unsigned I = 0; I != NumVars; ++I)
12116 Vars.push_back(Record.readSubExpr());
12117 C->setRHSExprs(Vars);
12118 Vars.clear();
12119 for (unsigned I = 0; I != NumVars; ++I)
12120 Vars.push_back(Record.readSubExpr());
12121 C->setReductionOps(Vars);
12122 Vars.clear();
12123 for (unsigned I = 0; I != NumVars; ++I)
12124 Vars.push_back(Record.readSubExpr());
12125 C->setTaskgroupDescriptors(Vars);
12126}
12127
12128void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
12129 VisitOMPClauseWithPostUpdate(C);
12130 C->setLParenLoc(Record.readSourceLocation());
12131 C->setColonLoc(Record.readSourceLocation());
12132 C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
12133 C->setModifierLoc(Record.readSourceLocation());
12134 unsigned NumVars = C->varlist_size();
12135 SmallVector<Expr *, 16> Vars;
12136 Vars.reserve(NumVars);
12137 for (unsigned i = 0; i != NumVars; ++i)
12138 Vars.push_back(Record.readSubExpr());
12139 C->setVarRefs(Vars);
12140 Vars.clear();
12141 for (unsigned i = 0; i != NumVars; ++i)
12142 Vars.push_back(Record.readSubExpr());
12143 C->setPrivates(Vars);
12144 Vars.clear();
12145 for (unsigned i = 0; i != NumVars; ++i)
12146 Vars.push_back(Record.readSubExpr());
12147 C->setInits(Vars);
12148 Vars.clear();
12149 for (unsigned i = 0; i != NumVars; ++i)
12150 Vars.push_back(Record.readSubExpr());
12151 C->setUpdates(Vars);
12152 Vars.clear();
12153 for (unsigned i = 0; i != NumVars; ++i)
12154 Vars.push_back(Record.readSubExpr());
12155 C->setFinals(Vars);
12156 C->setStep(Record.readSubExpr());
12157 C->setCalcStep(Record.readSubExpr());
12158}
12159
12160void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
12161 C->setLParenLoc(Record.readSourceLocation());
12162 C->setColonLoc(Record.readSourceLocation());
12163 unsigned NumVars = C->varlist_size();
12164 SmallVector<Expr *, 16> Vars;
12165 Vars.reserve(NumVars);
12166 for (unsigned i = 0; i != NumVars; ++i)
12167 Vars.push_back(Record.readSubExpr());
12168 C->setVarRefs(Vars);
12169 C->setAlignment(Record.readSubExpr());
12170}
12171
12172void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
12173 C->setLParenLoc(Record.readSourceLocation());
12174 unsigned NumVars = C->varlist_size();
12175 SmallVector<Expr *, 16> Exprs;
12176 Exprs.reserve(NumVars);
12177 for (unsigned i = 0; i != NumVars; ++i)
12178 Exprs.push_back(Record.readSubExpr());
12179 C->setVarRefs(Exprs);
12180 Exprs.clear();
12181 for (unsigned i = 0; i != NumVars; ++i)
12182 Exprs.push_back(Record.readSubExpr());
12183 C->setSourceExprs(Exprs);
12184 Exprs.clear();
12185 for (unsigned i = 0; i != NumVars; ++i)
12186 Exprs.push_back(Record.readSubExpr());
12187 C->setDestinationExprs(Exprs);
12188 Exprs.clear();
12189 for (unsigned i = 0; i != NumVars; ++i)
12190 Exprs.push_back(Record.readSubExpr());
12191 C->setAssignmentOps(Exprs);
12192}
12193
12194void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
12195 C->setLParenLoc(Record.readSourceLocation());
12196 unsigned NumVars = C->varlist_size();
12197 SmallVector<Expr *, 16> Exprs;
12198 Exprs.reserve(NumVars);
12199 for (unsigned i = 0; i != NumVars; ++i)
12200 Exprs.push_back(Record.readSubExpr());
12201 C->setVarRefs(Exprs);
12202 Exprs.clear();
12203 for (unsigned i = 0; i != NumVars; ++i)
12204 Exprs.push_back(Record.readSubExpr());
12205 C->setSourceExprs(Exprs);
12206 Exprs.clear();
12207 for (unsigned i = 0; i != NumVars; ++i)
12208 Exprs.push_back(Record.readSubExpr());
12209 C->setDestinationExprs(Exprs);
12210 Exprs.clear();
12211 for (unsigned i = 0; i != NumVars; ++i)
12212 Exprs.push_back(Record.readSubExpr());
12213 C->setAssignmentOps(Exprs);
12214}
12215
12216void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
12217 C->setLParenLoc(Record.readSourceLocation());
12218 unsigned NumVars = C->varlist_size();
12219 SmallVector<Expr *, 16> Vars;
12220 Vars.reserve(NumVars);
12221 for (unsigned i = 0; i != NumVars; ++i)
12222 Vars.push_back(Record.readSubExpr());
12223 C->setVarRefs(Vars);
12224}
12225
12226void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
12227 C->setLParenLoc(Record.readSourceLocation());
12228 C->setDependencyKind(
12229 static_cast<OpenMPDependClauseKind>(Record.readInt()));
12230 C->setDependencyLoc(Record.readSourceLocation());
12231 C->setColonLoc(Record.readSourceLocation());
12232 unsigned NumVars = C->varlist_size();
12233 SmallVector<Expr *, 16> Vars;
12234 Vars.reserve(NumVars);
12235 for (unsigned I = 0; I != NumVars; ++I)
12236 Vars.push_back(Record.readSubExpr());
12237 C->setVarRefs(Vars);
12238 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
12239 C->setLoopData(I, Record.readSubExpr());
12240}
12241
12242void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
12243 VisitOMPClauseWithPreInit(C);
12244 C->setDevice(Record.readSubExpr());
12245 C->setLParenLoc(Record.readSourceLocation());
12246}
12247
12248void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
12249 C->setLParenLoc(Record.readSourceLocation());
12250 C->setMapTypeModifier(
12251 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12252 C->setMapType(
12253 static_cast<OpenMPMapClauseKind>(Record.readInt()));
12254 C->setMapLoc(Record.readSourceLocation());
12255 C->setColonLoc(Record.readSourceLocation());
12256 auto NumVars = C->varlist_size();
12257 auto UniqueDecls = C->getUniqueDeclarationsNum();
12258 auto TotalLists = C->getTotalComponentListNum();
12259 auto TotalComponents = C->getTotalComponentsNum();
12260
12261 SmallVector<Expr *, 16> Vars;
12262 Vars.reserve(NumVars);
12263 for (unsigned i = 0; i != NumVars; ++i)
12264 Vars.push_back(Record.readSubExpr());
12265 C->setVarRefs(Vars);
12266
12267 SmallVector<ValueDecl *, 16> Decls;
12268 Decls.reserve(UniqueDecls);
12269 for (unsigned i = 0; i < UniqueDecls; ++i)
12270 Decls.push_back(Record.readDeclAs<ValueDecl>());
12271 C->setUniqueDecls(Decls);
12272
12273 SmallVector<unsigned, 16> ListsPerDecl;
12274 ListsPerDecl.reserve(UniqueDecls);
12275 for (unsigned i = 0; i < UniqueDecls; ++i)
12276 ListsPerDecl.push_back(Record.readInt());
12277 C->setDeclNumLists(ListsPerDecl);
12278
12279 SmallVector<unsigned, 32> ListSizes;
12280 ListSizes.reserve(TotalLists);
12281 for (unsigned i = 0; i < TotalLists; ++i)
12282 ListSizes.push_back(Record.readInt());
12283 C->setComponentListSizes(ListSizes);
12284
12285 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12286 Components.reserve(TotalComponents);
12287 for (unsigned i = 0; i < TotalComponents; ++i) {
12288 Expr *AssociatedExpr = Record.readSubExpr();
12289 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12290 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12291 AssociatedExpr, AssociatedDecl));
12292 }
12293 C->setComponents(Components, ListSizes);
12294}
12295
12296void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
12297 VisitOMPClauseWithPreInit(C);
12298 C->setNumTeams(Record.readSubExpr());
12299 C->setLParenLoc(Record.readSourceLocation());
12300}
12301
12302void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
12303 VisitOMPClauseWithPreInit(C);
12304 C->setThreadLimit(Record.readSubExpr());
12305 C->setLParenLoc(Record.readSourceLocation());
12306}
12307
12308void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
12309 C->setPriority(Record.readSubExpr());
12310 C->setLParenLoc(Record.readSourceLocation());
12311}
12312
12313void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
12314 C->setGrainsize(Record.readSubExpr());
12315 C->setLParenLoc(Record.readSourceLocation());
12316}
12317
12318void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
12319 C->setNumTasks(Record.readSubExpr());
12320 C->setLParenLoc(Record.readSourceLocation());
12321}
12322
12323void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
12324 C->setHint(Record.readSubExpr());
12325 C->setLParenLoc(Record.readSourceLocation());
12326}
12327
12328void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
12329 VisitOMPClauseWithPreInit(C);
12330 C->setDistScheduleKind(
12331 static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
12332 C->setChunkSize(Record.readSubExpr());
12333 C->setLParenLoc(Record.readSourceLocation());
12334 C->setDistScheduleKindLoc(Record.readSourceLocation());
12335 C->setCommaLoc(Record.readSourceLocation());
12336}
12337
12338void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
12339 C->setDefaultmapKind(
12340 static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
12341 C->setDefaultmapModifier(
12342 static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
12343 C->setLParenLoc(Record.readSourceLocation());
12344 C->setDefaultmapModifierLoc(Record.readSourceLocation());
12345 C->setDefaultmapKindLoc(Record.readSourceLocation());
12346}
12347
12348void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
12349 C->setLParenLoc(Record.readSourceLocation());
12350 auto NumVars = C->varlist_size();
12351 auto UniqueDecls = C->getUniqueDeclarationsNum();
12352 auto TotalLists = C->getTotalComponentListNum();
12353 auto TotalComponents = C->getTotalComponentsNum();
12354
12355 SmallVector<Expr *, 16> Vars;
12356 Vars.reserve(NumVars);
12357 for (unsigned i = 0; i != NumVars; ++i)
12358 Vars.push_back(Record.readSubExpr());
12359 C->setVarRefs(Vars);
12360
12361 SmallVector<ValueDecl *, 16> Decls;
12362 Decls.reserve(UniqueDecls);
12363 for (unsigned i = 0; i < UniqueDecls; ++i)
12364 Decls.push_back(Record.readDeclAs<ValueDecl>());
12365 C->setUniqueDecls(Decls);
12366
12367 SmallVector<unsigned, 16> ListsPerDecl;
12368 ListsPerDecl.reserve(UniqueDecls);
12369 for (unsigned i = 0; i < UniqueDecls; ++i)
12370 ListsPerDecl.push_back(Record.readInt());
12371 C->setDeclNumLists(ListsPerDecl);
12372
12373 SmallVector<unsigned, 32> ListSizes;
12374 ListSizes.reserve(TotalLists);
12375 for (unsigned i = 0; i < TotalLists; ++i)
12376 ListSizes.push_back(Record.readInt());
12377 C->setComponentListSizes(ListSizes);
12378
12379 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12380 Components.reserve(TotalComponents);
12381 for (unsigned i = 0; i < TotalComponents; ++i) {
12382 Expr *AssociatedExpr = Record.readSubExpr();
12383 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12384 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12385 AssociatedExpr, AssociatedDecl));
12386 }
12387 C->setComponents(Components, ListSizes);
12388}
12389
12390void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
12391 C->setLParenLoc(Record.readSourceLocation());
12392 auto NumVars = C->varlist_size();
12393 auto UniqueDecls = C->getUniqueDeclarationsNum();
12394 auto TotalLists = C->getTotalComponentListNum();
12395 auto TotalComponents = C->getTotalComponentsNum();
12396
12397 SmallVector<Expr *, 16> Vars;
12398 Vars.reserve(NumVars);
12399 for (unsigned i = 0; i != NumVars; ++i)
12400 Vars.push_back(Record.readSubExpr());
12401 C->setVarRefs(Vars);
12402
12403 SmallVector<ValueDecl *, 16> Decls;
12404 Decls.reserve(UniqueDecls);
12405 for (unsigned i = 0; i < UniqueDecls; ++i)
12406 Decls.push_back(Record.readDeclAs<ValueDecl>());
12407 C->setUniqueDecls(Decls);
12408
12409 SmallVector<unsigned, 16> ListsPerDecl;
12410 ListsPerDecl.reserve(UniqueDecls);
12411 for (unsigned i = 0; i < UniqueDecls; ++i)
12412 ListsPerDecl.push_back(Record.readInt());
12413 C->setDeclNumLists(ListsPerDecl);
12414
12415 SmallVector<unsigned, 32> ListSizes;
12416 ListSizes.reserve(TotalLists);
12417 for (unsigned i = 0; i < TotalLists; ++i)
12418 ListSizes.push_back(Record.readInt());
12419 C->setComponentListSizes(ListSizes);
12420
12421 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12422 Components.reserve(TotalComponents);
12423 for (unsigned i = 0; i < TotalComponents; ++i) {
12424 Expr *AssociatedExpr = Record.readSubExpr();
12425 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12426 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12427 AssociatedExpr, AssociatedDecl));
12428 }
12429 C->setComponents(Components, ListSizes);
12430}
12431
12432void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
12433 C->setLParenLoc(Record.readSourceLocation());
12434 auto NumVars = C->varlist_size();
12435 auto UniqueDecls = C->getUniqueDeclarationsNum();
12436 auto TotalLists = C->getTotalComponentListNum();
12437 auto TotalComponents = C->getTotalComponentsNum();
12438
12439 SmallVector<Expr *, 16> Vars;
12440 Vars.reserve(NumVars);
12441 for (unsigned i = 0; i != NumVars; ++i)
12442 Vars.push_back(Record.readSubExpr());
12443 C->setVarRefs(Vars);
12444 Vars.clear();
12445 for (unsigned i = 0; i != NumVars; ++i)
12446 Vars.push_back(Record.readSubExpr());
12447 C->setPrivateCopies(Vars);
12448 Vars.clear();
12449 for (unsigned i = 0; i != NumVars; ++i)
12450 Vars.push_back(Record.readSubExpr());
12451 C->setInits(Vars);
12452
12453 SmallVector<ValueDecl *, 16> Decls;
12454 Decls.reserve(UniqueDecls);
12455 for (unsigned i = 0; i < UniqueDecls; ++i)
12456 Decls.push_back(Record.readDeclAs<ValueDecl>());
12457 C->setUniqueDecls(Decls);
12458
12459 SmallVector<unsigned, 16> ListsPerDecl;
12460 ListsPerDecl.reserve(UniqueDecls);
12461 for (unsigned i = 0; i < UniqueDecls; ++i)
12462 ListsPerDecl.push_back(Record.readInt());
12463 C->setDeclNumLists(ListsPerDecl);
12464
12465 SmallVector<unsigned, 32> ListSizes;
12466 ListSizes.reserve(TotalLists);
12467 for (unsigned i = 0; i < TotalLists; ++i)
12468 ListSizes.push_back(Record.readInt());
12469 C->setComponentListSizes(ListSizes);
12470
12471 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12472 Components.reserve(TotalComponents);
12473 for (unsigned i = 0; i < TotalComponents; ++i) {
12474 Expr *AssociatedExpr = Record.readSubExpr();
12475 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12476 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12477 AssociatedExpr, AssociatedDecl));
12478 }
12479 C->setComponents(Components, ListSizes);
12480}
12481
12482void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
12483 C->setLParenLoc(Record.readSourceLocation());
12484 auto NumVars = C->varlist_size();
12485 auto UniqueDecls = C->getUniqueDeclarationsNum();
12486 auto TotalLists = C->getTotalComponentListNum();
12487 auto TotalComponents = C->getTotalComponentsNum();
12488
12489 SmallVector<Expr *, 16> Vars;
12490 Vars.reserve(NumVars);
12491 for (unsigned i = 0; i != NumVars; ++i)
12492 Vars.push_back(Record.readSubExpr());
12493 C->setVarRefs(Vars);
12494 Vars.clear();
12495
12496 SmallVector<ValueDecl *, 16> Decls;
12497 Decls.reserve(UniqueDecls);
12498 for (unsigned i = 0; i < UniqueDecls; ++i)
12499 Decls.push_back(Record.readDeclAs<ValueDecl>());
12500 C->setUniqueDecls(Decls);
12501
12502 SmallVector<unsigned, 16> ListsPerDecl;
12503 ListsPerDecl.reserve(UniqueDecls);
12504 for (unsigned i = 0; i < UniqueDecls; ++i)
12505 ListsPerDecl.push_back(Record.readInt());
12506 C->setDeclNumLists(ListsPerDecl);
12507
12508 SmallVector<unsigned, 32> ListSizes;
12509 ListSizes.reserve(TotalLists);
12510 for (unsigned i = 0; i < TotalLists; ++i)
12511 ListSizes.push_back(Record.readInt());
12512 C->setComponentListSizes(ListSizes);
12513
12514 SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
12515 Components.reserve(TotalComponents);
12516 for (unsigned i = 0; i < TotalComponents; ++i) {
12517 Expr *AssociatedExpr = Record.readSubExpr();
12518 auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
12519 Components.push_back(OMPClauseMappableExprCommon::MappableComponent(
12520 AssociatedExpr, AssociatedDecl));
12521 }
12522 C->setComponents(Components, ListSizes);
12523}