blob: 391e350445933c8d422630e9c509f1a88ccc2ae0 [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"
64#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000066#include "clang/Lex/HeaderSearch.h"
67#include "clang/Lex/HeaderSearchOptions.h"
68#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "clang/Lex/PreprocessingRecord.h"
71#include "clang/Lex/Preprocessor.h"
72#include "clang/Lex/PreprocessorOptions.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000073#include "clang/Lex/Token.h"
74#include "clang/Sema/ObjCMethodList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000075#include "clang/Sema/Scope.h"
76#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000077#include "clang/Sema/Weak.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000078#include "clang/Serialization/ASTBitCodes.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000079#include "clang/Serialization/ASTDeserializationListener.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000080#include "clang/Serialization/ContinuousRangeMap.h"
Douglas Gregore060e572013-01-25 01:03:03 +000081#include "clang/Serialization/GlobalModuleIndex.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000082#include "clang/Serialization/Module.h"
83#include "clang/Serialization/ModuleFileExtension.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000084#include "clang/Serialization/ModuleManager.h"
85#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086#include "llvm/ADT/APFloat.h"
87#include "llvm/ADT/APInt.h"
88#include "llvm/ADT/APSInt.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000089#include "llvm/ADT/ArrayRef.h"
90#include "llvm/ADT/DenseMap.h"
91#include "llvm/ADT/FoldingSet.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000092#include "llvm/ADT/Hashing.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000093#include "llvm/ADT/IntrusiveRefCntPtr.h"
94#include "llvm/ADT/None.h"
95#include "llvm/ADT/Optional.h"
96#include "llvm/ADT/STLExtras.h"
97#include "llvm/ADT/SmallPtrSet.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000098#include "llvm/ADT/SmallString.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000099#include "llvm/ADT/SmallVector.h"
Vedant Kumar48b4f762018-04-14 01:40:48 +0000100#include "llvm/ADT/StringExtras.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000101#include "llvm/ADT/StringMap.h"
102#include "llvm/ADT/StringRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000103#include "llvm/ADT/Triple.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000104#include "llvm/ADT/iterator_range.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000105#include "llvm/Bitcode/BitstreamReader.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000106#include "llvm/Support/Casting.h"
Richard Smithaada85c2016-02-06 02:06:43 +0000107#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000108#include "llvm/Support/Compiler.h"
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000109#include "llvm/Support/DJB.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000110#include "llvm/Support/Endian.h"
George Rimarc39f5492017-01-17 15:45:31 +0000111#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +0000112#include "llvm/Support/ErrorHandling.h"
113#include "llvm/Support/FileSystem.h"
114#include "llvm/Support/MemoryBuffer.h"
115#include "llvm/Support/Path.h"
116#include "llvm/Support/SaveAndRestore.h"
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000117#include "llvm/Support/Timer.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];
Guy Benyei11169dd2012-12-18 14:30:41 +0000707 if (File == ExistingPPOpts.ImplicitPCHInclude)
708 continue;
709
710 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
711 != PPOpts.Includes.end())
712 continue;
713
714 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000715 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000716 SuggestedPredefines += "\"\n";
717 }
718
Vedant Kumar48b4f762018-04-14 01:40:48 +0000719 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
720 StringRef File = ExistingPPOpts.MacroIncludes[I];
Guy Benyei11169dd2012-12-18 14:30:41 +0000721 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
722 File)
723 != PPOpts.MacroIncludes.end())
724 continue;
725
726 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000727 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000728 SuggestedPredefines += "\"\n##\n";
729 }
730
731 return false;
732}
733
734bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
735 bool Complain,
736 std::string &SuggestedPredefines) {
737 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
738
739 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000740 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000741 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000742 SuggestedPredefines,
743 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000744}
745
Yaxun Liu43712e02016-09-07 18:40:20 +0000746bool SimpleASTReaderListener::ReadPreprocessorOptions(
747 const PreprocessorOptions &PPOpts,
748 bool Complain,
749 std::string &SuggestedPredefines) {
750 return checkPreprocessorOptions(PPOpts,
751 PP.getPreprocessorOpts(),
752 nullptr,
753 PP.getFileManager(),
754 SuggestedPredefines,
755 PP.getLangOpts(),
756 false);
757}
758
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000759/// Check the header search options deserialized from the control block
760/// against the header search options in an existing preprocessor.
761///
762/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
763static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
764 StringRef SpecificModuleCachePath,
765 StringRef ExistingModuleCachePath,
766 DiagnosticsEngine *Diags,
767 const LangOptions &LangOpts) {
768 if (LangOpts.Modules) {
769 if (SpecificModuleCachePath != ExistingModuleCachePath) {
770 if (Diags)
771 Diags->Report(diag::err_pch_modulecache_mismatch)
772 << SpecificModuleCachePath << ExistingModuleCachePath;
773 return true;
774 }
775 }
776
777 return false;
778}
779
780bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
781 StringRef SpecificModuleCachePath,
782 bool Complain) {
783 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
784 PP.getHeaderSearchInfo().getModuleCachePath(),
785 Complain ? &Reader.Diags : nullptr,
786 PP.getLangOpts());
787}
788
Guy Benyei11169dd2012-12-18 14:30:41 +0000789void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
790 PP.setCounterValue(Value);
791}
792
793//===----------------------------------------------------------------------===//
794// AST reader implementation
795//===----------------------------------------------------------------------===//
796
Nico Weber824285e2014-05-08 04:26:47 +0000797void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
798 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000799 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000800 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000801}
802
Guy Benyei11169dd2012-12-18 14:30:41 +0000803unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
804 return serialization::ComputeHash(Sel);
805}
806
Guy Benyei11169dd2012-12-18 14:30:41 +0000807std::pair<unsigned, unsigned>
808ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000809 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000810
Justin Bogner57ba0b22014-03-28 22:03:24 +0000811 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
812 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000813 return std::make_pair(KeyLen, DataLen);
814}
815
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000816ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000817ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000818 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000819
Guy Benyei11169dd2012-12-18 14:30:41 +0000820 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000821 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
822 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
823 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000824 if (N == 0)
825 return SelTable.getNullarySelector(FirstII);
826 else if (N == 1)
827 return SelTable.getUnarySelector(FirstII);
828
829 SmallVector<IdentifierInfo *, 16> Args;
830 Args.push_back(FirstII);
831 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000832 Args.push_back(Reader.getLocalIdentifier(
833 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000834
835 return SelTable.getSelector(N, Args.data());
836}
837
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000838ASTSelectorLookupTrait::data_type
839ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000841 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000842
843 data_type Result;
844
Justin Bogner57ba0b22014-03-28 22:03:24 +0000845 Result.ID = Reader.getGlobalSelectorID(
846 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000847 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
848 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
849 Result.InstanceBits = FullInstanceBits & 0x3;
850 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
851 Result.FactoryBits = FullFactoryBits & 0x3;
852 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
853 unsigned NumInstanceMethods = FullInstanceBits >> 3;
854 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000855
856 // Load instance methods
857 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000858 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000859 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000860 Result.Instance.push_back(Method);
861 }
862
863 // Load factory methods
864 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +0000865 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
Justin Bogner57ba0b22014-03-28 22:03:24 +0000866 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 Result.Factory.push_back(Method);
868 }
869
870 return Result;
871}
872
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000873unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +0000874 return llvm::djbHash(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000875}
876
877std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000878ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000879 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000880
Justin Bogner57ba0b22014-03-28 22:03:24 +0000881 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
882 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 return std::make_pair(KeyLen, DataLen);
884}
885
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000886ASTIdentifierLookupTraitBase::internal_key_type
887ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000888 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000889 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000890}
891
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000892/// Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000893static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
894 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000895 return II.hadMacroDefinition() ||
896 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000897 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000898 II.hasRevertedTokenIDToIdentifier() ||
Richard Smithdbafb6c2017-06-29 23:23:46 +0000899 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Richard Smitha534a312015-07-21 23:54:07 +0000900 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000901}
902
Richard Smith76c2f2c2015-07-17 20:09:43 +0000903static bool readBit(unsigned &Bits) {
904 bool Value = Bits & 0x1;
905 Bits >>= 1;
906 return Value;
907}
908
Richard Smith79bf9202015-08-24 03:33:22 +0000909IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
910 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000911
Richard Smith79bf9202015-08-24 03:33:22 +0000912 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
913 return Reader.getGlobalIdentifierID(F, RawID >> 1);
914}
915
Richard Smitheb4b58f62016-02-05 01:40:54 +0000916static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
917 if (!II.isFromAST()) {
918 II.setIsFromAST();
919 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
920 if (isInterestingIdentifier(Reader, II, IsModule))
921 II.setChangedSinceDeserialization();
922 }
923}
924
Guy Benyei11169dd2012-12-18 14:30:41 +0000925IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
926 const unsigned char* d,
927 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000928 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +0000929
Justin Bogner57ba0b22014-03-28 22:03:24 +0000930 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000931 bool IsInteresting = RawID & 0x01;
932
933 // Wipe out the "is interesting" bit.
934 RawID = RawID >> 1;
935
Richard Smith76c2f2c2015-07-17 20:09:43 +0000936 // Build the IdentifierInfo and link the identifier ID with it.
937 IdentifierInfo *II = KnownII;
938 if (!II) {
939 II = &Reader.getIdentifierTable().getOwn(k);
940 KnownII = II;
941 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000942 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000943 Reader.markIdentifierUpToDate(II);
944
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
946 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000947 // For uninteresting identifiers, there's nothing else to do. Just notify
948 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000949 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000950 return II;
951 }
952
Justin Bogner57ba0b22014-03-28 22:03:24 +0000953 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
954 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000955 bool CPlusPlusOperatorKeyword = readBit(Bits);
956 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000957 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000958 bool Poisoned = readBit(Bits);
959 bool ExtensionToken = readBit(Bits);
960 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000961
962 assert(Bits == 0 && "Extra bits in the identifier?");
963 DataLen -= 8;
964
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 // Set or check the various bits in the IdentifierInfo structure.
966 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000967 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000968 II->revertTokenIDToIdentifier();
969 if (!F.isModule())
970 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
971 else if (HasRevertedBuiltin && II->getBuiltinID()) {
972 II->revertBuiltin();
973 assert((II->hasRevertedBuiltin() ||
974 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
975 "Incorrect ObjC keyword or builtin ID");
976 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 assert(II->isExtensionToken() == ExtensionToken &&
978 "Incorrect extension token flag");
979 (void)ExtensionToken;
980 if (Poisoned)
981 II->setIsPoisoned(true);
982 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
983 "Incorrect C++ operator keyword flag");
984 (void)CPlusPlusOperatorKeyword;
985
986 // If this identifier is a macro, deserialize the macro
987 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000988 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000989 uint32_t MacroDirectivesOffset =
990 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000991 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000992
Richard Smithd7329392015-04-21 21:46:32 +0000993 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 Reader.SetIdentifierInfo(ID, II);
997
998 // Read all of the declarations visible at global scope with this
999 // name.
1000 if (DataLen > 0) {
1001 SmallVector<uint32_t, 4> DeclIDs;
1002 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +00001003 DeclIDs.push_back(Reader.getGlobalDeclID(
1004 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 Reader.SetGloballyVisibleDecls(II, DeclIDs);
1006 }
1007
1008 return II;
1009}
1010
Richard Smitha06c7e62015-08-26 23:55:49 +00001011DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
1012 : Kind(Name.getNameKind()) {
1013 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001014 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001015 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::ObjCZeroArgSelector:
1018 case DeclarationName::ObjCOneArgSelector:
1019 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001020 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001021 break;
1022 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001023 Data = Name.getCXXOverloadedOperator();
1024 break;
1025 case DeclarationName::CXXLiteralOperatorName:
1026 Data = (uint64_t)Name.getCXXLiteralIdentifier();
1027 break;
Richard Smith35845152017-02-07 01:37:30 +00001028 case DeclarationName::CXXDeductionGuideName:
1029 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
1030 ->getDeclName().getAsIdentifierInfo();
1031 break;
Richard Smitha06c7e62015-08-26 23:55:49 +00001032 case DeclarationName::CXXConstructorName:
1033 case DeclarationName::CXXDestructorName:
1034 case DeclarationName::CXXConversionFunctionName:
1035 case DeclarationName::CXXUsingDirective:
1036 Data = 0;
1037 break;
1038 }
1039}
1040
1041unsigned DeclarationNameKey::getHash() const {
1042 llvm::FoldingSetNodeID ID;
1043 ID.AddInteger(Kind);
1044
1045 switch (Kind) {
1046 case DeclarationName::Identifier:
1047 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001048 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001049 ID.AddString(((IdentifierInfo*)Data)->getName());
1050 break;
1051 case DeclarationName::ObjCZeroArgSelector:
1052 case DeclarationName::ObjCOneArgSelector:
1053 case DeclarationName::ObjCMultiArgSelector:
1054 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1055 break;
1056 case DeclarationName::CXXOperatorName:
1057 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001058 break;
1059 case DeclarationName::CXXConstructorName:
1060 case DeclarationName::CXXDestructorName:
1061 case DeclarationName::CXXConversionFunctionName:
1062 case DeclarationName::CXXUsingDirective:
1063 break;
1064 }
1065
1066 return ID.ComputeHash();
1067}
1068
Richard Smithd88a7f12015-09-01 20:35:42 +00001069ModuleFile *
1070ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1071 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001072
Richard Smithd88a7f12015-09-01 20:35:42 +00001073 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1074 return Reader.getLocalModuleFile(F, ModuleFileID);
1075}
1076
Guy Benyei11169dd2012-12-18 14:30:41 +00001077std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001078ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001079 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001080
Justin Bogner57ba0b22014-03-28 22:03:24 +00001081 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1082 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001083 return std::make_pair(KeyLen, DataLen);
1084}
1085
Richard Smitha06c7e62015-08-26 23:55:49 +00001086ASTDeclContextNameLookupTrait::internal_key_type
1087ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001088 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001089
Vedant Kumar48b4f762018-04-14 01:40:48 +00001090 auto Kind = (DeclarationName::NameKind)*d++;
Richard Smitha06c7e62015-08-26 23:55:49 +00001091 uint64_t Data;
1092 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001093 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001094 case DeclarationName::CXXLiteralOperatorName:
1095 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001096 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001097 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 break;
1099 case DeclarationName::ObjCZeroArgSelector:
1100 case DeclarationName::ObjCOneArgSelector:
1101 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001102 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001103 (uint64_t)Reader.getLocalSelector(
1104 F, endian::readNext<uint32_t, little, unaligned>(
1105 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 break;
1107 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001108 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 case DeclarationName::CXXConstructorName:
1111 case DeclarationName::CXXDestructorName:
1112 case DeclarationName::CXXConversionFunctionName:
1113 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001114 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001115 break;
1116 }
1117
Richard Smitha06c7e62015-08-26 23:55:49 +00001118 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001119}
1120
Richard Smithd88a7f12015-09-01 20:35:42 +00001121void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1122 const unsigned char *d,
1123 unsigned DataLen,
1124 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001125 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001126
Richard Smithd88a7f12015-09-01 20:35:42 +00001127 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1128 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1129 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1130 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001131}
1132
Richard Smith0f4e2c42015-08-06 04:23:48 +00001133bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1134 BitstreamCursor &Cursor,
1135 uint64_t Offset,
1136 DeclContext *DC) {
1137 assert(Offset != 0);
1138
Guy Benyei11169dd2012-12-18 14:30:41 +00001139 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001140 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001141
Richard Smith0f4e2c42015-08-06 04:23:48 +00001142 RecordData Record;
1143 StringRef Blob;
1144 unsigned Code = Cursor.ReadCode();
1145 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1146 if (RecCode != DECL_CONTEXT_LEXICAL) {
1147 Error("Expected lexical block");
1148 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001149 }
1150
Richard Smith82f8fcd2015-08-06 22:07:25 +00001151 assert(!isa<TranslationUnitDecl>(DC) &&
1152 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001153 // If we are handling a C++ class template instantiation, we can see multiple
1154 // lexical updates for the same record. It's important that we select only one
1155 // of them, so that field numbering works properly. Just pick the first one we
1156 // see.
1157 auto &Lex = LexicalDecls[DC];
1158 if (!Lex.first) {
1159 Lex = std::make_pair(
1160 &M, llvm::makeArrayRef(
1161 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1162 Blob.data()),
1163 Blob.size() / 4));
1164 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001165 DC->setHasExternalLexicalStorage(true);
1166 return false;
1167}
Guy Benyei11169dd2012-12-18 14:30:41 +00001168
Richard Smith0f4e2c42015-08-06 04:23:48 +00001169bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1170 BitstreamCursor &Cursor,
1171 uint64_t Offset,
1172 DeclID ID) {
1173 assert(Offset != 0);
1174
1175 SavedStreamPosition SavedPosition(Cursor);
1176 Cursor.JumpToBit(Offset);
1177
1178 RecordData Record;
1179 StringRef Blob;
1180 unsigned Code = Cursor.ReadCode();
1181 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1182 if (RecCode != DECL_CONTEXT_VISIBLE) {
1183 Error("Expected visible lookup table block");
1184 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 }
1186
Richard Smith0f4e2c42015-08-06 04:23:48 +00001187 // We can't safely determine the primary context yet, so delay attaching the
1188 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001189 auto *Data = (const unsigned char*)Blob.data();
1190 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 return false;
1192}
1193
Richard Smith37a93df2017-02-18 00:32:02 +00001194void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithdbafb6c2017-06-29 23:23:46 +00001196 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001197 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001198 Diag(diag::note_module_cache_path)
1199 << PP.getHeaderSearchInfo().getModuleCachePath();
1200 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001201}
1202
1203void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001204 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001205 if (Diags.isDiagnosticInFlight())
1206 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1207 else
1208 Diag(DiagID) << Arg1 << Arg2;
1209}
1210
1211//===----------------------------------------------------------------------===//
1212// Source Manager Deserialization
1213//===----------------------------------------------------------------------===//
1214
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001215/// Read the line table in the source manager block.
Guy Benyei11169dd2012-12-18 14:30:41 +00001216/// \returns true if there was an error.
1217bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001218 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 unsigned Idx = 0;
1220 LineTableInfo &LineTable = SourceMgr.getLineTable();
1221
1222 // Parse the file names
1223 std::map<int, int> FileIDs;
Hans Wennborg14487362017-12-04 22:28:45 +00001224 FileIDs[-1] = -1; // For unspecified filenames.
Richard Smith63078492015-09-01 07:41:55 +00001225 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001226 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001227 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001228 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1229 }
Richard Smith63078492015-09-01 07:41:55 +00001230 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001231
1232 // Parse the line entries
1233 std::vector<LineEntry> Entries;
1234 while (Idx < Record.size()) {
1235 int FID = Record[Idx++];
1236 assert(FID >= 0 && "Serialized line entries for non-local file.");
1237 // Remap FileID from 1-based old view.
1238 FID += F.SLocEntryBaseID - 1;
1239
1240 // Extract the line entries
1241 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001242 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001243 Entries.clear();
1244 Entries.reserve(NumEntries);
1245 for (unsigned I = 0; I != NumEntries; ++I) {
1246 unsigned FileOffset = Record[Idx++];
1247 unsigned LineNo = Record[Idx++];
1248 int FilenameID = FileIDs[Record[Idx++]];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001249 SrcMgr::CharacteristicKind FileKind
1250 = (SrcMgr::CharacteristicKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 unsigned IncludeOffset = Record[Idx++];
1252 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1253 FileKind, IncludeOffset));
1254 }
1255 LineTable.AddEntry(FileID::get(FID), Entries);
1256 }
1257
1258 return false;
1259}
1260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001261/// Read a source manager block
Guy Benyei11169dd2012-12-18 14:30:41 +00001262bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1263 using namespace SrcMgr;
1264
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001265 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001266
1267 // Set the source-location entry cursor to the current position in
1268 // the stream. This cursor will be used to read the contents of the
1269 // source manager block initially, and then lazily read
1270 // source-location entries as needed.
1271 SLocEntryCursor = F.Stream;
1272
1273 // The stream itself is going to skip over the source manager block.
1274 if (F.Stream.SkipBlock()) {
1275 Error("malformed block record in AST file");
1276 return true;
1277 }
1278
1279 // Enter the source manager block.
1280 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1281 Error("malformed source manager block record in AST file");
1282 return true;
1283 }
1284
1285 RecordData Record;
1286 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001287 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001288
Chris Lattnere7b154b2013-01-19 21:39:22 +00001289 switch (E.Kind) {
1290 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1291 case llvm::BitstreamEntry::Error:
1292 Error("malformed block record in AST file");
1293 return true;
1294 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001295 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001296 case llvm::BitstreamEntry::Record:
1297 // The interesting case.
1298 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001300
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001303 StringRef Blob;
1304 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 default: // Default behavior: ignore.
1306 break;
1307
1308 case SM_SLOC_FILE_ENTRY:
1309 case SM_SLOC_BUFFER_ENTRY:
1310 case SM_SLOC_EXPANSION_ENTRY:
1311 // Once we hit one of the source location entries, we're done.
1312 return false;
1313 }
1314 }
1315}
1316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001317/// If a header file is not found at the path that we expect it to be
Guy Benyei11169dd2012-12-18 14:30:41 +00001318/// and the PCH file was moved from its original location, try to resolve the
1319/// file by assuming that header+PCH were moved together and the header is in
1320/// the same place relative to the PCH.
1321static std::string
1322resolveFileRelativeToOriginalDir(const std::string &Filename,
1323 const std::string &OriginalDir,
1324 const std::string &CurrDir) {
1325 assert(OriginalDir != CurrDir &&
1326 "No point trying to resolve the file if the PCH dir didn't change");
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001327
Guy Benyei11169dd2012-12-18 14:30:41 +00001328 using namespace llvm::sys;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001329
Guy Benyei11169dd2012-12-18 14:30:41 +00001330 SmallString<128> filePath(Filename);
1331 fs::make_absolute(filePath);
1332 assert(path::is_absolute(OriginalDir));
1333 SmallString<128> currPCHPath(CurrDir);
1334
1335 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1336 fileDirE = path::end(path::parent_path(filePath));
1337 path::const_iterator origDirI = path::begin(OriginalDir),
1338 origDirE = path::end(OriginalDir);
1339 // Skip the common path components from filePath and OriginalDir.
1340 while (fileDirI != fileDirE && origDirI != origDirE &&
1341 *fileDirI == *origDirI) {
1342 ++fileDirI;
1343 ++origDirI;
1344 }
1345 for (; origDirI != origDirE; ++origDirI)
1346 path::append(currPCHPath, "..");
1347 path::append(currPCHPath, fileDirI, fileDirE);
1348 path::append(currPCHPath, path::filename(Filename));
1349 return currPCHPath.str();
1350}
1351
1352bool ASTReader::ReadSLocEntry(int ID) {
1353 if (ID == 0)
1354 return false;
1355
1356 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1357 Error("source location entry ID out-of-range for AST file");
1358 return true;
1359 }
1360
Richard Smithaada85c2016-02-06 02:06:43 +00001361 // Local helper to read the (possibly-compressed) buffer data following the
1362 // entry record.
1363 auto ReadBuffer = [this](
1364 BitstreamCursor &SLocEntryCursor,
1365 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1366 RecordData Record;
1367 StringRef Blob;
1368 unsigned Code = SLocEntryCursor.ReadCode();
1369 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1370
1371 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001372 if (!llvm::zlib::isAvailable()) {
1373 Error("zlib is not available");
1374 return nullptr;
1375 }
Richard Smithaada85c2016-02-06 02:06:43 +00001376 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001377 if (llvm::Error E =
1378 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1379 Error("could not decompress embedded file contents: " +
1380 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001381 return nullptr;
1382 }
1383 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1384 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1385 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1386 } else {
1387 Error("AST record has invalid code");
1388 return nullptr;
1389 }
1390 };
1391
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1393 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001394 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 unsigned BaseOffset = F->SLocEntryBaseOffset;
1396
1397 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001398 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1399 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 Error("incorrectly-formatted source location entry in AST file");
1401 return true;
1402 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001403
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001405 StringRef Blob;
1406 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 default:
1408 Error("incorrectly-formatted source location entry in AST file");
1409 return true;
1410
1411 case SM_SLOC_FILE_ENTRY: {
1412 // We will detect whether a file changed and return 'Failure' for it, but
1413 // we will also try to fail gracefully by setting up the SLocEntry.
1414 unsigned InputID = Record[4];
1415 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001416 const FileEntry *File = IF.getFile();
1417 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001418
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001419 // Note that we only check if a File was returned. If it was out-of-date
1420 // we have complained but we will continue creating a FileID to recover
1421 // gracefully.
1422 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 return true;
1424
1425 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1426 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1427 // This is the module's main file.
1428 IncludeLoc = getImportLocation(F);
1429 }
Vedant Kumar48b4f762018-04-14 01:40:48 +00001430 SrcMgr::CharacteristicKind
1431 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001432 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1433 ID, BaseOffset + Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001434 SrcMgr::FileInfo &FileInfo =
1435 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 FileInfo.NumCreatedFIDs = Record[5];
1437 if (Record[3])
1438 FileInfo.setHasLineDirectives();
1439
1440 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1441 unsigned NumFileDecls = Record[7];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001442 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1444 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1445 NumFileDecls));
1446 }
Richard Smithaada85c2016-02-06 02:06:43 +00001447
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 const SrcMgr::ContentCache *ContentCache
Richard Smithf3f84612017-06-29 02:19:42 +00001449 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001450 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001451 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1452 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001453 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1454 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001455 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001456 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 }
1458
1459 break;
1460 }
1461
1462 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001463 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001464 unsigned Offset = Record[0];
Vedant Kumar48b4f762018-04-14 01:40:48 +00001465 SrcMgr::CharacteristicKind
1466 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00001467 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001468 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001469 IncludeLoc = getImportLocation(F);
1470 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001471
Richard Smithaada85c2016-02-06 02:06:43 +00001472 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1473 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001475 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001476 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 break;
1478 }
1479
1480 case SM_SLOC_EXPANSION_ENTRY: {
1481 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1482 SourceMgr.createExpansionLoc(SpellingLoc,
1483 ReadSourceLocation(*F, Record[2]),
1484 ReadSourceLocation(*F, Record[3]),
Richard Smithb5f81712018-04-30 05:25:48 +00001485 Record[5],
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 Record[4],
1487 ID,
1488 BaseOffset + Record[0]);
1489 break;
1490 }
1491 }
1492
1493 return false;
1494}
1495
1496std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1497 if (ID == 0)
1498 return std::make_pair(SourceLocation(), "");
1499
1500 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1501 Error("source location entry ID out-of-range for AST file");
1502 return std::make_pair(SourceLocation(), "");
1503 }
1504
1505 // Find which module file this entry lands in.
1506 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001507 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 return std::make_pair(SourceLocation(), "");
1509
1510 // FIXME: Can we map this down to a particular submodule? That would be
1511 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001512 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001513}
1514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001515/// Find the location where the module F is imported.
Guy Benyei11169dd2012-12-18 14:30:41 +00001516SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1517 if (F->ImportLoc.isValid())
1518 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001519
Guy Benyei11169dd2012-12-18 14:30:41 +00001520 // Otherwise we have a PCH. It's considered to be "imported" at the first
1521 // location of its includer.
1522 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001523 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001524 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001525 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 return F->ImportedBy[0]->FirstLoc;
1528}
1529
1530/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1531/// specified cursor. Read the abbreviations that are at the top of the block
1532/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001533bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001534 if (Cursor.EnterSubBlock(BlockID))
1535 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001536
1537 while (true) {
1538 uint64_t Offset = Cursor.GetCurrentBitNo();
1539 unsigned Code = Cursor.ReadCode();
1540
1541 // We expect all abbrevs to be at the start of the block.
1542 if (Code != llvm::bitc::DEFINE_ABBREV) {
1543 Cursor.JumpToBit(Offset);
1544 return false;
1545 }
1546 Cursor.ReadAbbrevRecord();
1547 }
1548}
1549
Richard Smithe40f2ba2013-08-07 21:41:30 +00001550Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001551 unsigned &Idx) {
1552 Token Tok;
1553 Tok.startToken();
1554 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1555 Tok.setLength(Record[Idx++]);
1556 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1557 Tok.setIdentifierInfo(II);
1558 Tok.setKind((tok::TokenKind)Record[Idx++]);
1559 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1560 return Tok;
1561}
1562
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001563MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001564 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001565
1566 // Keep track of where we are in the stream, then jump back there
1567 // after reading this macro.
1568 SavedStreamPosition SavedPosition(Stream);
1569
1570 Stream.JumpToBit(Offset);
1571 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001572 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001573 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001574
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001576 // Advance to the next record, but if we get to the end of the block, don't
1577 // pop it (removing all the abbreviations from the cursor) since we want to
1578 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001579 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001580 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001581
Chris Lattnerefa77172013-01-20 00:00:22 +00001582 switch (Entry.Kind) {
1583 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1584 case llvm::BitstreamEntry::Error:
1585 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001586 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001587 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001588 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001589 case llvm::BitstreamEntry::Record:
1590 // The interesting case.
1591 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001592 }
1593
1594 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 Record.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00001596 PreprocessorRecordTypes RecType =
1597 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001598 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001599 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001600 case PP_MACRO_DIRECTIVE_HISTORY:
1601 return Macro;
1602
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 case PP_MACRO_OBJECT_LIKE:
1604 case PP_MACRO_FUNCTION_LIKE: {
1605 // If we already have a macro, that means that we've hit the end
1606 // of the definition of the macro we were looking for. We're
1607 // done.
1608 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001609 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001610
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001611 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001613 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001614 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001616 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001617
Guy Benyei11169dd2012-12-18 14:30:41 +00001618 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1619 // Decode function-like macro info.
1620 bool isC99VarArgs = Record[NextIndex++];
1621 bool isGNUVarArgs = Record[NextIndex++];
1622 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001623 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001624 unsigned NumArgs = Record[NextIndex++];
1625 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001626 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001627
1628 // Install function-like macro info.
1629 MI->setIsFunctionLike();
1630 if (isC99VarArgs) MI->setIsC99Varargs();
1631 if (isGNUVarArgs) MI->setIsGNUVarargs();
1632 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001633 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 }
1635
Guy Benyei11169dd2012-12-18 14:30:41 +00001636 // Remember that we saw this macro last so that we add the tokens that
1637 // form its body to it.
1638 Macro = MI;
1639
1640 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1641 Record[NextIndex]) {
1642 // We have a macro definition. Register the association
1643 PreprocessedEntityID
1644 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1645 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001646 PreprocessingRecord::PPEntityID PPID =
1647 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
Vedant Kumar48b4f762018-04-14 01:40:48 +00001648 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
Richard Smith66a81862015-05-04 02:25:31 +00001649 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001650 if (PPDef)
1651 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 }
1653
1654 ++NumMacrosRead;
1655 break;
1656 }
1657
1658 case PP_TOKEN: {
1659 // If we see a TOKEN before a PP_MACRO_*, then the file is
1660 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001661 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001662
John McCallf413f5e2013-05-03 00:10:13 +00001663 unsigned Idx = 0;
1664 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 Macro->AddTokenToBody(Tok);
1666 break;
1667 }
1668 }
1669 }
1670}
1671
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001672PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001673ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1674 unsigned LocalID) const {
1675 if (!M.ModuleOffsetMap.empty())
1676 ReadModuleOffsetMap(M);
1677
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001678 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001679 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001680 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001681 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001682
Guy Benyei11169dd2012-12-18 14:30:41 +00001683 return LocalID + I->second;
1684}
1685
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001686unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1687 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001688}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001689
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001690HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001691HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001692 internal_key_type ikey = {FE->getSize(),
1693 M.HasTimestamps ? FE->getModificationTime() : 0,
1694 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001695 return ikey;
1696}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001697
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001698bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001699 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001700 return false;
1701
Mehdi Amini004b9c72016-10-10 22:52:47 +00001702 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001703 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001704
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001706 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001707 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1708 if (!Key.Imported)
1709 return FileMgr.getFile(Key.Filename);
1710
1711 std::string Resolved = Key.Filename;
1712 Reader.ResolveImportedPath(M, Resolved);
1713 return FileMgr.getFile(Resolved);
1714 };
1715
1716 const FileEntry *FEA = GetFile(a);
1717 const FileEntry *FEB = GetFile(b);
1718 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001719}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001720
Guy Benyei11169dd2012-12-18 14:30:41 +00001721std::pair<unsigned, unsigned>
1722HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001723 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001724
Vedant Kumar48b4f762018-04-14 01:40:48 +00001725 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
1726 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001727 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001728}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001729
1730HeaderFileInfoTrait::internal_key_type
1731HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001732 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001733
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001734 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001735 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1736 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001737 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001738 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001739 return ikey;
1740}
1741
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001742HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001743HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001745 using namespace llvm::support;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001746
1747 const unsigned char *End = d + DataLen;
Guy Benyei11169dd2012-12-18 14:30:41 +00001748 HeaderFileInfo HFI;
1749 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001750 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001751 HFI.isImport |= (Flags >> 5) & 0x01;
1752 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1753 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001754 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001755 // FIXME: Find a better way to handle this. Maybe just store a
1756 // "has been included" flag?
1757 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1758 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001759 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1760 M, endian::readNext<uint32_t, little, unaligned>(d));
1761 if (unsigned FrameworkOffset =
1762 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001763 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001764 // since 0 is used as an indicator for "no framework name".
1765 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1766 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1767 }
Richard Smith386bb072015-08-18 23:42:23 +00001768
1769 assert((End - d) % 4 == 0 &&
1770 "Wrong data length in HeaderFileInfo deserialization");
1771 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001772 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001773 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1774 LocalSMID >>= 2;
1775
1776 // This header is part of a module. Associate it with the module to enable
1777 // implicit module import.
1778 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1779 Module *Mod = Reader.getSubmodule(GlobalSMID);
1780 FileManager &FileMgr = Reader.getFileManager();
1781 ModuleMap &ModMap =
1782 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1783
1784 std::string Filename = key.Filename;
1785 if (key.Imported)
1786 Reader.ResolveImportedPath(M, Filename);
1787 // FIXME: This is not always the right filename-as-written, but we're not
1788 // going to use this information to rebuild the module, so it doesn't make
1789 // a lot of difference.
1790 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001791 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1792 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001793 }
1794
Guy Benyei11169dd2012-12-18 14:30:41 +00001795 // This HeaderFileInfo was externally loaded.
1796 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001797 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 return HFI;
1799}
1800
Richard Smithd7329392015-04-21 21:46:32 +00001801void ASTReader::addPendingMacro(IdentifierInfo *II,
1802 ModuleFile *M,
1803 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001804 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1805 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001806}
1807
1808void ASTReader::ReadDefinedMacros() {
1809 // Note that we are loading defined macros.
1810 Deserializing Macros(this);
1811
Vedant Kumar48b4f762018-04-14 01:40:48 +00001812 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001813 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001814
1815 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001816 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 continue;
1818
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001819 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001820 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001821
1822 RecordData Record;
1823 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001824 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001825
Chris Lattnere7b154b2013-01-19 21:39:22 +00001826 switch (E.Kind) {
1827 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1828 case llvm::BitstreamEntry::Error:
1829 Error("malformed block record in AST file");
1830 return;
1831 case llvm::BitstreamEntry::EndBlock:
1832 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001833
Chris Lattnere7b154b2013-01-19 21:39:22 +00001834 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001835 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001836 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001837 default: // Default behavior: ignore.
1838 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001839
Chris Lattnere7b154b2013-01-19 21:39:22 +00001840 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001841 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001842 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001843 if (II->isOutOfDate())
1844 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001845 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001846 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001847
Chris Lattnere7b154b2013-01-19 21:39:22 +00001848 case PP_TOKEN:
1849 // Ignore tokens.
1850 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001852 break;
1853 }
1854 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001855 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 }
1857}
1858
1859namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001860
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001861 /// Visitor class used to look up identifirs in an AST file.
Guy Benyei11169dd2012-12-18 14:30:41 +00001862 class IdentifierLookupVisitor {
1863 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001864 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001865 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001866 unsigned &NumIdentifierLookups;
1867 unsigned &NumIdentifierLookupHits;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001868 IdentifierInfo *Found = nullptr;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001869
Guy Benyei11169dd2012-12-18 14:30:41 +00001870 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001871 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1872 unsigned &NumIdentifierLookups,
1873 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001874 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1875 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001876 NumIdentifierLookups(NumIdentifierLookups),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001877 NumIdentifierLookupHits(NumIdentifierLookupHits) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001878
1879 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001881 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001882 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001883
Vedant Kumar48b4f762018-04-14 01:40:48 +00001884 ASTIdentifierLookupTable *IdTable
1885 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 if (!IdTable)
1887 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001888
1889 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001890 Found);
1891 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001892 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001893 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001894 if (Pos == IdTable->end())
1895 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001896
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 // Dereferencing the iterator has the effect of building the
1898 // IdentifierInfo node and populating it with the various
1899 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001900 ++NumIdentifierLookupHits;
1901 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001902 return true;
1903 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001905 // Retrieve the identifier info found within the module
Guy Benyei11169dd2012-12-18 14:30:41 +00001906 // files.
1907 IdentifierInfo *getIdentifierInfo() const { return Found; }
1908 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001909
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00001910} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001911
1912void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1913 // Note that we are loading an identifier.
1914 Deserializing AnIdentifier(this);
1915
1916 unsigned PriorGeneration = 0;
1917 if (getContext().getLangOpts().Modules)
1918 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001919
1920 // If there is a global index, look there first to determine which modules
1921 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001922 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001923 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001924 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001925 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1926 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001927 }
1928 }
1929
Douglas Gregor7211ac12013-01-25 23:32:03 +00001930 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001931 NumIdentifierLookups,
1932 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001933 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001934 markIdentifierUpToDate(&II);
1935}
1936
1937void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1938 if (!II)
1939 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001940
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 II->setOutOfDate(false);
1942
1943 // Update the generation for this identifier.
1944 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001945 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001946}
1947
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001948void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1949 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001950 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001951
1952 BitstreamCursor &Cursor = M.MacroCursor;
1953 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001954 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001955
Richard Smith713369b2015-04-23 20:40:50 +00001956 struct ModuleMacroRecord {
1957 SubmoduleID SubModID;
1958 MacroInfo *MI;
1959 SmallVector<SubmoduleID, 8> Overrides;
1960 };
1961 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001962
Richard Smithd7329392015-04-21 21:46:32 +00001963 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1964 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1965 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001966 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001967 while (true) {
1968 llvm::BitstreamEntry Entry =
1969 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1970 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1971 Error("malformed block record in AST file");
1972 return;
1973 }
1974
1975 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001976 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001977 case PP_MACRO_DIRECTIVE_HISTORY:
1978 break;
1979
1980 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001981 ModuleMacros.push_back(ModuleMacroRecord());
1982 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001983 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1984 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001985 for (int I = 2, N = Record.size(); I != N; ++I)
1986 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001987 continue;
1988 }
1989
1990 default:
1991 Error("malformed block record in AST file");
1992 return;
1993 }
1994
1995 // We found the macro directive history; that's the last record
1996 // for this macro.
1997 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001998 }
1999
Richard Smithd7329392015-04-21 21:46:32 +00002000 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00002001 {
2002 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00002003 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00002004 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00002005 Overrides.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00002006 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00002007 Module *Mod = getSubmodule(ModID);
2008 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002009 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00002010 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00002011 }
2012
2013 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00002014 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00002015 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00002016 }
2017 }
2018
2019 // Don't read the directive history for a module; we don't have anywhere
2020 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00002021 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00002022 return;
2023
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002024 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00002025 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002026 unsigned Idx = 0, N = Record.size();
2027 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00002028 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002029 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002030 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002031 switch (K) {
2032 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00002033 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00002034 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002035 break;
2036 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002037 case MacroDirective::MD_Undefine:
Richard Smith3981b172015-04-30 02:16:23 +00002038 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002039 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00002040 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00002041 bool isPublic = Record[Idx++];
2042 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
2043 break;
2044 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002045
2046 if (!Latest)
2047 Latest = MD;
2048 if (Earliest)
2049 Earliest->setPrevious(MD);
2050 Earliest = MD;
2051 }
2052
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002053 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002054 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002055}
2056
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002057ASTReader::InputFileInfo
2058ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002059 // Go find this input file.
2060 BitstreamCursor &Cursor = F.InputFilesCursor;
2061 SavedStreamPosition SavedPosition(Cursor);
2062 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2063
2064 unsigned Code = Cursor.ReadCode();
2065 RecordData Record;
2066 StringRef Blob;
2067
2068 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2069 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2070 "invalid record type for input file");
2071 (void)Result;
2072
2073 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002074 InputFileInfo R;
2075 R.StoredSize = static_cast<off_t>(Record[1]);
2076 R.StoredTime = static_cast<time_t>(Record[2]);
2077 R.Overridden = static_cast<bool>(Record[3]);
2078 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002079 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002080 R.Filename = Blob;
2081 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002082 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002083}
2084
Manman Renc8c94152016-10-21 23:35:03 +00002085static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002086InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002087 // If this ID is bogus, just return an empty input file.
2088 if (ID == 0 || ID > F.InputFilesLoaded.size())
2089 return InputFile();
2090
2091 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002092 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002093 return F.InputFilesLoaded[ID-1];
2094
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002095 if (F.InputFilesLoaded[ID-1].isNotFound())
2096 return InputFile();
2097
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002099 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002100 SavedStreamPosition SavedPosition(Cursor);
2101 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002102
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002103 InputFileInfo FI = readInputFileInfo(F, ID);
2104 off_t StoredSize = FI.StoredSize;
2105 time_t StoredTime = FI.StoredTime;
2106 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002107 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002108 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002109
Richard Smitha8cfffa2015-11-26 02:04:16 +00002110 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002111 // If we didn't find the file, resolve it relative to the
2112 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002113 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2114 F.OriginalDir != F.BaseDirectory) {
2115 std::string Resolved = resolveFileRelativeToOriginalDir(
2116 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002117 if (!Resolved.empty())
2118 File = FileMgr.getFile(Resolved);
2119 }
2120
2121 // For an overridden file, create a virtual file with the stored
2122 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002123 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002124 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002125
Craig Toppera13603a2014-05-22 05:54:18 +00002126 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002127 if (Complain) {
2128 std::string ErrorStr = "could not find file '";
2129 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002130 ErrorStr += "' referenced by AST file '";
2131 ErrorStr += F.FileName;
2132 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002133 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002134 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002135 // Record that we didn't find the file.
2136 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2137 return InputFile();
2138 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002139
Ben Langmuir198c1682014-03-07 07:27:49 +00002140 // Check if there was a request to override the contents of the file
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002141 // that was part of the precompiled header. Overriding such a file
Ben Langmuir198c1682014-03-07 07:27:49 +00002142 // can lead to problems when lexing using the source locations from the
2143 // PCH.
2144 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002145 // FIXME: Reject if the overrides are different.
2146 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002147 if (Complain)
2148 Error(diag::err_fe_pch_file_overridden, Filename);
2149 // After emitting the diagnostic, recover by disabling the override so
2150 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002151 //
2152 // FIXME: This recovery is just as broken as the original state; there may
2153 // be another precompiled module that's using the overridden contents, or
2154 // we might be half way through parsing it. Instead, we should treat the
2155 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002156 SM.disableFileContentsOverride(File);
2157 // The FileEntry is a virtual file entry with the size of the contents
2158 // that would override the original contents. Set it to the original's
2159 // size/time.
2160 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2161 StoredSize, StoredTime);
2162 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002163
Ben Langmuir198c1682014-03-07 07:27:49 +00002164 bool IsOutOfDate = false;
2165
2166 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002167 if (!Overridden && //
2168 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002169 (StoredTime && StoredTime != File->getModificationTime() &&
2170 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002171 )) {
2172 if (Complain) {
2173 // Build a list of the PCH imports that got us here (in reverse).
2174 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002175 while (!ImportStack.back()->ImportedBy.empty())
Ben Langmuir198c1682014-03-07 07:27:49 +00002176 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002177
Ben Langmuir198c1682014-03-07 07:27:49 +00002178 // The top-level PCH is stale.
2179 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002180 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2181 if (DiagnosticKind == 0)
2182 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2183 else if (DiagnosticKind == 1)
2184 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2185 else
2186 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002187
Ben Langmuir198c1682014-03-07 07:27:49 +00002188 // Print the import stack.
2189 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2190 Diag(diag::note_pch_required_by)
2191 << Filename << ImportStack[0]->FileName;
2192 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002193 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002194 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002195 }
2196
Ben Langmuir198c1682014-03-07 07:27:49 +00002197 if (!Diags.isDiagnosticInFlight())
2198 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002199 }
2200
Ben Langmuir198c1682014-03-07 07:27:49 +00002201 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002202 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002203 // FIXME: If the file is overridden and we've already opened it,
2204 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002205
Richard Smitha8cfffa2015-11-26 02:04:16 +00002206 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002207
2208 // Note that we've loaded this input file.
2209 F.InputFilesLoaded[ID-1] = IF;
2210 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002211}
2212
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002213/// If we are loading a relocatable PCH or module file, and the filename
Richard Smith7ed1bc92014-12-05 22:42:13 +00002214/// is not an absolute path, add the system or module root to the beginning of
2215/// the file name.
2216void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2217 // Resolve relative to the base directory, if we have one.
2218 if (!M.BaseDirectory.empty())
2219 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002220}
2221
Richard Smith7ed1bc92014-12-05 22:42:13 +00002222void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2224 return;
2225
Richard Smith7ed1bc92014-12-05 22:42:13 +00002226 SmallString<128> Buffer;
2227 llvm::sys::path::append(Buffer, Prefix, Filename);
2228 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002229}
2230
Richard Smith0f99d6a2015-08-09 08:48:41 +00002231static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2232 switch (ARR) {
2233 case ASTReader::Failure: return true;
2234 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2235 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2236 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2237 case ASTReader::ConfigurationMismatch:
2238 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2239 case ASTReader::HadErrors: return true;
2240 case ASTReader::Success: return false;
2241 }
2242
2243 llvm_unreachable("unknown ASTReadResult");
2244}
2245
Richard Smith0516b182015-09-08 19:40:14 +00002246ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2247 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2248 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002249 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002250 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2251 return Failure;
2252
2253 // Read all of the records in the options block.
2254 RecordData Record;
2255 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002256 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002257 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002258
Richard Smith0516b182015-09-08 19:40:14 +00002259 switch (Entry.Kind) {
2260 case llvm::BitstreamEntry::Error:
2261 case llvm::BitstreamEntry::SubBlock:
2262 return Failure;
2263
2264 case llvm::BitstreamEntry::EndBlock:
2265 return Result;
2266
2267 case llvm::BitstreamEntry::Record:
2268 // The interesting case.
2269 break;
2270 }
2271
2272 // Read and process a record.
2273 Record.clear();
2274 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2275 case LANGUAGE_OPTIONS: {
2276 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2277 if (ParseLanguageOptions(Record, Complain, Listener,
2278 AllowCompatibleConfigurationMismatch))
2279 Result = ConfigurationMismatch;
2280 break;
2281 }
2282
2283 case TARGET_OPTIONS: {
2284 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2285 if (ParseTargetOptions(Record, Complain, Listener,
2286 AllowCompatibleConfigurationMismatch))
2287 Result = ConfigurationMismatch;
2288 break;
2289 }
2290
Richard Smith0516b182015-09-08 19:40:14 +00002291 case FILE_SYSTEM_OPTIONS: {
2292 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2293 if (!AllowCompatibleConfigurationMismatch &&
2294 ParseFileSystemOptions(Record, Complain, Listener))
2295 Result = ConfigurationMismatch;
2296 break;
2297 }
2298
2299 case HEADER_SEARCH_OPTIONS: {
2300 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2301 if (!AllowCompatibleConfigurationMismatch &&
2302 ParseHeaderSearchOptions(Record, Complain, Listener))
2303 Result = ConfigurationMismatch;
2304 break;
2305 }
2306
2307 case PREPROCESSOR_OPTIONS:
2308 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2309 if (!AllowCompatibleConfigurationMismatch &&
2310 ParsePreprocessorOptions(Record, Complain, Listener,
2311 SuggestedPredefines))
2312 Result = ConfigurationMismatch;
2313 break;
2314 }
2315 }
2316}
2317
Guy Benyei11169dd2012-12-18 14:30:41 +00002318ASTReader::ASTReadResult
2319ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002320 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002321 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002322 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002323 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002324 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002325
2326 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2327 Error("malformed block record in AST file");
2328 return Failure;
2329 }
2330
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002331 // Lambda to read the unhashed control block the first time it's called.
2332 //
2333 // For PCM files, the unhashed control block cannot be read until after the
2334 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2335 // need to look ahead before reading the IMPORTS record. For consistency,
2336 // this block is always read somehow (see BitstreamEntry::EndBlock).
2337 bool HasReadUnhashedControlBlock = false;
2338 auto readUnhashedControlBlockOnce = [&]() {
2339 if (!HasReadUnhashedControlBlock) {
2340 HasReadUnhashedControlBlock = true;
2341 if (ASTReadResult Result =
2342 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2343 return Result;
2344 }
2345 return Success;
2346 };
2347
Guy Benyei11169dd2012-12-18 14:30:41 +00002348 // Read all of the records and blocks in the control block.
2349 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002350 unsigned NumInputs = 0;
2351 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002352 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002353 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002354
Chris Lattnere7b154b2013-01-19 21:39:22 +00002355 switch (Entry.Kind) {
2356 case llvm::BitstreamEntry::Error:
2357 Error("malformed block record in AST file");
2358 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002359 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002360 // Validate the module before returning. This call catches an AST with
2361 // no module name and no imports.
2362 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2363 return Result;
2364
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002365 // Validate input files.
2366 const HeaderSearchOptions &HSOpts =
2367 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002368
Richard Smitha1825302014-10-23 22:18:29 +00002369 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002370 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2371 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002372 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2373 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002375
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002376 // If we are reading a module, we will create a verification timestamp,
2377 // so we verify all input files. Otherwise, verify only user input
2378 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002379
2380 unsigned N = NumUserInputs;
2381 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002382 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002383 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002384 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002385 N = NumInputs;
2386
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002387 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002388 InputFile IF = getInputFile(F, I+1, Complain);
2389 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002391 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002393
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002394 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002395 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002396
Ben Langmuircb69b572014-03-07 06:40:32 +00002397 if (Listener && Listener->needsInputFileVisitation()) {
2398 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2399 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002400 for (unsigned I = 0; I < N; ++I) {
2401 bool IsSystem = I >= NumUserInputs;
2402 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002403 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002404 F.Kind == MK_ExplicitModule ||
2405 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002406 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002407 }
2408
Richard Smith8a308ec2015-11-05 00:54:55 +00002409 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002410 }
2411
Chris Lattnere7b154b2013-01-19 21:39:22 +00002412 case llvm::BitstreamEntry::SubBlock:
2413 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 case INPUT_FILES_BLOCK_ID:
2415 F.InputFilesCursor = Stream;
2416 if (Stream.SkipBlock() || // Skip with the main cursor
2417 // Read the abbreviations
2418 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2419 Error("malformed block record in AST file");
2420 return Failure;
2421 }
2422 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002423
2424 case OPTIONS_BLOCK_ID:
2425 // If we're reading the first module for this group, check its options
2426 // are compatible with ours. For modules it imports, no further checking
2427 // is required, because we checked them when we built it.
2428 if (Listener && !ImportedBy) {
2429 // Should we allow the configuration of the module file to differ from
2430 // the configuration of the current translation unit in a compatible
2431 // way?
2432 //
2433 // FIXME: Allow this for files explicitly specified with -include-pch.
2434 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002435 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002436
Richard Smith8a308ec2015-11-05 00:54:55 +00002437 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2438 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002439 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002440 if (Result == Failure) {
2441 Error("malformed block record in AST file");
2442 return Result;
2443 }
2444
Richard Smith8a308ec2015-11-05 00:54:55 +00002445 if (DisableValidation ||
2446 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2447 Result = Success;
2448
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002449 // If we can't load the module, exit early since we likely
2450 // will rebuild the module anyway. The stream may be in the
2451 // middle of a block.
2452 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002453 return Result;
2454 } else if (Stream.SkipBlock()) {
2455 Error("malformed block record in AST file");
2456 return Failure;
2457 }
2458 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002459
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002461 if (Stream.SkipBlock()) {
2462 Error("malformed block record in AST file");
2463 return Failure;
2464 }
2465 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002467
Chris Lattnere7b154b2013-01-19 21:39:22 +00002468 case llvm::BitstreamEntry::Record:
2469 // The interesting case.
2470 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 }
2472
2473 // Read and process a record.
2474 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002475 StringRef Blob;
2476 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002477 case METADATA: {
2478 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2479 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002480 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2481 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 return VersionMismatch;
2483 }
2484
Richard Smithe75ee0f2015-08-17 07:13:32 +00002485 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2487 Diag(diag::err_pch_with_compiler_errors);
2488 return HadErrors;
2489 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002490 if (hasErrors) {
2491 Diags.ErrorOccurred = true;
2492 Diags.UncompilableErrorOccurred = true;
2493 Diags.UnrecoverableErrorOccurred = true;
2494 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002495
2496 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002497 // Relative paths in a relocatable PCH are relative to our sysroot.
2498 if (F.RelocatablePCH)
2499 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002500
Richard Smithe75ee0f2015-08-17 07:13:32 +00002501 F.HasTimestamps = Record[5];
2502
Guy Benyei11169dd2012-12-18 14:30:41 +00002503 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002504 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2506 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002507 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002508 return VersionMismatch;
2509 }
2510 break;
2511 }
2512
2513 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002514 // Validate the AST before processing any imports (otherwise, untangling
2515 // them can be error-prone and expensive). A module will have a name and
2516 // will already have been validated, but this catches the PCH case.
2517 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2518 return Result;
2519
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002520 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002521 unsigned Idx = 0, N = Record.size();
2522 while (Idx < N) {
2523 // Read information about the AST file.
Vedant Kumar48b4f762018-04-14 01:40:48 +00002524 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 // The import location will be the local one for now; we will adjust
2526 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002527 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002528 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002529 ReadUntranslatedSourceLocation(Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00002530 off_t StoredSize = (off_t)Record[Idx++];
2531 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002532 ASTFileSignature StoredSignature = {
2533 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2534 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2535 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002536
2537 std::string ImportedName = ReadString(Record, Idx);
2538 std::string ImportedFile;
2539
2540 // For prebuilt and explicit modules first consult the file map for
2541 // an override. Note that here we don't search prebuilt module
2542 // directories, only the explicit name to file mappings. Also, we will
2543 // still verify the size/signature making sure it is essentially the
2544 // same file but perhaps in a different location.
2545 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2546 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2547 ImportedName, /*FileMapOnly*/ true);
2548
2549 if (ImportedFile.empty())
2550 ImportedFile = ReadPath(F, Record, Idx);
2551 else
2552 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002553
Richard Smith0f99d6a2015-08-09 08:48:41 +00002554 // If our client can't cope with us being out of date, we can't cope with
2555 // our dependency being missing.
2556 unsigned Capabilities = ClientLoadCapabilities;
2557 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2558 Capabilities &= ~ARR_Missing;
2559
Guy Benyei11169dd2012-12-18 14:30:41 +00002560 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002561 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2562 Loaded, StoredSize, StoredModTime,
2563 StoredSignature, Capabilities);
2564
2565 // If we diagnosed a problem, produce a backtrace.
2566 if (isDiagnosedResult(Result, Capabilities))
2567 Diag(diag::note_module_file_imported_by)
2568 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2569
2570 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 case Failure: return Failure;
2572 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002573 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002574 case OutOfDate: return OutOfDate;
2575 case VersionMismatch: return VersionMismatch;
2576 case ConfigurationMismatch: return ConfigurationMismatch;
2577 case HadErrors: return HadErrors;
2578 case Success: break;
2579 }
2580 }
2581 break;
2582 }
2583
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 case ORIGINAL_FILE:
2585 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002586 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002588 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 break;
2590
2591 case ORIGINAL_FILE_ID:
2592 F.OriginalSourceFileID = FileID::get(Record[0]);
2593 break;
2594
2595 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002596 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002597 break;
2598
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002599 case MODULE_NAME:
2600 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002601 if (Listener)
2602 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002603
2604 // Validate the AST as soon as we have a name so we can exit early on
2605 // failure.
2606 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2607 return Result;
Vedant Kumar48b4f762018-04-14 01:40:48 +00002608
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002609 break;
2610
Richard Smith223d3f22014-12-06 03:21:08 +00002611 case MODULE_DIRECTORY: {
2612 assert(!F.ModuleName.empty() &&
2613 "MODULE_DIRECTORY found before MODULE_NAME");
2614 // If we've already loaded a module map file covering this module, we may
2615 // have a better path for it (relative to the current build).
2616 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2617 if (M && M->Directory) {
2618 // If we're implicitly loading a module, the base directory can't
2619 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002620 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002621 const DirectoryEntry *BuildDir =
2622 PP.getFileManager().getDirectory(Blob);
2623 if (!BuildDir || BuildDir != M->Directory) {
2624 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2625 Diag(diag::err_imported_module_relocated)
2626 << F.ModuleName << Blob << M->Directory->getName();
2627 return OutOfDate;
2628 }
2629 }
2630 F.BaseDirectory = M->Directory->getName();
2631 } else {
2632 F.BaseDirectory = Blob;
2633 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002634 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002635 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002636
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002637 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002638 if (ASTReadResult Result =
2639 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2640 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002641 break;
2642
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002643 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002644 NumInputs = Record[0];
2645 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002646 F.InputFileOffsets =
2647 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002648 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002649 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 break;
2651 }
2652 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002653}
2654
Ben Langmuir2c9af442014-04-10 17:57:43 +00002655ASTReader::ASTReadResult
2656ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002657 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002658
2659 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2660 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002661 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 }
2663
2664 // Read all of the records and blocks for the AST file.
2665 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002666 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002667 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002668
Chris Lattnere7b154b2013-01-19 21:39:22 +00002669 switch (Entry.Kind) {
2670 case llvm::BitstreamEntry::Error:
2671 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002672 return Failure;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00002673 case llvm::BitstreamEntry::EndBlock:
Richard Smithc0fbba72013-04-03 22:49:41 +00002674 // Outside of C++, we do not store a lookup map for the translation unit.
2675 // Instead, mark it as needing a lookup map to be built if this module
2676 // contains any declarations lexically within it (which it always does!).
2677 // This usually has no cost, since we very rarely need the lookup map for
2678 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002679 if (ASTContext *Ctx = ContextObj) {
2680 DeclContext *DC = Ctx->getTranslationUnitDecl();
2681 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2682 DC->setMustBuildLookupTable();
2683 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002684
Ben Langmuir2c9af442014-04-10 17:57:43 +00002685 return Success;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002686 case llvm::BitstreamEntry::SubBlock:
2687 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 case DECLTYPES_BLOCK_ID:
2689 // We lazily load the decls block, but we want to set up the
2690 // DeclsCursor cursor to point into it. Clone our current bitcode
2691 // cursor to it, enter the block and read the abbrevs in that block.
2692 // With the main cursor, we just skip over it.
2693 F.DeclsCursor = Stream;
2694 if (Stream.SkipBlock() || // Skip with the main cursor.
2695 // Read the abbrevs.
2696 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2697 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002698 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 }
2700 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002701
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 case PREPROCESSOR_BLOCK_ID:
2703 F.MacroCursor = Stream;
2704 if (!PP.getExternalSource())
2705 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002706
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 if (Stream.SkipBlock() ||
2708 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2709 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002710 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 }
2712 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2713 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002714
Guy Benyei11169dd2012-12-18 14:30:41 +00002715 case PREPROCESSOR_DETAIL_BLOCK_ID:
2716 F.PreprocessorDetailCursor = Stream;
2717 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002718 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002720 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002721 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002722 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002724 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002725
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 if (!PP.getPreprocessingRecord())
2727 PP.createPreprocessingRecord();
2728 if (!PP.getPreprocessingRecord()->getExternalSource())
2729 PP.getPreprocessingRecord()->SetExternalSource(*this);
2730 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 case SOURCE_MANAGER_BLOCK_ID:
2733 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002734 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002738 if (ASTReadResult Result =
2739 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002740 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002742
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002744 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 if (Stream.SkipBlock() ||
2746 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2747 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002748 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 }
2750 CommentsCursors.push_back(std::make_pair(C, &F));
2751 break;
2752 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002753
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002755 if (Stream.SkipBlock()) {
2756 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002757 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002758 }
2759 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 }
2761 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002762
Chris Lattnere7b154b2013-01-19 21:39:22 +00002763 case llvm::BitstreamEntry::Record:
2764 // The interesting case.
2765 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 }
2767
2768 // Read and process a record.
2769 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002770 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002771 auto RecordType =
2772 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2773
2774 // If we're not loading an AST context, we don't care about most records.
2775 if (!ContextObj) {
2776 switch (RecordType) {
2777 case IDENTIFIER_TABLE:
2778 case IDENTIFIER_OFFSET:
2779 case INTERESTING_IDENTIFIERS:
2780 case STATISTICS:
2781 case PP_CONDITIONAL_STACK:
2782 case PP_COUNTER_VALUE:
2783 case SOURCE_LOCATION_OFFSETS:
2784 case MODULE_OFFSET_MAP:
2785 case SOURCE_MANAGER_LINE_TABLE:
2786 case SOURCE_LOCATION_PRELOADS:
2787 case PPD_ENTITIES_OFFSETS:
2788 case HEADER_SEARCH_TABLE:
2789 case IMPORTED_MODULES:
2790 case MACRO_OFFSET:
2791 break;
2792 default:
2793 continue;
2794 }
2795 }
2796
2797 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002798 default: // Default behavior: ignore.
2799 break;
2800
2801 case TYPE_OFFSET: {
2802 if (F.LocalNumTypes != 0) {
2803 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002804 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002806 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 F.LocalNumTypes = Record[0];
2808 unsigned LocalBaseTypeIndex = Record[1];
2809 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002810
Guy Benyei11169dd2012-12-18 14:30:41 +00002811 if (F.LocalNumTypes > 0) {
2812 // Introduce the global -> local mapping for types within this module.
2813 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002814
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 // Introduce the local -> global mapping for types within this module.
2816 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002817 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002819
2820 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002821 }
2822 break;
2823 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002824
Guy Benyei11169dd2012-12-18 14:30:41 +00002825 case DECL_OFFSET: {
2826 if (F.LocalNumDecls != 0) {
2827 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002828 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002830 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 F.LocalNumDecls = Record[0];
2832 unsigned LocalBaseDeclID = Record[1];
2833 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002834
Guy Benyei11169dd2012-12-18 14:30:41 +00002835 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002836 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002837 // module.
2838 GlobalDeclMap.insert(
2839 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002840
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 // Introduce the local -> global mapping for declarations within this
2842 // module.
2843 F.DeclRemap.insertOrReplace(
2844 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002845
Guy Benyei11169dd2012-12-18 14:30:41 +00002846 // Introduce the global -> local mapping for declarations within this
2847 // module.
2848 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002849
Ben Langmuir52ca6782014-10-20 16:27:32 +00002850 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2851 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002852 break;
2853 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002854
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002856 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002857 LexicalContents Contents(
2858 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2859 Blob.data()),
2860 static_cast<unsigned int>(Blob.size() / 4));
2861 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002862 TU->setHasExternalLexicalStorage(true);
2863 break;
2864 }
2865
2866 case UPDATE_VISIBLE: {
2867 unsigned Idx = 0;
2868 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002869 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002870 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002871 // If we've already loaded the decl, perform the updates when we finish
2872 // loading this block.
2873 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002874 PendingUpdateRecords.push_back(
2875 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002876 break;
2877 }
2878
2879 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002880 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002881 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002882 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2883 (const unsigned char *)F.IdentifierTableData + Record[0],
2884 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2885 (const unsigned char *)F.IdentifierTableData,
2886 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002887
Guy Benyei11169dd2012-12-18 14:30:41 +00002888 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2889 }
2890 break;
2891
2892 case IDENTIFIER_OFFSET: {
2893 if (F.LocalNumIdentifiers != 0) {
2894 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002895 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002897 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002898 F.LocalNumIdentifiers = Record[0];
2899 unsigned LocalBaseIdentifierID = Record[1];
2900 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002901
Guy Benyei11169dd2012-12-18 14:30:41 +00002902 if (F.LocalNumIdentifiers > 0) {
2903 // Introduce the global -> local mapping for identifiers within this
2904 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002905 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002907
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 // Introduce the local -> global mapping for identifiers within this
2909 // module.
2910 F.IdentifierRemap.insertOrReplace(
2911 std::make_pair(LocalBaseIdentifierID,
2912 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002913
Ben Langmuir52ca6782014-10-20 16:27:32 +00002914 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2915 + F.LocalNumIdentifiers);
2916 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 break;
2918 }
2919
Richard Smith33e0f7e2015-07-22 02:08:40 +00002920 case INTERESTING_IDENTIFIERS:
2921 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2922 break;
2923
Ben Langmuir332aafe2014-01-31 01:06:56 +00002924 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002925 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2926 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002928 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 break;
2930
David Blaikie9ffe5a32017-01-30 05:00:26 +00002931 case MODULAR_CODEGEN_DECLS:
2932 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2933 // them (ie: if we're not codegenerating this module).
2934 if (F.Kind == MK_MainFile)
2935 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2936 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2937 break;
2938
Guy Benyei11169dd2012-12-18 14:30:41 +00002939 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002940 if (SpecialTypes.empty()) {
2941 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2942 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2943 break;
2944 }
2945
2946 if (SpecialTypes.size() != Record.size()) {
2947 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002948 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002949 }
2950
2951 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2952 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2953 if (!SpecialTypes[I])
2954 SpecialTypes[I] = ID;
2955 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2956 // merge step?
2957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 break;
2959
2960 case STATISTICS:
2961 TotalNumStatements += Record[0];
2962 TotalNumMacros += Record[1];
2963 TotalLexicalDeclContexts += Record[2];
2964 TotalVisibleDeclContexts += Record[3];
2965 break;
2966
2967 case UNUSED_FILESCOPED_DECLS:
2968 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2969 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2970 break;
2971
2972 case DELEGATING_CTORS:
2973 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2974 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2975 break;
2976
2977 case WEAK_UNDECLARED_IDENTIFIERS:
2978 if (Record.size() % 4 != 0) {
2979 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002980 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002982
2983 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 // files. This isn't the way to do it :)
2985 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002986
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 // Translate the weak, undeclared identifiers into global IDs.
2988 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2989 WeakUndeclaredIdentifiers.push_back(
2990 getGlobalIdentifierID(F, Record[I++]));
2991 WeakUndeclaredIdentifiers.push_back(
2992 getGlobalIdentifierID(F, Record[I++]));
2993 WeakUndeclaredIdentifiers.push_back(
2994 ReadSourceLocation(F, Record, I).getRawEncoding());
2995 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2996 }
2997 break;
2998
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003000 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 F.LocalNumSelectors = Record[0];
3002 unsigned LocalBaseSelectorID = Record[1];
3003 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003004
Guy Benyei11169dd2012-12-18 14:30:41 +00003005 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003006 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003007 // module.
3008 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003009
3010 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 // module.
3012 F.SelectorRemap.insertOrReplace(
3013 std::make_pair(LocalBaseSelectorID,
3014 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003015
3016 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00003017 }
3018 break;
3019 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003020
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003022 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 if (Record[0])
3024 F.SelectorLookupTable
3025 = ASTSelectorLookupTable::Create(
3026 F.SelectorLookupTableData + Record[0],
3027 F.SelectorLookupTableData,
3028 ASTSelectorLookupTrait(*this, F));
3029 TotalNumMethodPoolEntries += Record[1];
3030 break;
3031
3032 case REFERENCED_SELECTOR_POOL:
3033 if (!Record.empty()) {
3034 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003035 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 Record[Idx++]));
3037 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
3038 getRawEncoding());
3039 }
3040 }
3041 break;
3042
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003043 case PP_CONDITIONAL_STACK:
3044 if (!Record.empty()) {
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003045 unsigned Idx = 0, End = Record.size() - 1;
3046 bool ReachedEOFWhileSkipping = Record[Idx++];
3047 llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
3048 if (ReachedEOFWhileSkipping) {
3049 SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
3050 SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
3051 bool FoundNonSkipPortion = Record[Idx++];
3052 bool FoundElse = Record[Idx++];
3053 SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
3054 SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
3055 FoundElse, ElseLoc);
3056 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003057 SmallVector<PPConditionalInfo, 4> ConditionalStack;
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003058 while (Idx < End) {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003059 auto Loc = ReadSourceLocation(F, Record, Idx);
3060 bool WasSkipping = Record[Idx++];
3061 bool FoundNonSkip = Record[Idx++];
3062 bool FoundElse = Record[Idx++];
3063 ConditionalStack.push_back(
3064 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3065 }
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +00003066 PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00003067 }
3068 break;
3069
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 case PP_COUNTER_VALUE:
3071 if (!Record.empty() && Listener)
3072 Listener->ReadCounter(F, Record[0]);
3073 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003074
Guy Benyei11169dd2012-12-18 14:30:41 +00003075 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003076 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 F.NumFileSortedDecls = Record[0];
3078 break;
3079
3080 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003081 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003082 F.LocalNumSLocEntries = Record[0];
3083 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003084 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003085 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003087 if (!F.SLocEntryBaseID) {
3088 Error("ran out of source locations");
3089 break;
3090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 // Make our entry in the range map. BaseID is negative and growing, so
3092 // we invert it. Because we invert it, though, we need the other end of
3093 // the range.
3094 unsigned RangeStart =
3095 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3096 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3097 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3098
3099 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3100 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3101 GlobalSLocOffsetMap.insert(
3102 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3103 - SLocSpaceSize,&F));
3104
3105 // Initialize the remapping table.
3106 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003107 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003109 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003111
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 TotalNumSLocEntries += F.LocalNumSLocEntries;
3113 break;
3114 }
3115
Richard Smith37a93df2017-02-18 00:32:02 +00003116 case MODULE_OFFSET_MAP:
3117 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003119
3120 case SOURCE_MANAGER_LINE_TABLE:
3121 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003122 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003123 break;
3124
3125 case SOURCE_LOCATION_PRELOADS: {
3126 // Need to transform from the local view (1-based IDs) to the global view,
3127 // which is based off F.SLocEntryBaseID.
3128 if (!F.PreloadSLocEntries.empty()) {
3129 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003130 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003131 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003132
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 F.PreloadSLocEntries.swap(Record);
3134 break;
3135 }
3136
3137 case EXT_VECTOR_DECLS:
3138 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3139 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3140 break;
3141
3142 case VTABLE_USES:
3143 if (Record.size() % 3 != 0) {
3144 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003145 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003147
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 // Later tables overwrite earlier ones.
3149 // FIXME: Modules will have some trouble with this. This is clearly not
3150 // the right way to do this.
3151 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003152
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3154 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3155 VTableUses.push_back(
3156 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3157 VTableUses.push_back(Record[Idx++]);
3158 }
3159 break;
3160
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 case PENDING_IMPLICIT_INSTANTIATIONS:
3162 if (PendingInstantiations.size() % 2 != 0) {
3163 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003164 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 }
3166
3167 if (Record.size() % 2 != 0) {
3168 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003169 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 }
3171
3172 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3173 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3174 PendingInstantiations.push_back(
3175 ReadSourceLocation(F, Record, I).getRawEncoding());
3176 }
3177 break;
3178
3179 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003180 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003181 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003182 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003183 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003184 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3185 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3186 break;
3187
3188 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003189 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3190 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3191 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003192
3193 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003194
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 unsigned StartingID;
3196 if (!PP.getPreprocessingRecord())
3197 PP.createPreprocessingRecord();
3198 if (!PP.getPreprocessingRecord()->getExternalSource())
3199 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003200 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003201 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003202 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003203 F.BasePreprocessedEntityID = StartingID;
3204
3205 if (F.NumPreprocessedEntities > 0) {
3206 // Introduce the global -> local mapping for preprocessed entities in
3207 // this module.
3208 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003209
Guy Benyei11169dd2012-12-18 14:30:41 +00003210 // Introduce the local -> global mapping for preprocessed entities in
3211 // this module.
3212 F.PreprocessedEntityRemap.insertOrReplace(
3213 std::make_pair(LocalBasePreprocessedEntityID,
3214 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3215 }
3216
3217 break;
3218 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003219
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003220 case PPD_SKIPPED_RANGES: {
3221 F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
3222 assert(Blob.size() % sizeof(PPSkippedRange) == 0);
3223 F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
3224
3225 if (!PP.getPreprocessingRecord())
3226 PP.createPreprocessingRecord();
3227 if (!PP.getPreprocessingRecord()->getExternalSource())
3228 PP.getPreprocessingRecord()->SetExternalSource(*this);
3229 F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
3230 ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
Jonas Devlieghere560ce2c2018-02-26 15:16:42 +00003231
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00003232 if (F.NumPreprocessedSkippedRanges > 0)
3233 GlobalSkippedRangeMap.insert(
3234 std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
3235 break;
3236 }
3237
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003238 case DECL_UPDATE_OFFSETS:
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 if (Record.size() % 2 != 0) {
3240 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003241 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003242 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003243 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3244 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3245 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3246
3247 // If we've already loaded the decl, perform the updates when we finish
3248 // loading this block.
3249 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003250 PendingUpdateRecords.push_back(
3251 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003252 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003254
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003255 case OBJC_CATEGORIES_MAP:
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 if (F.LocalNumObjCCategoriesInMap != 0) {
3257 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003258 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003260
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003262 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003263 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003264
Guy Benyei11169dd2012-12-18 14:30:41 +00003265 case OBJC_CATEGORIES:
3266 F.ObjCCategories.swap(Record);
3267 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003268
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 case CUDA_SPECIAL_DECL_REFS:
3270 // Later tables overwrite earlier ones.
3271 // FIXME: Modules will have trouble with this.
3272 CUDASpecialDeclRefs.clear();
3273 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3274 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3275 break;
3276
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003277 case HEADER_SEARCH_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003278 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003279 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 if (Record[0]) {
3281 F.HeaderFileInfoTable
3282 = HeaderFileInfoLookupTable::Create(
3283 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3284 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003285 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003286 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003287 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003288
Guy Benyei11169dd2012-12-18 14:30:41 +00003289 PP.getHeaderSearchInfo().SetExternalSource(this);
3290 if (!PP.getHeaderSearchInfo().getExternalLookup())
3291 PP.getHeaderSearchInfo().SetExternalLookup(this);
3292 }
3293 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003294
Guy Benyei11169dd2012-12-18 14:30:41 +00003295 case FP_PRAGMA_OPTIONS:
3296 // Later tables overwrite earlier ones.
3297 FPPragmaOptions.swap(Record);
3298 break;
3299
3300 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003301 for (unsigned I = 0, E = Record.size(); I != E; ) {
3302 auto Name = ReadString(Record, I);
3303 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003304 Opt.Supported = Record[I++] != 0;
3305 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003306 Opt.Avail = Record[I++];
3307 Opt.Core = Record[I++];
3308 }
3309 break;
3310
3311 case OPENCL_EXTENSION_TYPES:
3312 for (unsigned I = 0, E = Record.size(); I != E;) {
3313 auto TypeID = static_cast<::TypeID>(Record[I++]);
3314 auto *Type = GetType(TypeID).getTypePtr();
3315 auto NumExt = static_cast<unsigned>(Record[I++]);
3316 for (unsigned II = 0; II != NumExt; ++II) {
3317 auto Ext = ReadString(Record, I);
3318 OpenCLTypeExtMap[Type].insert(Ext);
3319 }
3320 }
3321 break;
3322
3323 case OPENCL_EXTENSION_DECLS:
3324 for (unsigned I = 0, E = Record.size(); I != E;) {
3325 auto DeclID = static_cast<::DeclID>(Record[I++]);
3326 auto *Decl = GetDecl(DeclID);
3327 auto NumExt = static_cast<unsigned>(Record[I++]);
3328 for (unsigned II = 0; II != NumExt; ++II) {
3329 auto Ext = ReadString(Record, I);
3330 OpenCLDeclExtMap[Decl].insert(Ext);
3331 }
3332 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003333 break;
3334
3335 case TENTATIVE_DEFINITIONS:
3336 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3337 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3338 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003339
Guy Benyei11169dd2012-12-18 14:30:41 +00003340 case KNOWN_NAMESPACES:
3341 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3342 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3343 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003344
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003345 case UNDEFINED_BUT_USED:
3346 if (UndefinedButUsed.size() % 2 != 0) {
3347 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003348 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003349 }
3350
3351 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003352 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003353 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003354 }
3355 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003356 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3357 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003358 ReadSourceLocation(F, Record, I).getRawEncoding());
3359 }
3360 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003361
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003362 case DELETE_EXPRS_TO_ANALYZE:
3363 for (unsigned I = 0, N = Record.size(); I != N;) {
3364 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3365 const uint64_t Count = Record[I++];
3366 DelayedDeleteExprs.push_back(Count);
3367 for (uint64_t C = 0; C < Count; ++C) {
3368 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3369 bool IsArrayForm = Record[I++] == 1;
3370 DelayedDeleteExprs.push_back(IsArrayForm);
3371 }
3372 }
3373 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003374
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003375 case IMPORTED_MODULES:
Manman Ren11f2a472016-08-18 17:42:15 +00003376 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003377 // If we aren't loading a module (which has its own exports), make
3378 // all of the imported modules visible.
3379 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003380 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3381 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3382 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003383 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003384 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003385 if (DeserializationListener)
3386 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3387 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003388 }
3389 }
3390 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003391
Guy Benyei11169dd2012-12-18 14:30:41 +00003392 case MACRO_OFFSET: {
3393 if (F.LocalNumMacros != 0) {
3394 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003395 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003396 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003397 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003398 F.LocalNumMacros = Record[0];
3399 unsigned LocalBaseMacroID = Record[1];
3400 F.BaseMacroID = getTotalNumMacros();
3401
3402 if (F.LocalNumMacros > 0) {
3403 // Introduce the global -> local mapping for macros within this module.
3404 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3405
3406 // Introduce the local -> global mapping for macros within this module.
3407 F.MacroRemap.insertOrReplace(
3408 std::make_pair(LocalBaseMacroID,
3409 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003410
3411 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003412 }
3413 break;
3414 }
3415
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003416 case LATE_PARSED_TEMPLATE:
Richard Smithe40f2ba2013-08-07 21:41:30 +00003417 LateParsedTemplates.append(Record.begin(), Record.end());
3418 break;
Dario Domizioli13a0a382014-05-23 12:13:25 +00003419
3420 case OPTIMIZE_PRAGMA_OPTIONS:
3421 if (Record.size() != 1) {
3422 Error("invalid pragma optimize record");
3423 return Failure;
3424 }
3425 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3426 break;
Nico Weber72889432014-09-06 01:25:55 +00003427
Nico Weber779355f2016-03-02 23:22:00 +00003428 case MSSTRUCT_PRAGMA_OPTIONS:
3429 if (Record.size() != 1) {
3430 Error("invalid pragma ms_struct record");
3431 return Failure;
3432 }
3433 PragmaMSStructState = Record[0];
3434 break;
3435
Nico Weber42932312016-03-03 00:17:35 +00003436 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3437 if (Record.size() != 2) {
3438 Error("invalid pragma ms_struct record");
3439 return Failure;
3440 }
3441 PragmaMSPointersToMembersState = Record[0];
3442 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3443 break;
3444
Nico Weber72889432014-09-06 01:25:55 +00003445 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3446 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3447 UnusedLocalTypedefNameCandidates.push_back(
3448 getGlobalDeclID(F, Record[I]));
3449 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003450
3451 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3452 if (Record.size() != 1) {
3453 Error("invalid cuda pragma options record");
3454 return Failure;
3455 }
3456 ForceCUDAHostDeviceDepth = Record[0];
3457 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003458
3459 case PACK_PRAGMA_OPTIONS: {
3460 if (Record.size() < 3) {
3461 Error("invalid pragma pack record");
3462 return Failure;
3463 }
3464 PragmaPackCurrentValue = Record[0];
3465 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3466 unsigned NumStackEntries = Record[2];
3467 unsigned Idx = 3;
3468 // Reset the stack when importing a new module.
3469 PragmaPackStack.clear();
3470 for (unsigned I = 0; I < NumStackEntries; ++I) {
3471 PragmaPackStackEntry Entry;
3472 Entry.Value = Record[Idx++];
3473 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003474 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003475 PragmaPackStrings.push_back(ReadString(Record, Idx));
3476 Entry.SlotLabel = PragmaPackStrings.back();
3477 PragmaPackStack.push_back(Entry);
3478 }
3479 break;
3480 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003481 }
3482 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003483}
3484
Richard Smith37a93df2017-02-18 00:32:02 +00003485void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3486 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3487
3488 // Additional remapping information.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003489 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
Richard Smith37a93df2017-02-18 00:32:02 +00003490 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3491 F.ModuleOffsetMap = StringRef();
3492
3493 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3494 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3495 F.SLocRemap.insert(std::make_pair(0U, 0));
3496 F.SLocRemap.insert(std::make_pair(2U, 1));
3497 }
3498
3499 // Continuous range maps we may be updating in our module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00003500 using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
Richard Smith37a93df2017-02-18 00:32:02 +00003501 RemapBuilder SLocRemap(F.SLocRemap);
3502 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3503 RemapBuilder MacroRemap(F.MacroRemap);
3504 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3505 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3506 RemapBuilder SelectorRemap(F.SelectorRemap);
3507 RemapBuilder DeclRemap(F.DeclRemap);
3508 RemapBuilder TypeRemap(F.TypeRemap);
3509
3510 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003511 // FIXME: Looking up dependency modules by filename is horrible. Let's
3512 // start fixing this with prebuilt and explicit modules and see how it
3513 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003514 using namespace llvm::support;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003515 ModuleKind Kind = static_cast<ModuleKind>(
3516 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003517 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3518 StringRef Name = StringRef((const char*)Data, Len);
3519 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003520 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3521 ? ModuleMgr.lookupByModuleName(Name)
3522 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003523 if (!OM) {
3524 std::string Msg =
3525 "SourceLocation remap refers to unknown module, cannot find ";
3526 Msg.append(Name);
3527 Error(Msg);
3528 return;
3529 }
3530
3531 uint32_t SLocOffset =
3532 endian::readNext<uint32_t, little, unaligned>(Data);
3533 uint32_t IdentifierIDOffset =
3534 endian::readNext<uint32_t, little, unaligned>(Data);
3535 uint32_t MacroIDOffset =
3536 endian::readNext<uint32_t, little, unaligned>(Data);
3537 uint32_t PreprocessedEntityIDOffset =
3538 endian::readNext<uint32_t, little, unaligned>(Data);
3539 uint32_t SubmoduleIDOffset =
3540 endian::readNext<uint32_t, little, unaligned>(Data);
3541 uint32_t SelectorIDOffset =
3542 endian::readNext<uint32_t, little, unaligned>(Data);
3543 uint32_t DeclIDOffset =
3544 endian::readNext<uint32_t, little, unaligned>(Data);
3545 uint32_t TypeIndexOffset =
3546 endian::readNext<uint32_t, little, unaligned>(Data);
3547
3548 uint32_t None = std::numeric_limits<uint32_t>::max();
3549
3550 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3551 RemapBuilder &Remap) {
3552 if (Offset != None)
3553 Remap.insert(std::make_pair(Offset,
3554 static_cast<int>(BaseOffset - Offset)));
3555 };
3556 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3557 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3558 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3559 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3560 PreprocessedEntityRemap);
3561 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3562 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3563 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3564 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3565
3566 // Global -> local mappings.
3567 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3568 }
3569}
3570
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003571ASTReader::ASTReadResult
3572ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3573 const ModuleFile *ImportedBy,
3574 unsigned ClientLoadCapabilities) {
3575 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003576 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003577
3578 // Try to resolve ModuleName in the current header search context and
3579 // verify that it is found in the same module map file as we saved. If the
3580 // top-level AST file is a main file, skip this check because there is no
3581 // usable header search context.
3582 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003583 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003584 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003585 // An implicitly-loaded module file should have its module listed in some
3586 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003587 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003588 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3589 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3590 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003591 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003592 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003593 if (auto *ASTFE = M ? M->getASTFile() : nullptr) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003594 // This module was defined by an imported (explicit) module.
3595 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3596 << ASTFE->getName();
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003597 } else {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003598 // This module was built with a different module map.
3599 Diag(diag::err_imported_module_not_found)
3600 << F.ModuleName << F.FileName << ImportedBy->FileName
3601 << F.ModuleMapPath;
Bruno Cardoso Lopesa66a3252017-11-17 03:24:11 +00003602 // In case it was imported by a PCH, there's a chance the user is
3603 // just missing to include the search path to the directory containing
3604 // the modulemap.
3605 if (ImportedBy->Kind == MK_PCH)
3606 Diag(diag::note_imported_by_pch_module_not_found)
3607 << llvm::sys::path::parent_path(F.ModuleMapPath);
3608 }
Richard Smith0f99d6a2015-08-09 08:48:41 +00003609 }
3610 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003611 }
3612
Richard Smithe842a472014-10-22 02:05:46 +00003613 assert(M->Name == F.ModuleName && "found module with different name");
3614
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003615 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003616 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003617 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3618 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003619 assert(ImportedBy && "top-level import should be verified");
3620 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3621 Diag(diag::err_imported_module_modmap_changed)
3622 << F.ModuleName << ImportedBy->FileName
3623 << ModMap->getName() << F.ModuleMapPath;
3624 return OutOfDate;
3625 }
3626
3627 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3628 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3629 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003630 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003631 const FileEntry *F =
3632 FileMgr.getFile(Filename, false, false);
3633 if (F == nullptr) {
3634 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3635 Error("could not find file '" + Filename +"' referenced by AST file");
3636 return OutOfDate;
3637 }
3638 AdditionalStoredMaps.insert(F);
3639 }
3640
3641 // Check any additional module map files (e.g. module.private.modulemap)
3642 // that are not in the pcm.
3643 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003644 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003645 // Remove files that match
3646 // Note: SmallPtrSet::erase is really remove
3647 if (!AdditionalStoredMaps.erase(ModMap)) {
3648 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3649 Diag(diag::err_module_different_modmap)
3650 << F.ModuleName << /*new*/0 << ModMap->getName();
3651 return OutOfDate;
3652 }
3653 }
3654 }
3655
3656 // Check any additional module map files that are in the pcm, but not
3657 // found in header search. Cases that match are already removed.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003658 for (const FileEntry *ModMap : AdditionalStoredMaps) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003659 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3660 Diag(diag::err_module_different_modmap)
3661 << F.ModuleName << /*not new*/1 << ModMap->getName();
3662 return OutOfDate;
3663 }
3664 }
3665
3666 if (Listener)
3667 Listener->ReadModuleMapFile(F.ModuleMapPath);
3668 return Success;
3669}
3670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003671/// Move the given method to the back of the global list of methods.
Douglas Gregorc1489562013-02-12 23:36:21 +00003672static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3673 // Find the entry for this selector in the method pool.
3674 Sema::GlobalMethodPool::iterator Known
3675 = S.MethodPool.find(Method->getSelector());
3676 if (Known == S.MethodPool.end())
3677 return;
3678
3679 // Retrieve the appropriate method list.
3680 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3681 : Known->second.second;
3682 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003683 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003684 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003685 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003686 Found = true;
3687 } else {
3688 // Keep searching.
3689 continue;
3690 }
3691 }
3692
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003693 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003694 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003695 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003696 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003697 }
3698}
3699
Richard Smithde711422015-04-23 21:20:19 +00003700void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003701 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Vedant Kumar48b4f762018-04-14 01:40:48 +00003702 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003703 bool wasHidden = D->isHidden();
3704 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003705
Vedant Kumar48b4f762018-04-14 01:40:48 +00003706 if (wasHidden && SemaObj) {
3707 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
Richard Smith49f906a2014-03-01 00:08:04 +00003708 moveMethodToBackOfGlobalList(*SemaObj, Method);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003709 }
3710 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 }
3712}
3713
Richard Smith49f906a2014-03-01 00:08:04 +00003714void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003715 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003716 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003717 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003718 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003719 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003720 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003721 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003722
3723 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003724 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003725 // there is nothing more to do.
3726 continue;
3727 }
Richard Smith49f906a2014-03-01 00:08:04 +00003728
Guy Benyei11169dd2012-12-18 14:30:41 +00003729 if (!Mod->isAvailable()) {
3730 // Modules that aren't available cannot be made visible.
3731 continue;
3732 }
3733
3734 // Update the module's name visibility.
3735 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003736
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 // If we've already deserialized any names from this module,
3738 // mark them as visible.
3739 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3740 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003741 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003742 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003743 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003744 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3745 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003746 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003747
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003749 SmallVector<Module *, 16> Exports;
3750 Mod->getExportedModules(Exports);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003751 for (SmallVectorImpl<Module *>::iterator
3752 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3753 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003754 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003755 Stack.push_back(Exported);
Vedant Kumar48b4f762018-04-14 01:40:48 +00003756 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003757 }
3758}
3759
Richard Smith6561f922016-09-12 21:06:40 +00003760/// We've merged the definition \p MergedDef into the existing definition
3761/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3762/// visible.
3763void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3764 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003765 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3766 // in modules other than its owning module. We should instead give the
3767 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003768 if (Def->isHidden()) {
3769 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003770 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003771 Def->setVisibleDespiteOwningModule();
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003772 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3773 getContext().mergeDefinitionIntoModule(
3774 Def, MergedDef->getImportedOwningModule(),
3775 /*NotifyListeners*/ false);
3776 PendingMergedDefinitionsToDeduplicate.insert(Def);
3777 } else {
3778 auto SubmoduleID = MergedDef->getOwningModuleID();
3779 assert(SubmoduleID && "hidden definition in no module");
3780 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3781 }
Richard Smith6561f922016-09-12 21:06:40 +00003782 }
3783}
3784
Douglas Gregore060e572013-01-25 01:03:03 +00003785bool ASTReader::loadGlobalIndex() {
3786 if (GlobalIndex)
3787 return false;
3788
3789 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003790 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003791 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003792
Douglas Gregore060e572013-01-25 01:03:03 +00003793 // Try to load the global index.
3794 TriedLoadingGlobalIndex = true;
3795 StringRef ModuleCachePath
3796 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3797 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003798 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003799 if (!Result.first)
3800 return true;
3801
3802 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003803 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003804 return false;
3805}
3806
3807bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003808 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003809 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3810}
3811
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003812static void updateModuleTimestamp(ModuleFile &MF) {
3813 // Overwrite the timestamp file contents so that file's mtime changes.
3814 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003815 std::error_code EC;
3816 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3817 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003818 return;
3819 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003820 OS.close();
3821 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003822}
3823
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003824/// Given a cursor at the start of an AST file, scan ahead and drop the
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003825/// cursor into the start of the given block ID, returning false on success and
3826/// true on failure.
3827static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003828 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003829 llvm::BitstreamEntry Entry = Cursor.advance();
3830 switch (Entry.Kind) {
3831 case llvm::BitstreamEntry::Error:
3832 case llvm::BitstreamEntry::EndBlock:
3833 return true;
3834
3835 case llvm::BitstreamEntry::Record:
3836 // Ignore top-level records.
3837 Cursor.skipRecord(Entry.ID);
3838 break;
3839
3840 case llvm::BitstreamEntry::SubBlock:
3841 if (Entry.ID == BlockID) {
3842 if (Cursor.EnterSubBlock(BlockID))
3843 return true;
3844 // Found it!
3845 return false;
3846 }
3847
3848 if (Cursor.SkipBlock())
3849 return true;
3850 }
3851 }
3852}
3853
Benjamin Kramer0772c422016-02-13 13:42:54 +00003854ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 ModuleKind Type,
3856 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003857 unsigned ClientLoadCapabilities,
3858 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003859 llvm::SaveAndRestore<SourceLocation>
3860 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3861
Richard Smithd1c46742014-04-30 02:24:17 +00003862 // Defer any pending actions until we get to the end of reading the AST file.
3863 Deserializing AnASTFile(this);
3864
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003866 unsigned PreviousGeneration = 0;
3867 if (ContextObj)
3868 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003869
3870 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003871 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003872 switch (ASTReadResult ReadResult =
3873 ReadASTCore(FileName, Type, ImportLoc,
3874 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3875 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003877 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 case OutOfDate:
3879 case VersionMismatch:
3880 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003881 case HadErrors: {
3882 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
Vedant Kumar48b4f762018-04-14 01:40:48 +00003883 for (const ImportedModule &IM : Loaded)
Ben Langmuir9801b252014-06-20 00:24:56 +00003884 LoadedSet.insert(IM.Mod);
3885
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003886 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003887 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003888 ? &PP.getHeaderSearchInfo().getModuleMap()
3889 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003890
3891 // If we find that any modules are unusable, the global index is going
3892 // to be out-of-date. Just remove it.
3893 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003894 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003895 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003896 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 case Success:
3898 break;
3899 }
3900
3901 // Here comes stuff that we only do once the entire chain is loaded.
3902
3903 // Load the AST blocks of all of the modules that we loaded.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003904 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3905 MEnd = Loaded.end();
3906 M != MEnd; ++M) {
3907 ModuleFile &F = *M->Mod;
Guy Benyei11169dd2012-12-18 14:30:41 +00003908
3909 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003910 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3911 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003912
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003913 // Read the extension blocks.
3914 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3915 if (ASTReadResult Result = ReadExtensionBlock(F))
3916 return Result;
3917 }
3918
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003919 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003920 // bits of all files we've seen.
3921 F.GlobalBitOffset = TotalModulesSizeInBits;
3922 TotalModulesSizeInBits += F.SizeInBits;
3923 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003924
Guy Benyei11169dd2012-12-18 14:30:41 +00003925 // Preload SLocEntries.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003926 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3927 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 // Load it through the SourceManager and don't call ReadSLocEntry()
3929 // directly because the entry may have already been loaded in which case
3930 // calling ReadSLocEntry() directly would trigger an assertion in
3931 // SourceManager.
3932 SourceMgr.getLoadedSLocEntryByID(Index);
3933 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003934
Richard Smithea741482017-05-01 22:10:47 +00003935 // Map the original source file ID into the ID space of the current
3936 // compilation.
3937 if (F.OriginalSourceFileID.isValid()) {
3938 F.OriginalSourceFileID = FileID::get(
3939 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3940 }
3941
Richard Smith33e0f7e2015-07-22 02:08:40 +00003942 // Preload all the pending interesting identifiers by marking them out of
3943 // date.
3944 for (auto Offset : F.PreloadIdentifierOffsets) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00003945 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
Richard Smith33e0f7e2015-07-22 02:08:40 +00003946 F.IdentifierTableData + Offset);
3947
3948 ASTIdentifierLookupTrait Trait(*this, F);
3949 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3950 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003951 auto &II = PP.getIdentifierTable().getOwn(Key);
3952 II.setOutOfDate(true);
3953
3954 // Mark this identifier as being from an AST file so that we can track
3955 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003956 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003957
3958 // Associate the ID with the identifier so that the writer can reuse it.
3959 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3960 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003961 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 }
3963
Douglas Gregor603cd862013-03-22 18:50:14 +00003964 // Setup the import locations and notify the module manager that we've
3965 // committed to these module files.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003966 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3967 MEnd = Loaded.end();
3968 M != MEnd; ++M) {
3969 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003970
3971 ModuleMgr.moduleFileAccepted(&F);
3972
3973 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003974 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003975 // FIXME: We assume that locations from PCH / preamble do not need
3976 // any translation.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003977 if (!M->ImportedBy)
3978 F.ImportLoc = M->ImportLoc;
Guy Benyei11169dd2012-12-18 14:30:41 +00003979 else
Vedant Kumar48b4f762018-04-14 01:40:48 +00003980 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003981 }
3982
Richard Smithdbafb6c2017-06-29 23:23:46 +00003983 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003984 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3985 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003986 // Mark all of the identifiers in the identifier table as being out of date,
3987 // so that various accessors know to check the loaded modules when the
3988 // identifier is used.
3989 //
3990 // For C++ modules, we don't need information on many identifiers (just
3991 // those that provide macros or are poisoned), so we mark all of
3992 // the interesting ones via PreloadIdentifierOffsets.
Vedant Kumar48b4f762018-04-14 01:40:48 +00003993 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3994 IdEnd = PP.getIdentifierTable().end();
3995 Id != IdEnd; ++Id)
3996 Id->second->setOutOfDate(true);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003997 }
Manman Rena0f31a02016-04-29 19:04:05 +00003998 // Mark selectors as out of date.
3999 for (auto Sel : SelectorGeneration)
4000 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004001
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 // Resolve any unresolved module exports.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004003 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
4004 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
4006 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00004007
4008 switch (Unresolved.Kind) {
4009 case UnresolvedModuleRef::Conflict:
4010 if (ResolvedMod) {
4011 Module::Conflict Conflict;
4012 Conflict.Other = ResolvedMod;
4013 Conflict.Message = Unresolved.String.str();
4014 Unresolved.Mod->Conflicts.push_back(Conflict);
4015 }
4016 continue;
4017
4018 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00004020 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00004021 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00004022
Douglas Gregorfb912652013-03-20 21:10:35 +00004023 case UnresolvedModuleRef::Export:
4024 if (ResolvedMod || Unresolved.IsWildcard)
4025 Unresolved.Mod->Exports.push_back(
4026 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
4027 continue;
4028 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004029 }
Douglas Gregorfb912652013-03-20 21:10:35 +00004030 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004031
Graydon Hoaree7196af2016-12-09 21:45:49 +00004032 if (Imported)
4033 Imported->append(ImportedModules.begin(),
4034 ImportedModules.end());
4035
Daniel Jasperba7f2f72013-09-24 09:14:14 +00004036 // FIXME: How do we load the 'use'd modules? They may not be submodules.
4037 // Might be unnecessary as use declarations are only used to build the
4038 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004039
Richard Smithdbafb6c2017-06-29 23:23:46 +00004040 if (ContextObj)
4041 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00004042
Richard Smith3d8e97e2013-10-18 06:54:39 +00004043 if (SemaObj)
4044 UpdateSema();
4045
Guy Benyei11169dd2012-12-18 14:30:41 +00004046 if (DeserializationListener)
4047 DeserializationListener->ReaderInitialized(this);
4048
4049 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00004050 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004051 // If this AST file is a precompiled preamble, then set the
4052 // preamble file ID of the source manager to the file source file
4053 // from which the preamble was built.
4054 if (Type == MK_Preamble) {
4055 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
4056 } else if (Type == MK_MainFile) {
4057 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
4058 }
4059 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004060
Guy Benyei11169dd2012-12-18 14:30:41 +00004061 // For any Objective-C class definitions we have already loaded, make sure
4062 // that we load any additional categories.
Vedant Kumar48b4f762018-04-14 01:40:48 +00004063 if (ContextObj) {
4064 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
4065 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
4066 ObjCClassesLoaded[I],
Richard Smithdbafb6c2017-06-29 23:23:46 +00004067 PreviousGeneration);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004068 }
4069 }
Douglas Gregore060e572013-01-25 01:03:03 +00004070
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004071 if (PP.getHeaderSearchInfo()
4072 .getHeaderSearchOpts()
4073 .ModulesValidateOncePerBuildSession) {
4074 // Now we are certain that the module and all modules it depends on are
4075 // up to date. Create or update timestamp files for modules that are
4076 // located in the module cache (not for PCH files that could be anywhere
4077 // in the filesystem).
Vedant Kumar48b4f762018-04-14 01:40:48 +00004078 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4079 ImportedModule &M = Loaded[I];
4080 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004081 updateModuleTimestamp(*M.Mod);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004082 }
4083 }
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004084 }
4085
Guy Benyei11169dd2012-12-18 14:30:41 +00004086 return Success;
4087}
4088
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004089static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004090
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004091/// Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004092static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004093 return Stream.canSkipToPos(4) &&
4094 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004095 Stream.Read(8) == 'P' &&
4096 Stream.Read(8) == 'C' &&
4097 Stream.Read(8) == 'H';
4098}
4099
Richard Smith0f99d6a2015-08-09 08:48:41 +00004100static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4101 switch (Kind) {
4102 case MK_PCH:
4103 return 0; // PCH
4104 case MK_ImplicitModule:
4105 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004106 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004107 return 1; // module
4108 case MK_MainFile:
4109 case MK_Preamble:
4110 return 2; // main source file
4111 }
4112 llvm_unreachable("unknown module kind");
4113}
4114
Guy Benyei11169dd2012-12-18 14:30:41 +00004115ASTReader::ASTReadResult
4116ASTReader::ReadASTCore(StringRef FileName,
4117 ModuleKind Type,
4118 SourceLocation ImportLoc,
4119 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004120 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004121 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004122 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 unsigned ClientLoadCapabilities) {
4124 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004125 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004126 ModuleManager::AddModuleResult AddResult
4127 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004128 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004129 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004130 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004131
Douglas Gregor7029ce12013-03-19 00:28:20 +00004132 switch (AddResult) {
4133 case ModuleManager::AlreadyLoaded:
4134 return Success;
4135
4136 case ModuleManager::NewlyLoaded:
4137 // Load module file below.
4138 break;
4139
4140 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004141 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004142 // it.
4143 if (ClientLoadCapabilities & ARR_Missing)
4144 return Missing;
4145
4146 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004147 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004148 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004149 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004150 return Failure;
4151
4152 case ModuleManager::OutOfDate:
4153 // We couldn't load the module file because it is out-of-date. If the
4154 // client can handle out-of-date, return it.
4155 if (ClientLoadCapabilities & ARR_OutOfDate)
4156 return OutOfDate;
4157
4158 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004159 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004160 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004161 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004162 return Failure;
4163 }
4164
Douglas Gregor7029ce12013-03-19 00:28:20 +00004165 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004166
Guy Benyei11169dd2012-12-18 14:30:41 +00004167 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004168 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004169 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004170 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004171
Guy Benyei11169dd2012-12-18 14:30:41 +00004172 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004173 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004174 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4175 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004176 return Failure;
4177 }
4178
4179 // This is used for compatibility with older PCH formats.
4180 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004181 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004182 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004183
Chris Lattnerefa77172013-01-20 00:00:22 +00004184 switch (Entry.Kind) {
4185 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004186 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004187 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004188 Error("invalid record at top-level of AST file");
4189 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004190
Chris Lattnerefa77172013-01-20 00:00:22 +00004191 case llvm::BitstreamEntry::SubBlock:
4192 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004193 }
4194
Chris Lattnerefa77172013-01-20 00:00:22 +00004195 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 case CONTROL_BLOCK_ID:
4197 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004198 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004199 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004200 // Check that we didn't try to load a non-module AST file as a module.
4201 //
4202 // FIXME: Should we also perform the converse check? Loading a module as
4203 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004204 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4205 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004206 F.ModuleName.empty()) {
4207 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4208 if (Result != OutOfDate ||
4209 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4210 Diag(diag::err_module_file_not_module) << FileName;
4211 return Result;
4212 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004213 break;
4214
4215 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004216 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 case OutOfDate: return OutOfDate;
4218 case VersionMismatch: return VersionMismatch;
4219 case ConfigurationMismatch: return ConfigurationMismatch;
4220 case HadErrors: return HadErrors;
4221 }
4222 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004223
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 case AST_BLOCK_ID:
4225 if (!HaveReadControlBlock) {
4226 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004227 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004228 return VersionMismatch;
4229 }
4230
4231 // Record that we've loaded this module.
4232 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4233 return Success;
4234
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004235 case UNHASHED_CONTROL_BLOCK_ID:
4236 // This block is handled using look-ahead during ReadControlBlock. We
4237 // shouldn't get here!
4238 Error("malformed block record in AST file");
4239 return Failure;
4240
Guy Benyei11169dd2012-12-18 14:30:41 +00004241 default:
4242 if (Stream.SkipBlock()) {
4243 Error("malformed block record in AST file");
4244 return Failure;
4245 }
4246 break;
4247 }
4248 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004249
4250 return Success;
4251}
4252
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004253ASTReader::ASTReadResult
4254ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4255 unsigned ClientLoadCapabilities) {
4256 const HeaderSearchOptions &HSOpts =
4257 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4258 bool AllowCompatibleConfigurationMismatch =
4259 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4260
4261 ASTReadResult Result = readUnhashedControlBlockImpl(
4262 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4263 Listener.get(),
4264 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4265
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004266 // If F was directly imported by another module, it's implicitly validated by
4267 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004268 if (DisableValidation || WasImportedBy ||
4269 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4270 return Success;
4271
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004272 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004273 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004274 return Failure;
4275 }
4276
4277 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4278 // If this module has already been finalized in the PCMCache, we're stuck
4279 // with it; we can only load a single version of each module.
4280 //
4281 // This can happen when a module is imported in two contexts: in one, as a
4282 // user module; in another, as a system module (due to an import from
4283 // another module marked with the [system] flag). It usually indicates a
4284 // bug in the module map: this module should also be marked with [system].
4285 //
4286 // If -Wno-system-headers (the default), and the first import is as a
4287 // system module, then validation will fail during the as-user import,
4288 // since -Werror flags won't have been validated. However, it's reasonable
4289 // to treat this consistently as a system module.
4290 //
4291 // If -Wsystem-headers, the PCM on disk was built with
4292 // -Wno-system-headers, and the first import is as a user module, then
4293 // validation will fail during the as-system import since the PCM on disk
4294 // doesn't guarantee that -Werror was respected. However, the -Werror
4295 // flags were checked during the initial as-user import.
4296 if (PCMCache.isBufferFinal(F.FileName)) {
4297 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4298 return Success;
4299 }
4300 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004301
4302 return Result;
4303}
4304
4305ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4306 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4307 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4308 bool ValidateDiagnosticOptions) {
4309 // Initialize a stream.
4310 BitstreamCursor Stream(StreamData);
4311
4312 // Sniff for the signature.
4313 if (!startsWithASTFileMagic(Stream))
4314 return Failure;
4315
4316 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4317 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4318 return Failure;
4319
4320 // Read all of the records in the options block.
4321 RecordData Record;
4322 ASTReadResult Result = Success;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004323 while (true) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004324 llvm::BitstreamEntry Entry = Stream.advance();
4325
4326 switch (Entry.Kind) {
4327 case llvm::BitstreamEntry::Error:
4328 case llvm::BitstreamEntry::SubBlock:
4329 return Failure;
4330
4331 case llvm::BitstreamEntry::EndBlock:
4332 return Result;
4333
4334 case llvm::BitstreamEntry::Record:
4335 // The interesting case.
4336 break;
4337 }
4338
4339 // Read and process a record.
4340 Record.clear();
4341 switch (
4342 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004343 case SIGNATURE:
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004344 if (F)
4345 std::copy(Record.begin(), Record.end(), F->Signature.data());
4346 break;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004347 case DIAGNOSTIC_OPTIONS: {
4348 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4349 if (Listener && ValidateDiagnosticOptions &&
4350 !AllowCompatibleConfigurationMismatch &&
4351 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004352 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004353 break;
4354 }
4355 case DIAG_PRAGMA_MAPPINGS:
4356 if (!F)
4357 break;
4358 if (F->PragmaDiagMappings.empty())
4359 F->PragmaDiagMappings.swap(Record);
4360 else
4361 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4362 Record.begin(), Record.end());
4363 break;
4364 }
4365 }
4366}
4367
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004368/// Parse a record and blob containing module file extension metadata.
4369static bool parseModuleFileExtensionMetadata(
4370 const SmallVectorImpl<uint64_t> &Record,
4371 StringRef Blob,
4372 ModuleFileExtensionMetadata &Metadata) {
4373 if (Record.size() < 4) return true;
4374
4375 Metadata.MajorVersion = Record[0];
4376 Metadata.MinorVersion = Record[1];
4377
4378 unsigned BlockNameLen = Record[2];
4379 unsigned UserInfoLen = Record[3];
4380
4381 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4382
4383 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4384 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4385 Blob.data() + BlockNameLen + UserInfoLen);
4386 return false;
4387}
4388
4389ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4390 BitstreamCursor &Stream = F.Stream;
4391
4392 RecordData Record;
4393 while (true) {
4394 llvm::BitstreamEntry Entry = Stream.advance();
4395 switch (Entry.Kind) {
4396 case llvm::BitstreamEntry::SubBlock:
4397 if (Stream.SkipBlock())
4398 return Failure;
4399
4400 continue;
4401
4402 case llvm::BitstreamEntry::EndBlock:
4403 return Success;
4404
4405 case llvm::BitstreamEntry::Error:
4406 return HadErrors;
4407
4408 case llvm::BitstreamEntry::Record:
4409 break;
4410 }
4411
4412 Record.clear();
4413 StringRef Blob;
4414 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4415 switch (RecCode) {
4416 case EXTENSION_METADATA: {
4417 ModuleFileExtensionMetadata Metadata;
4418 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4419 return Failure;
4420
4421 // Find a module file extension with this block name.
4422 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4423 if (Known == ModuleFileExtensions.end()) break;
4424
4425 // Form a reader.
4426 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4427 F, Stream)) {
4428 F.ExtensionReaders.push_back(std::move(Reader));
4429 }
4430
4431 break;
4432 }
4433 }
4434 }
4435
4436 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004437}
4438
Richard Smitha7e2cc62015-05-01 01:53:09 +00004439void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004440 assert(ContextObj && "no context to initialize");
4441 ASTContext &Context = *ContextObj;
4442
Guy Benyei11169dd2012-12-18 14:30:41 +00004443 // If there's a listener, notify them that we "read" the translation unit.
4444 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004445 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004446 Context.getTranslationUnitDecl());
4447
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 // FIXME: Find a better way to deal with collisions between these
4449 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004450
Guy Benyei11169dd2012-12-18 14:30:41 +00004451 // Load the special types.
4452 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4453 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4454 if (!Context.CFConstantStringTypeDecl)
4455 Context.setCFConstantStringType(GetType(String));
4456 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004457
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4459 QualType FileType = GetType(File);
4460 if (FileType.isNull()) {
4461 Error("FILE type is NULL");
4462 return;
4463 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004464
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 if (!Context.FILEDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004466 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004467 Context.setFILEDecl(Typedef->getDecl());
4468 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004469 const TagType *Tag = FileType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004470 if (!Tag) {
4471 Error("Invalid FILE type in AST file");
4472 return;
4473 }
4474 Context.setFILEDecl(Tag->getDecl());
4475 }
4476 }
4477 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004478
Guy Benyei11169dd2012-12-18 14:30:41 +00004479 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4480 QualType Jmp_bufType = GetType(Jmp_buf);
4481 if (Jmp_bufType.isNull()) {
4482 Error("jmp_buf type is NULL");
4483 return;
4484 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004485
Guy Benyei11169dd2012-12-18 14:30:41 +00004486 if (!Context.jmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004487 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004488 Context.setjmp_bufDecl(Typedef->getDecl());
4489 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004490 const TagType *Tag = Jmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004491 if (!Tag) {
4492 Error("Invalid jmp_buf type in AST file");
4493 return;
4494 }
4495 Context.setjmp_bufDecl(Tag->getDecl());
4496 }
4497 }
4498 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004499
Guy Benyei11169dd2012-12-18 14:30:41 +00004500 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4501 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4502 if (Sigjmp_bufType.isNull()) {
4503 Error("sigjmp_buf type is NULL");
4504 return;
4505 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004506
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 if (!Context.sigjmp_bufDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004508 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004509 Context.setsigjmp_bufDecl(Typedef->getDecl());
4510 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004511 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004512 assert(Tag && "Invalid sigjmp_buf type in AST file");
4513 Context.setsigjmp_bufDecl(Tag->getDecl());
4514 }
4515 }
4516 }
4517
4518 if (unsigned ObjCIdRedef
4519 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4520 if (Context.ObjCIdRedefinitionType.isNull())
4521 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4522 }
4523
4524 if (unsigned ObjCClassRedef
4525 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4526 if (Context.ObjCClassRedefinitionType.isNull())
4527 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4528 }
4529
4530 if (unsigned ObjCSelRedef
4531 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4532 if (Context.ObjCSelRedefinitionType.isNull())
4533 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4534 }
4535
4536 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4537 QualType Ucontext_tType = GetType(Ucontext_t);
4538 if (Ucontext_tType.isNull()) {
4539 Error("ucontext_t type is NULL");
4540 return;
4541 }
4542
4543 if (!Context.ucontext_tDecl) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004544 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 Context.setucontext_tDecl(Typedef->getDecl());
4546 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00004547 const TagType *Tag = Ucontext_tType->getAs<TagType>();
Guy Benyei11169dd2012-12-18 14:30:41 +00004548 assert(Tag && "Invalid ucontext_t type in AST file");
4549 Context.setucontext_tDecl(Tag->getDecl());
4550 }
4551 }
4552 }
4553 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004554
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4556
4557 // If there were any CUDA special declarations, deserialize them.
4558 if (!CUDASpecialDeclRefs.empty()) {
4559 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4560 Context.setcudaConfigureCallDecl(
4561 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4562 }
Richard Smith56be7542014-03-21 00:33:59 +00004563
Guy Benyei11169dd2012-12-18 14:30:41 +00004564 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004565 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004566 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004567 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004568 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004569 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004570 if (Import.ImportLoc.isValid())
4571 PP.makeModuleVisible(Imported, Import.ImportLoc);
4572 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004573 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004574 }
4575 ImportedModules.clear();
4576}
4577
4578void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004579 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004580}
4581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004582/// Reads and return the signature record from \p PCH's control block, or
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004583/// else returns 0.
4584static ASTFileSignature readASTFileSignature(StringRef PCH) {
4585 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004586 if (!startsWithASTFileMagic(Stream))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004587 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004588
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004589 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4590 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
Vedant Kumar48b4f762018-04-14 01:40:48 +00004591 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004592
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004593 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004594 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004595 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004596 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004597 if (Entry.Kind != llvm::BitstreamEntry::Record)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004598 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004599
4600 Record.clear();
4601 StringRef Blob;
4602 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004603 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4604 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004605 }
4606}
4607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004608/// Retrieve the name of the original source file name
Guy Benyei11169dd2012-12-18 14:30:41 +00004609/// directly from the AST file, without actually loading the AST
4610/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004611std::string ASTReader::getOriginalSourceFile(
4612 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004613 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004614 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004615 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004616 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004617 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4618 << ASTFileName << Buffer.getError().message();
Vedant Kumar48b4f762018-04-14 01:40:48 +00004619 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 }
4621
4622 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004623 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004624
4625 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004626 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004628 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004629 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004630
Chris Lattnere7b154b2013-01-19 21:39:22 +00004631 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004632 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004633 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004634 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004635 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004636
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004637 // Scan for ORIGINAL_FILE inside the control block.
4638 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004639 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004640 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004641 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
Vedant Kumar48b4f762018-04-14 01:40:48 +00004642 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004643
Chris Lattnere7b154b2013-01-19 21:39:22 +00004644 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4645 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
Vedant Kumar48b4f762018-04-14 01:40:48 +00004646 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004648
Guy Benyei11169dd2012-12-18 14:30:41 +00004649 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004650 StringRef Blob;
4651 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4652 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004653 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004654}
4655
4656namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004657
Guy Benyei11169dd2012-12-18 14:30:41 +00004658 class SimplePCHValidator : public ASTReaderListener {
4659 const LangOptions &ExistingLangOpts;
4660 const TargetOptions &ExistingTargetOpts;
4661 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004662 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004663 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004664
Guy Benyei11169dd2012-12-18 14:30:41 +00004665 public:
4666 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4667 const TargetOptions &ExistingTargetOpts,
4668 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004669 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004670 FileManager &FileMgr)
4671 : ExistingLangOpts(ExistingLangOpts),
4672 ExistingTargetOpts(ExistingTargetOpts),
4673 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004674 ExistingModuleCachePath(ExistingModuleCachePath),
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004675 FileMgr(FileMgr) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00004676
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004677 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4678 bool AllowCompatibleDifferences) override {
4679 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4680 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004681 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004682
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004683 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4684 bool AllowCompatibleDifferences) override {
4685 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4686 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004687 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004688
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004689 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4690 StringRef SpecificModuleCachePath,
4691 bool Complain) override {
4692 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4693 ExistingModuleCachePath,
4694 nullptr, ExistingLangOpts);
4695 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004696
Craig Topper3e89dfe2014-03-13 02:13:41 +00004697 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4698 bool Complain,
4699 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004700 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004701 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004702 }
4703 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004704
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004705} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004706
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004707bool ASTReader::readASTFileControlBlock(
4708 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004709 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004710 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004711 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004713 // FIXME: This allows use of the VFS; we do not allow use of the
4714 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004715 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 if (!Buffer) {
4717 return true;
4718 }
4719
4720 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004721 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4722 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004723
4724 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004725 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004727
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004728 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004729 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004730 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004731
4732 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004733 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004734 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004735 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004736
Guy Benyei11169dd2012-12-18 14:30:41 +00004737 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004738 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004739 bool DoneWithControlBlock = false;
4740 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004741 llvm::BitstreamEntry Entry = Stream.advance();
4742
4743 switch (Entry.Kind) {
4744 case llvm::BitstreamEntry::SubBlock: {
4745 switch (Entry.ID) {
4746 case OPTIONS_BLOCK_ID: {
4747 std::string IgnoredSuggestedPredefines;
4748 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4749 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004750 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004751 return true;
4752 break;
4753 }
4754
4755 case INPUT_FILES_BLOCK_ID:
4756 InputFilesCursor = Stream;
4757 if (Stream.SkipBlock() ||
4758 (NeedsInputFiles &&
4759 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4760 return true;
4761 break;
4762
4763 default:
4764 if (Stream.SkipBlock())
4765 return true;
4766 break;
4767 }
4768
4769 continue;
4770 }
4771
4772 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004773 DoneWithControlBlock = true;
4774 break;
Richard Smith0516b182015-09-08 19:40:14 +00004775
4776 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004777 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004778
4779 case llvm::BitstreamEntry::Record:
4780 break;
4781 }
4782
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004783 if (DoneWithControlBlock) break;
4784
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004786 StringRef Blob;
4787 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004788 switch ((ControlRecordTypes)RecCode) {
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00004789 case METADATA:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004790 if (Record[0] != VERSION_MAJOR)
4791 return true;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004792 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004793 return true;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004794 break;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004795 case MODULE_NAME:
4796 Listener.ReadModuleName(Blob);
4797 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004798 case MODULE_DIRECTORY:
4799 ModuleDir = Blob;
4800 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004801 case MODULE_MAP_FILE: {
4802 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004803 auto Path = ReadString(Record, Idx);
4804 ResolveImportedPath(Path, ModuleDir);
4805 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004806 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004807 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004808 case INPUT_FILE_OFFSETS: {
4809 if (!NeedsInputFiles)
4810 break;
4811
4812 unsigned NumInputFiles = Record[0];
4813 unsigned NumUserFiles = Record[1];
Raphael Isemanneb13d3d2018-05-23 09:02:40 +00004814 const llvm::support::unaligned_uint64_t *InputFileOffs =
4815 (const llvm::support::unaligned_uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004816 for (unsigned I = 0; I != NumInputFiles; ++I) {
4817 // Go find this input file.
4818 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004819
4820 if (isSystemFile && !NeedsSystemInputFiles)
4821 break; // the rest are system input files
4822
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004823 BitstreamCursor &Cursor = InputFilesCursor;
4824 SavedStreamPosition SavedPosition(Cursor);
4825 Cursor.JumpToBit(InputFileOffs[I]);
4826
4827 unsigned Code = Cursor.ReadCode();
4828 RecordData Record;
4829 StringRef Blob;
4830 bool shouldContinue = false;
4831 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4832 case INPUT_FILE:
Vedant Kumar48b4f762018-04-14 01:40:48 +00004833 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004834 std::string Filename = Blob;
4835 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004836 shouldContinue = Listener.visitInputFile(
4837 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004838 break;
4839 }
4840 if (!shouldContinue)
4841 break;
4842 }
4843 break;
4844 }
4845
Richard Smithd4b230b2014-10-27 23:01:16 +00004846 case IMPORTS: {
4847 if (!NeedsImports)
4848 break;
4849
4850 unsigned Idx = 0, N = Record.size();
4851 while (Idx < N) {
4852 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004853 Idx += 5; // ImportLoc, Size, ModTime, Signature
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004854 SkipString(Record, Idx); // Module name; FIXME: pass to listener?
Richard Smith7ed1bc92014-12-05 22:42:13 +00004855 std::string Filename = ReadString(Record, Idx);
4856 ResolveImportedPath(Filename, ModuleDir);
4857 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004858 }
4859 break;
4860 }
4861
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004862 default:
4863 // No other validation to perform.
4864 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 }
4866 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004867
4868 // Look for module file extension blocks, if requested.
4869 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004870 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004871 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4872 bool DoneWithExtensionBlock = false;
4873 while (!DoneWithExtensionBlock) {
4874 llvm::BitstreamEntry Entry = Stream.advance();
4875
4876 switch (Entry.Kind) {
4877 case llvm::BitstreamEntry::SubBlock:
4878 if (Stream.SkipBlock())
4879 return true;
4880
4881 continue;
4882
4883 case llvm::BitstreamEntry::EndBlock:
4884 DoneWithExtensionBlock = true;
4885 continue;
4886
4887 case llvm::BitstreamEntry::Error:
4888 return true;
4889
4890 case llvm::BitstreamEntry::Record:
4891 break;
4892 }
4893
4894 Record.clear();
4895 StringRef Blob;
4896 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4897 switch (RecCode) {
4898 case EXTENSION_METADATA: {
4899 ModuleFileExtensionMetadata Metadata;
4900 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4901 return true;
4902
4903 Listener.readModuleFileExtension(Metadata);
4904 break;
4905 }
4906 }
4907 }
4908 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004909 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004910 }
4911
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004912 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4913 if (readUnhashedControlBlockImpl(
4914 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4915 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4916 ValidateDiagnosticOptions) != Success)
4917 return true;
4918
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004919 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004920}
4921
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004922bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4923 const PCHContainerReader &PCHContainerRdr,
4924 const LangOptions &LangOpts,
4925 const TargetOptions &TargetOpts,
4926 const PreprocessorOptions &PPOpts,
4927 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004928 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4929 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004930 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004931 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004932 validator,
4933 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004934}
4935
Ben Langmuir2c9af442014-04-10 17:57:43 +00004936ASTReader::ASTReadResult
4937ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004938 // Enter the submodule block.
4939 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4940 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004941 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004942 }
4943
4944 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4945 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004946 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004947 RecordData Record;
4948 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004949 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004950
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004951 switch (Entry.Kind) {
4952 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4953 case llvm::BitstreamEntry::Error:
4954 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004955 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004956 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004957 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004958 case llvm::BitstreamEntry::Record:
4959 // The interesting case.
4960 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004962
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004964 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004965 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004966 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4967
4968 if ((Kind == SUBMODULE_METADATA) != First) {
4969 Error("submodule metadata record should be at beginning of block");
4970 return Failure;
4971 }
4972 First = false;
4973
4974 // Submodule information is only valid if we have a current module.
4975 // FIXME: Should we error on these cases?
4976 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4977 Kind != SUBMODULE_DEFINITION)
4978 continue;
4979
4980 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 default: // Default behavior: ignore.
4982 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004983
Richard Smith03478d92014-10-23 22:12:14 +00004984 case SUBMODULE_DEFINITION: {
Jordan Rose90b0a1f2018-04-20 17:16:04 +00004985 if (Record.size() < 12) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004987 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 }
Richard Smith03478d92014-10-23 22:12:14 +00004989
Chris Lattner0e6c9402013-01-20 02:38:54 +00004990 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004991 unsigned Idx = 0;
4992 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4993 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00004994 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00004995 bool IsFramework = Record[Idx++];
4996 bool IsExplicit = Record[Idx++];
4997 bool IsSystem = Record[Idx++];
4998 bool IsExternC = Record[Idx++];
4999 bool InferSubmodules = Record[Idx++];
5000 bool InferExplicitSubmodules = Record[Idx++];
5001 bool InferExportWildcard = Record[Idx++];
5002 bool ConfigMacrosExhaustive = Record[Idx++];
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005003 bool ModuleMapIsPrivate = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00005004
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005005 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005006 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005008
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 // Retrieve this (sub)module from the module map, creating it if
5010 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00005011 CurrentModule =
5012 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
5013 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00005014
5015 // FIXME: set the definition loc for CurrentModule, or call
5016 // ModMap.setInferredModuleAllowedBy()
5017
Guy Benyei11169dd2012-12-18 14:30:41 +00005018 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
5019 if (GlobalIndex >= SubmodulesLoaded.size() ||
5020 SubmodulesLoaded[GlobalIndex]) {
5021 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00005022 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005024
Douglas Gregor7029ce12013-03-19 00:28:20 +00005025 if (!ParentModule) {
5026 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
5027 if (CurFile != F.File) {
5028 if (!Diags.isDiagnosticInFlight()) {
5029 Diag(diag::err_module_file_conflict)
5030 << CurrentModule->getTopLevelModuleName()
5031 << CurFile->getName()
5032 << F.File->getName();
5033 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00005034 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005035 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005036 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00005037
5038 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00005039 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00005040 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00005041
Richard Smithdd8b5332017-09-04 05:37:53 +00005042 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00005043 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00005044 CurrentModule->IsFromModuleFile = true;
5045 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00005046 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 CurrentModule->InferSubmodules = InferSubmodules;
5048 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
5049 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00005050 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Jordan Rose90b0a1f2018-04-20 17:16:04 +00005051 CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 if (DeserializationListener)
5053 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005054
Guy Benyei11169dd2012-12-18 14:30:41 +00005055 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005056
Richard Smith8a3e39a2016-03-28 21:31:09 +00005057 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005058 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00005059 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00005060 CurrentModule->UnresolvedConflicts.clear();
5061 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00005062
5063 // The module is available unless it's missing a requirement; relevant
5064 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
5065 // Missing headers that were present when the module was built do not
5066 // make it unavailable -- if we got this far, this must be an explicitly
5067 // imported module file.
5068 CurrentModule->Requirements.clear();
5069 CurrentModule->MissingHeaders.clear();
5070 CurrentModule->IsMissingRequirement =
5071 ParentModule && ParentModule->IsMissingRequirement;
5072 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 break;
5074 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005075
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005077 std::string Filename = Blob;
5078 ResolveImportedPath(F, Filename);
5079 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005080 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005081 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5082 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005083 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5084 Error("mismatched umbrella headers in submodule");
5085 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 }
5087 }
5088 break;
5089 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005090
Richard Smith202210b2014-10-24 20:23:01 +00005091 case SUBMODULE_HEADER:
5092 case SUBMODULE_EXCLUDED_HEADER:
5093 case SUBMODULE_PRIVATE_HEADER:
5094 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005095 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5096 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005097 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005098
Richard Smith202210b2014-10-24 20:23:01 +00005099 case SUBMODULE_TEXTUAL_HEADER:
5100 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5101 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5102 // them here.
5103 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005104
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005105 case SUBMODULE_TOPHEADER:
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005106 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005107 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005108
5109 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005110 std::string Dirname = Blob;
5111 ResolveImportedPath(F, Dirname);
5112 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005113 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005114 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5115 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005116 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5117 Error("mismatched umbrella directories in submodule");
5118 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005119 }
5120 }
5121 break;
5122 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005123
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005125 F.BaseSubmoduleID = getTotalNumSubmodules();
5126 F.LocalNumSubmodules = Record[0];
5127 unsigned LocalBaseSubmoduleID = Record[1];
5128 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005129 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005130 // module.
5131 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005132
5133 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 // module.
5135 F.SubmoduleRemap.insertOrReplace(
5136 std::make_pair(LocalBaseSubmoduleID,
5137 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005138
Ben Langmuir52ca6782014-10-20 16:27:32 +00005139 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5140 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005141 break;
5142 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005143
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005144 case SUBMODULE_IMPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005146 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005147 Unresolved.File = &F;
5148 Unresolved.Mod = CurrentModule;
5149 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005150 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005151 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005152 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005153 }
5154 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005155
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005156 case SUBMODULE_EXPORTS:
Guy Benyei11169dd2012-12-18 14:30:41 +00005157 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005158 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005159 Unresolved.File = &F;
5160 Unresolved.Mod = CurrentModule;
5161 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005162 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005163 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005164 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005165 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005166
5167 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 // the parsed, unresolved exports around.
5169 CurrentModule->UnresolvedExports.clear();
5170 break;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005171
5172 case SUBMODULE_REQUIRES:
Richard Smithdbafb6c2017-06-29 23:23:46 +00005173 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5174 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005175 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005176
5177 case SUBMODULE_LINK_LIBRARY:
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005178 ModMap.resolveLinkAsDependencies(CurrentModule);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005179 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005180 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005181 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005182
5183 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005184 CurrentModule->ConfigMacros.push_back(Blob.str());
5185 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005186
5187 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005188 UnresolvedModuleRef Unresolved;
5189 Unresolved.File = &F;
5190 Unresolved.Mod = CurrentModule;
5191 Unresolved.ID = Record[0];
5192 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5193 Unresolved.IsWildcard = false;
5194 Unresolved.String = Blob;
5195 UnresolvedModuleRefs.push_back(Unresolved);
5196 break;
5197 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005198
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005199 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005200 if (!ContextObj)
5201 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005202 SmallVector<uint32_t, 16> Inits;
5203 for (auto &ID : Record)
5204 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005205 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005206 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005207 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005208
5209 case SUBMODULE_EXPORT_AS:
5210 CurrentModule->ExportAsModule = Blob.str();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00005211 ModMap.addLinkAsDependency(CurrentModule);
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005212 break;
5213 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 }
5215}
5216
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005217/// Parse the record that corresponds to a LangOptions data
Guy Benyei11169dd2012-12-18 14:30:41 +00005218/// structure.
5219///
5220/// This routine parses the language options from the AST file and then gives
5221/// them to the AST listener if one is set.
5222///
5223/// \returns true if the listener deems the file unacceptable, false otherwise.
5224bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5225 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005226 ASTReaderListener &Listener,
5227 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 LangOptions LangOpts;
5229 unsigned Idx = 0;
5230#define LANGOPT(Name, Bits, Default, Description) \
5231 LangOpts.Name = Record[Idx++];
5232#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5233 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5234#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005235#define SANITIZER(NAME, ID) \
5236 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005237#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005238
Ben Langmuircd98cb72015-06-23 18:20:18 +00005239 for (unsigned N = Record[Idx++]; N; --N)
5240 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5241
Vedant Kumar48b4f762018-04-14 01:40:48 +00005242 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005243 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5244 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005245
Ben Langmuird4a667a2015-06-23 18:20:23 +00005246 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005247
5248 // Comment options.
5249 for (unsigned N = Record[Idx++]; N; --N) {
5250 LangOpts.CommentOpts.BlockCommandNames.push_back(
5251 ReadString(Record, Idx));
5252 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005253 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005254
Samuel Antaoee8fb302016-01-06 13:42:12 +00005255 // OpenMP offloading options.
5256 for (unsigned N = Record[Idx++]; N; --N) {
5257 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5258 }
5259
5260 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5261
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005262 return Listener.ReadLanguageOptions(LangOpts, Complain,
5263 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005264}
5265
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005266bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5267 ASTReaderListener &Listener,
5268 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005269 unsigned Idx = 0;
5270 TargetOptions TargetOpts;
5271 TargetOpts.Triple = ReadString(Record, Idx);
5272 TargetOpts.CPU = ReadString(Record, Idx);
5273 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 for (unsigned N = Record[Idx++]; N; --N) {
5275 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5276 }
5277 for (unsigned N = Record[Idx++]; N; --N) {
5278 TargetOpts.Features.push_back(ReadString(Record, Idx));
5279 }
5280
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005281 return Listener.ReadTargetOptions(TargetOpts, Complain,
5282 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005283}
5284
5285bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5286 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005287 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005288 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005289#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005290#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005291 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005292#include "clang/Basic/DiagnosticOptions.def"
5293
Richard Smith3be1cb22014-08-07 00:24:21 +00005294 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005295 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005296 for (unsigned N = Record[Idx++]; N; --N)
5297 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005298
5299 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5300}
5301
5302bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5303 ASTReaderListener &Listener) {
5304 FileSystemOptions FSOpts;
5305 unsigned Idx = 0;
5306 FSOpts.WorkingDir = ReadString(Record, Idx);
5307 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5308}
5309
5310bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5311 bool Complain,
5312 ASTReaderListener &Listener) {
5313 HeaderSearchOptions HSOpts;
5314 unsigned Idx = 0;
5315 HSOpts.Sysroot = ReadString(Record, Idx);
5316
5317 // Include entries.
5318 for (unsigned N = Record[Idx++]; N; --N) {
5319 std::string Path = ReadString(Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005320 frontend::IncludeDirGroup Group
5321 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005322 bool IsFramework = Record[Idx++];
5323 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005324 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5325 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005326 }
5327
5328 // System header prefixes.
5329 for (unsigned N = Record[Idx++]; N; --N) {
5330 std::string Prefix = ReadString(Record, Idx);
5331 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005332 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005333 }
5334
5335 HSOpts.ResourceDir = ReadString(Record, Idx);
5336 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005337 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005338 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005339 HSOpts.ImplicitModuleMaps = Record[Idx++];
5340 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 HSOpts.UseBuiltinIncludes = Record[Idx++];
5342 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5343 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5344 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005345 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005346
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005347 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5348 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005349}
5350
5351bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5352 bool Complain,
5353 ASTReaderListener &Listener,
5354 std::string &SuggestedPredefines) {
5355 PreprocessorOptions PPOpts;
5356 unsigned Idx = 0;
5357
5358 // Macro definitions/undefs
5359 for (unsigned N = Record[Idx++]; N; --N) {
5360 std::string Macro = ReadString(Record, Idx);
5361 bool IsUndef = Record[Idx++];
5362 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5363 }
5364
5365 // Includes
5366 for (unsigned N = Record[Idx++]; N; --N) {
5367 PPOpts.Includes.push_back(ReadString(Record, Idx));
5368 }
5369
5370 // Macro Includes
5371 for (unsigned N = Record[Idx++]; N; --N) {
5372 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5373 }
5374
5375 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005376 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005377 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5378 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5379 PPOpts.ObjCXXARCStandardLibrary =
5380 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5381 SuggestedPredefines.clear();
5382 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5383 SuggestedPredefines);
5384}
5385
5386std::pair<ModuleFile *, unsigned>
5387ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5388 GlobalPreprocessedEntityMapType::iterator
5389 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005390 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 "Corrupted global preprocessed entity map");
5392 ModuleFile *M = I->second;
5393 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5394 return std::make_pair(M, LocalIndex);
5395}
5396
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005397llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005398ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5399 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5400 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5401 Mod.NumPreprocessedEntities);
5402
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005403 return llvm::make_range(PreprocessingRecord::iterator(),
5404 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005405}
5406
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005407llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005408ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005409 return llvm::make_range(
5410 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5411 ModuleDeclIterator(this, &Mod,
5412 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005413}
5414
Cameron Desrochersb60f1b62018-01-15 19:14:16 +00005415SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
5416 auto I = GlobalSkippedRangeMap.find(GlobalIndex);
5417 assert(I != GlobalSkippedRangeMap.end() &&
5418 "Corrupted global skipped range map");
5419 ModuleFile *M = I->second;
5420 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
5421 assert(LocalIndex < M->NumPreprocessedSkippedRanges);
5422 PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
5423 SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
5424 TranslateSourceLocation(*M, RawRange.getEnd()));
5425 assert(Range.isValid());
5426 return Range;
5427}
5428
Guy Benyei11169dd2012-12-18 14:30:41 +00005429PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5430 PreprocessedEntityID PPID = Index+1;
5431 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5432 ModuleFile &M = *PPInfo.first;
5433 unsigned LocalIndex = PPInfo.second;
5434 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5435
Guy Benyei11169dd2012-12-18 14:30:41 +00005436 if (!PP.getPreprocessingRecord()) {
5437 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005438 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005439 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005440
5441 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005442 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5443
5444 llvm::BitstreamEntry Entry =
5445 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5446 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005447 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005448
Guy Benyei11169dd2012-12-18 14:30:41 +00005449 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005450 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5451 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005452 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005453 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005454 RecordData Record;
Vedant Kumar48b4f762018-04-14 01:40:48 +00005455 PreprocessorDetailRecordTypes RecType =
5456 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5457 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005458 switch (RecType) {
5459 case PPD_MACRO_EXPANSION: {
5460 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005461 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005462 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005463 if (isBuiltin)
5464 Name = getLocalIdentifier(M, Record[1]);
5465 else {
Richard Smith66a81862015-05-04 02:25:31 +00005466 PreprocessedEntityID GlobalID =
5467 getGlobalPreprocessedEntityID(M, Record[1]);
5468 Def = cast<MacroDefinitionRecord>(
5469 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005470 }
5471
5472 MacroExpansion *ME;
5473 if (isBuiltin)
5474 ME = new (PPRec) MacroExpansion(Name, Range);
5475 else
5476 ME = new (PPRec) MacroExpansion(Def, Range);
5477
5478 return ME;
5479 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005480
Guy Benyei11169dd2012-12-18 14:30:41 +00005481 case PPD_MACRO_DEFINITION: {
5482 // Decode the identifier info and then check again; if the macro is
5483 // still defined and associated with the identifier,
5484 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005485 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005486
5487 if (DeserializationListener)
5488 DeserializationListener->MacroDefinitionRead(PPID, MD);
5489
5490 return MD;
5491 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005492
Guy Benyei11169dd2012-12-18 14:30:41 +00005493 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005494 const char *FullFileNameStart = Blob.data() + Record[0];
5495 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005496 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005497 if (!FullFileName.empty())
5498 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005499
Guy Benyei11169dd2012-12-18 14:30:41 +00005500 // FIXME: Stable encoding
Vedant Kumar48b4f762018-04-14 01:40:48 +00005501 InclusionDirective::InclusionKind Kind
5502 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5503 InclusionDirective *ID
5504 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005505 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005506 Record[1], Record[3],
5507 File,
5508 Range);
5509 return ID;
5510 }
5511 }
5512
5513 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5514}
5515
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005516/// Find the next module that contains entities and return the ID
Guy Benyei11169dd2012-12-18 14:30:41 +00005517/// of the first entry.
NAKAMURA Takumi12ab07e2017-10-12 09:42:14 +00005518///
5519/// \param SLocMapI points at a chunk of a module that contains no
5520/// preprocessed entities or the entities it contains are not the ones we are
5521/// looking for.
Guy Benyei11169dd2012-12-18 14:30:41 +00005522PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5523 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5524 ++SLocMapI;
5525 for (GlobalSLocOffsetMapType::const_iterator
5526 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5527 ModuleFile &M = *SLocMapI->second;
5528 if (M.NumPreprocessedEntities)
5529 return M.BasePreprocessedEntityID;
5530 }
5531
5532 return getTotalNumPreprocessedEntities();
5533}
5534
5535namespace {
5536
Guy Benyei11169dd2012-12-18 14:30:41 +00005537struct PPEntityComp {
5538 const ASTReader &Reader;
5539 ModuleFile &M;
5540
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005541 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005542
5543 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5544 SourceLocation LHS = getLoc(L);
5545 SourceLocation RHS = getLoc(R);
5546 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5547 }
5548
5549 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5550 SourceLocation LHS = getLoc(L);
5551 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5552 }
5553
5554 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5555 SourceLocation RHS = getLoc(R);
5556 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5557 }
5558
5559 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005560 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005561 }
5562};
5563
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005564} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005565
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005566PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5567 bool EndsAfter) const {
5568 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005569 return getTotalNumPreprocessedEntities();
5570
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005571 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5572 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005573 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5574 "Corrupted global sloc offset map");
5575
5576 if (SLocMapI->second->NumPreprocessedEntities == 0)
5577 return findNextPreprocessedEntity(SLocMapI);
5578
5579 ModuleFile &M = *SLocMapI->second;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005580
5581 using pp_iterator = const PPEntityOffset *;
5582
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5584 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5585
5586 size_t Count = M.NumPreprocessedEntities;
5587 size_t Half;
5588 pp_iterator First = pp_begin;
5589 pp_iterator PPI;
5590
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005591 if (EndsAfter) {
5592 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005593 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005594 } else {
5595 // Do a binary search manually instead of using std::lower_bound because
5596 // The end locations of entities may be unordered (when a macro expansion
5597 // is inside another macro argument), but for this case it is not important
5598 // whether we get the first macro expansion or its containing macro.
5599 while (Count > 0) {
5600 Half = Count / 2;
5601 PPI = First;
5602 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005603 if (SourceMgr.isBeforeInTranslationUnit(
5604 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005605 First = PPI;
5606 ++First;
5607 Count = Count - Half - 1;
5608 } else
5609 Count = Half;
5610 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005611 }
5612
5613 if (PPI == pp_end)
5614 return findNextPreprocessedEntity(SLocMapI);
5615
5616 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5617}
5618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005619/// Returns a pair of [Begin, End) indices of preallocated
Guy Benyei11169dd2012-12-18 14:30:41 +00005620/// preprocessed entities that \arg Range encompasses.
5621std::pair<unsigned, unsigned>
5622 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5623 if (Range.isInvalid())
5624 return std::make_pair(0,0);
5625 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5626
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005627 PreprocessedEntityID BeginID =
5628 findPreprocessedEntity(Range.getBegin(), false);
5629 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005630 return std::make_pair(BeginID, EndID);
5631}
5632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005633/// Optionally returns true or false if the preallocated preprocessed
Guy Benyei11169dd2012-12-18 14:30:41 +00005634/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005635Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005636 FileID FID) {
5637 if (FID.isInvalid())
5638 return false;
5639
5640 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5641 ModuleFile &M = *PPInfo.first;
5642 unsigned LocalIndex = PPInfo.second;
5643 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005644
Richard Smithcb34bd32016-03-27 07:28:06 +00005645 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005646 if (Loc.isInvalid())
5647 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005648
Guy Benyei11169dd2012-12-18 14:30:41 +00005649 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5650 return true;
5651 else
5652 return false;
5653}
5654
5655namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005656
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005657 /// Visitor used to search for information about a header file.
Guy Benyei11169dd2012-12-18 14:30:41 +00005658 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005659 const FileEntry *FE;
David Blaikie05785d12013-02-20 22:23:23 +00005660 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005661
Guy Benyei11169dd2012-12-18 14:30:41 +00005662 public:
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005663 explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005664
5665 bool operator()(ModuleFile &M) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00005666 HeaderFileInfoLookupTable *Table
5667 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
Guy Benyei11169dd2012-12-18 14:30:41 +00005668 if (!Table)
5669 return false;
5670
5671 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005672 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005673 if (Pos == Table->end())
5674 return false;
5675
Richard Smithbdf2d932015-07-30 03:37:16 +00005676 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005677 return true;
5678 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005679
David Blaikie05785d12013-02-20 22:23:23 +00005680 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005681 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005682
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00005683} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005684
5685HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005686 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005687 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005688 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005689 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005690
Guy Benyei11169dd2012-12-18 14:30:41 +00005691 return HeaderFileInfo();
5692}
5693
5694void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005695 using DiagState = DiagnosticsEngine::DiagState;
5696 SmallVector<DiagState *, 32> DiagStates;
5697
Vedant Kumar48b4f762018-04-14 01:40:48 +00005698 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005699 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005700 auto &Record = F.PragmaDiagMappings;
5701 if (Record.empty())
5702 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005703
Richard Smithd230de22017-01-26 01:01:01 +00005704 DiagStates.clear();
5705
5706 auto ReadDiagState =
5707 [&](const DiagState &BasedOn, SourceLocation Loc,
5708 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5709 unsigned BackrefID = Record[Idx++];
5710 if (BackrefID != 0)
5711 return DiagStates[BackrefID - 1];
5712
Guy Benyei11169dd2012-12-18 14:30:41 +00005713 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005714 Diag.DiagStates.push_back(BasedOn);
5715 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005716 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005717 unsigned Size = Record[Idx++];
5718 assert(Idx + Size * 2 <= Record.size() &&
5719 "Invalid data, not enough diag/map pairs");
5720 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005721 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005722 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005723 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005724 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5725 continue;
5726
5727 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5728
5729 // If this mapping was specified as a warning but the severity was
5730 // upgraded due to diagnostic settings, simulate the current diagnostic
5731 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005732 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5733 NewMapping.setSeverity(diag::Severity::Warning);
5734 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005735 }
5736
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005737 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005738 }
Richard Smithd230de22017-01-26 01:01:01 +00005739 return NewState;
5740 };
5741
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005742 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005743 DiagState *FirstState;
5744 if (F.Kind == MK_ImplicitModule) {
5745 // Implicitly-built modules are reused with different diagnostic
5746 // settings. Use the initial diagnostic state from Diag to simulate this
5747 // compilation's diagnostic settings.
5748 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5749 DiagStates.push_back(FirstState);
5750
5751 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005752 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005753 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005754 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005755 assert(Idx < Record.size() &&
5756 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005757 } else if (F.isModule()) {
5758 // For an explicit module, preserve the flags from the module build
5759 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5760 // -Wblah flags.
5761 unsigned Flags = Record[Idx++];
5762 DiagState Initial;
5763 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5764 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5765 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5766 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5767 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5768 Initial.ExtBehavior = (diag::Severity)Flags;
5769 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005770
Richard Smith6c2b5a82018-02-09 01:15:13 +00005771 assert(F.OriginalSourceFileID.isValid());
5772
Richard Smithe37391c2017-05-03 00:28:49 +00005773 // Set up the root buffer of the module to start with the initial
5774 // diagnostic state of the module itself, to cover files that contain no
5775 // explicit transitions (for which we did not serialize anything).
5776 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5777 .StateTransitions.push_back({FirstState, 0});
5778 } else {
5779 // For prefix ASTs, start with whatever the user configured on the
5780 // command line.
5781 Idx++; // Skip flags.
5782 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5783 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005784 }
Richard Smithd230de22017-01-26 01:01:01 +00005785
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005786 // Read the state transitions.
5787 unsigned NumLocations = Record[Idx++];
5788 while (NumLocations--) {
5789 assert(Idx < Record.size() &&
5790 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005791 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5792 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
Richard Smith6c2b5a82018-02-09 01:15:13 +00005793 assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
Richard Smithd230de22017-01-26 01:01:01 +00005794 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5795 unsigned Transitions = Record[Idx++];
5796
5797 // Note that we don't need to set up Parent/ParentOffset here, because
5798 // we won't be changing the diagnostic state within imported FileIDs
5799 // (other than perhaps appending to the main source file, which has no
5800 // parent).
5801 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5802 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5803 for (unsigned I = 0; I != Transitions; ++I) {
5804 unsigned Offset = Record[Idx++];
5805 auto *State =
5806 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5807 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005808 }
5809 }
Richard Smithd230de22017-01-26 01:01:01 +00005810
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005811 // Read the final state.
5812 assert(Idx < Record.size() &&
5813 "Invalid data, missing final pragma diagnostic state");
5814 SourceLocation CurStateLoc =
5815 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5816 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5817
5818 if (!F.isModule()) {
5819 Diag.DiagStatesByLoc.CurDiagState = CurState;
5820 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5821
5822 // Preserve the property that the imaginary root file describes the
5823 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005824 FileID NullFile;
5825 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005826 if (T.empty())
5827 T.push_back({CurState, 0});
5828 else
5829 T[0].State = CurState;
5830 }
5831
Richard Smithd230de22017-01-26 01:01:01 +00005832 // Don't try to read these mappings again.
5833 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005834 }
5835}
5836
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005837/// Get the correct cursor and offset for loading a type.
Guy Benyei11169dd2012-12-18 14:30:41 +00005838ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5839 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5840 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5841 ModuleFile *M = I->second;
5842 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5843}
5844
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005845/// Read and return the type with the given index..
Guy Benyei11169dd2012-12-18 14:30:41 +00005846///
5847/// The index is the type ID, shifted and minus the number of predefs. This
5848/// routine actually reads the record corresponding to the type at the given
5849/// location. It is a helper routine for GetType, which deals with reading type
5850/// IDs.
5851QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005852 assert(ContextObj && "reading type with no AST context");
5853 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005854 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005855 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005856
5857 // Keep track of where we are in the stream, then jump back there
5858 // after reading this type.
5859 SavedStreamPosition SavedPosition(DeclsCursor);
5860
5861 ReadingKindTracker ReadingKind(Read_Type, *this);
5862
5863 // Note that we are loading a type record.
5864 Deserializing AType(this);
5865
5866 unsigned Idx = 0;
5867 DeclsCursor.JumpToBit(Loc.Offset);
5868 RecordData Record;
5869 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005870 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005871 case TYPE_EXT_QUAL: {
5872 if (Record.size() != 2) {
5873 Error("Incorrect encoding of extended qualifier type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005874 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005875 }
5876 QualType Base = readType(*Loc.F, Record, Idx);
5877 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5878 return Context.getQualifiedType(Base, Quals);
5879 }
5880
5881 case TYPE_COMPLEX: {
5882 if (Record.size() != 1) {
5883 Error("Incorrect encoding of complex type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005884 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005885 }
5886 QualType ElemType = readType(*Loc.F, Record, Idx);
5887 return Context.getComplexType(ElemType);
5888 }
5889
5890 case TYPE_POINTER: {
5891 if (Record.size() != 1) {
5892 Error("Incorrect encoding of pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005893 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005894 }
5895 QualType PointeeType = readType(*Loc.F, Record, Idx);
5896 return Context.getPointerType(PointeeType);
5897 }
5898
Reid Kleckner8a365022013-06-24 17:51:48 +00005899 case TYPE_DECAYED: {
5900 if (Record.size() != 1) {
5901 Error("Incorrect encoding of decayed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005902 return QualType();
Reid Kleckner8a365022013-06-24 17:51:48 +00005903 }
5904 QualType OriginalType = readType(*Loc.F, Record, Idx);
5905 QualType DT = Context.getAdjustedParameterType(OriginalType);
5906 if (!isa<DecayedType>(DT))
5907 Error("Decayed type does not decay");
5908 return DT;
5909 }
5910
Reid Kleckner0503a872013-12-05 01:23:43 +00005911 case TYPE_ADJUSTED: {
5912 if (Record.size() != 2) {
5913 Error("Incorrect encoding of adjusted type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005914 return QualType();
Reid Kleckner0503a872013-12-05 01:23:43 +00005915 }
5916 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5917 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5918 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5919 }
5920
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 case TYPE_BLOCK_POINTER: {
5922 if (Record.size() != 1) {
5923 Error("Incorrect encoding of block pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005924 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005925 }
5926 QualType PointeeType = readType(*Loc.F, Record, Idx);
5927 return Context.getBlockPointerType(PointeeType);
5928 }
5929
5930 case TYPE_LVALUE_REFERENCE: {
5931 if (Record.size() != 2) {
5932 Error("Incorrect encoding of lvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005933 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005934 }
5935 QualType PointeeType = readType(*Loc.F, Record, Idx);
5936 return Context.getLValueReferenceType(PointeeType, Record[1]);
5937 }
5938
5939 case TYPE_RVALUE_REFERENCE: {
5940 if (Record.size() != 1) {
5941 Error("Incorrect encoding of rvalue reference type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005942 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005943 }
5944 QualType PointeeType = readType(*Loc.F, Record, Idx);
5945 return Context.getRValueReferenceType(PointeeType);
5946 }
5947
5948 case TYPE_MEMBER_POINTER: {
5949 if (Record.size() != 2) {
5950 Error("Incorrect encoding of member pointer type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005951 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005952 }
5953 QualType PointeeType = readType(*Loc.F, Record, Idx);
5954 QualType ClassType = readType(*Loc.F, Record, Idx);
5955 if (PointeeType.isNull() || ClassType.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00005956 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005957
Guy Benyei11169dd2012-12-18 14:30:41 +00005958 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5959 }
5960
5961 case TYPE_CONSTANT_ARRAY: {
5962 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005963 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005964 unsigned IndexTypeQuals = Record[2];
5965 unsigned Idx = 3;
5966 llvm::APInt Size = ReadAPInt(Record, Idx);
5967 return Context.getConstantArrayType(ElementType, Size,
5968 ASM, IndexTypeQuals);
5969 }
5970
5971 case TYPE_INCOMPLETE_ARRAY: {
5972 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005973 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005974 unsigned IndexTypeQuals = Record[2];
5975 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5976 }
5977
5978 case TYPE_VARIABLE_ARRAY: {
5979 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00005980 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00005981 unsigned IndexTypeQuals = Record[2];
5982 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5983 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5984 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5985 ASM, IndexTypeQuals,
5986 SourceRange(LBLoc, RBLoc));
5987 }
5988
5989 case TYPE_VECTOR: {
5990 if (Record.size() != 3) {
5991 Error("incorrect encoding of vector type in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00005992 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00005993 }
5994
5995 QualType ElementType = readType(*Loc.F, Record, Idx);
5996 unsigned NumElements = Record[1];
5997 unsigned VecKind = Record[2];
5998 return Context.getVectorType(ElementType, NumElements,
5999 (VectorType::VectorKind)VecKind);
6000 }
6001
6002 case TYPE_EXT_VECTOR: {
6003 if (Record.size() != 3) {
6004 Error("incorrect encoding of extended 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 return Context.getExtVectorType(ElementType, NumElements);
6011 }
6012
6013 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006014 if (Record.size() != 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006015 Error("incorrect encoding of no-proto function type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006016 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006017 }
6018 QualType ResultType = readType(*Loc.F, Record, Idx);
6019 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006020 (CallingConv)Record[4], Record[5], Record[6],
6021 Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006022 return Context.getFunctionNoProtoType(ResultType, Info);
6023 }
6024
6025 case TYPE_FUNCTION_PROTO: {
6026 QualType ResultType = readType(*Loc.F, Record, Idx);
6027
6028 FunctionProtoType::ExtProtoInfo EPI;
6029 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
6030 /*hasregparm*/ Record[2],
6031 /*regparm*/ Record[3],
6032 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00006033 /*produces*/ Record[5],
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006034 /*nocallersavedregs*/ Record[6],
6035 /*nocfcheck*/ Record[7]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006036
Oren Ben Simhon220671a2018-03-17 13:31:35 +00006037 unsigned Idx = 8;
Guy Benyei11169dd2012-12-18 14:30:41 +00006038
6039 EPI.Variadic = Record[Idx++];
6040 EPI.HasTrailingReturn = Record[Idx++];
6041 EPI.TypeQuals = Record[Idx++];
6042 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00006043 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00006044 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00006045
6046 unsigned NumParams = Record[Idx++];
6047 SmallVector<QualType, 16> ParamTypes;
6048 for (unsigned I = 0; I != NumParams; ++I)
6049 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
6050
John McCall18afab72016-03-01 00:49:02 +00006051 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
6052 if (Idx != Record.size()) {
6053 for (unsigned I = 0; I != NumParams; ++I)
6054 ExtParameterInfos.push_back(
6055 FunctionProtoType::ExtParameterInfo
6056 ::getFromOpaqueValue(Record[Idx++]));
6057 EPI.ExtParameterInfos = ExtParameterInfos.data();
6058 }
6059
6060 assert(Idx == Record.size());
6061
Jordan Rose5c382722013-03-08 21:51:21 +00006062 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00006063 }
6064
6065 case TYPE_UNRESOLVED_USING: {
6066 unsigned Idx = 0;
6067 return Context.getTypeDeclType(
6068 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
6069 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006070
Guy Benyei11169dd2012-12-18 14:30:41 +00006071 case TYPE_TYPEDEF: {
6072 if (Record.size() != 2) {
6073 Error("incorrect encoding of typedef type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006074 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006075 }
6076 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006077 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006078 QualType Canonical = readType(*Loc.F, Record, Idx);
6079 if (!Canonical.isNull())
6080 Canonical = Context.getCanonicalType(Canonical);
6081 return Context.getTypedefType(Decl, Canonical);
6082 }
6083
6084 case TYPE_TYPEOF_EXPR:
6085 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
6086
6087 case TYPE_TYPEOF: {
6088 if (Record.size() != 1) {
6089 Error("incorrect encoding of typeof(type) in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006090 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006091 }
6092 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6093 return Context.getTypeOfType(UnderlyingType);
6094 }
6095
6096 case TYPE_DECLTYPE: {
6097 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6098 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6099 }
6100
6101 case TYPE_UNARY_TRANSFORM: {
6102 QualType BaseType = readType(*Loc.F, Record, Idx);
6103 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006104 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00006105 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6106 }
6107
Richard Smith74aeef52013-04-26 16:15:35 +00006108 case TYPE_AUTO: {
6109 QualType Deduced = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006110 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006111 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006112 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006114
Richard Smith600b5262017-01-26 20:40:47 +00006115 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6116 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6117 QualType Deduced = readType(*Loc.F, Record, Idx);
6118 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6119 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6120 IsDependent);
6121 }
6122
Guy Benyei11169dd2012-12-18 14:30:41 +00006123 case TYPE_RECORD: {
6124 if (Record.size() != 2) {
6125 Error("incorrect encoding of record type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006126 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 }
6128 unsigned Idx = 0;
6129 bool IsDependent = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006130 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006131 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6132 QualType T = Context.getRecordType(RD);
6133 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6134 return T;
6135 }
6136
6137 case TYPE_ENUM: {
6138 if (Record.size() != 2) {
6139 Error("incorrect encoding of enum type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006140 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006141 }
6142 unsigned Idx = 0;
6143 bool IsDependent = Record[Idx++];
6144 QualType T
6145 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6146 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6147 return T;
6148 }
6149
6150 case TYPE_ATTRIBUTED: {
6151 if (Record.size() != 3) {
6152 Error("incorrect encoding of attributed type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006153 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 }
6155 QualType modifiedType = readType(*Loc.F, Record, Idx);
6156 QualType equivalentType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006157 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006158 return Context.getAttributedType(kind, modifiedType, equivalentType);
6159 }
6160
6161 case TYPE_PAREN: {
6162 if (Record.size() != 1) {
6163 Error("incorrect encoding of paren type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006164 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006165 }
6166 QualType InnerType = readType(*Loc.F, Record, Idx);
6167 return Context.getParenType(InnerType);
6168 }
6169
6170 case TYPE_PACK_EXPANSION: {
6171 if (Record.size() != 2) {
6172 Error("incorrect encoding of pack expansion type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006173 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006174 }
6175 QualType Pattern = readType(*Loc.F, Record, Idx);
6176 if (Pattern.isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006177 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006178 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006179 if (Record[1])
6180 NumExpansions = Record[1] - 1;
6181 return Context.getPackExpansionType(Pattern, NumExpansions);
6182 }
6183
6184 case TYPE_ELABORATED: {
6185 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006186 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006187 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6188 QualType NamedType = readType(*Loc.F, Record, Idx);
Joel E. Denny7509a2f2018-05-14 19:36:45 +00006189 TagDecl *OwnedTagDecl = ReadDeclAs<TagDecl>(*Loc.F, Record, Idx);
6190 return Context.getElaboratedType(Keyword, NNS, NamedType, OwnedTagDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00006191 }
6192
6193 case TYPE_OBJC_INTERFACE: {
6194 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006195 ObjCInterfaceDecl *ItfD
6196 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006197 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6198 }
6199
Manman Rene6be26c2016-09-13 17:25:08 +00006200 case TYPE_OBJC_TYPE_PARAM: {
6201 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006202 ObjCTypeParamDecl *Decl
6203 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
Manman Rene6be26c2016-09-13 17:25:08 +00006204 unsigned NumProtos = Record[Idx++];
6205 SmallVector<ObjCProtocolDecl*, 4> Protos;
6206 for (unsigned I = 0; I != NumProtos; ++I)
6207 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6208 return Context.getObjCTypeParamType(Decl, Protos);
6209 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006210
Guy Benyei11169dd2012-12-18 14:30:41 +00006211 case TYPE_OBJC_OBJECT: {
6212 unsigned Idx = 0;
6213 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006214 unsigned NumTypeArgs = Record[Idx++];
6215 SmallVector<QualType, 4> TypeArgs;
6216 for (unsigned I = 0; I != NumTypeArgs; ++I)
6217 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 unsigned NumProtos = Record[Idx++];
6219 SmallVector<ObjCProtocolDecl*, 4> Protos;
6220 for (unsigned I = 0; I != NumProtos; ++I)
6221 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006222 bool IsKindOf = Record[Idx++];
6223 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006224 }
6225
6226 case TYPE_OBJC_OBJECT_POINTER: {
6227 unsigned Idx = 0;
6228 QualType Pointee = readType(*Loc.F, Record, Idx);
6229 return Context.getObjCObjectPointerType(Pointee);
6230 }
6231
6232 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6233 unsigned Idx = 0;
6234 QualType Parm = readType(*Loc.F, Record, Idx);
6235 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006236 return Context.getSubstTemplateTypeParmType(
6237 cast<TemplateTypeParmType>(Parm),
6238 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006239 }
6240
6241 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6242 unsigned Idx = 0;
6243 QualType Parm = readType(*Loc.F, Record, Idx);
6244 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6245 return Context.getSubstTemplateTypeParmPackType(
6246 cast<TemplateTypeParmType>(Parm),
6247 ArgPack);
6248 }
6249
6250 case TYPE_INJECTED_CLASS_NAME: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006251 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006252 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6253 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6254 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006255 const Type *T = nullptr;
6256 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6257 if (const Type *Existing = DI->getTypeForDecl()) {
6258 T = Existing;
6259 break;
6260 }
6261 }
6262 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006263 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006264 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6265 DI->setTypeForDecl(T);
6266 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006267 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006268 }
6269
6270 case TYPE_TEMPLATE_TYPE_PARM: {
6271 unsigned Idx = 0;
6272 unsigned Depth = Record[Idx++];
6273 unsigned Index = Record[Idx++];
6274 bool Pack = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00006275 TemplateTypeParmDecl *D
6276 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006277 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6278 }
6279
6280 case TYPE_DEPENDENT_NAME: {
6281 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006282 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006283 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006284 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006285 QualType Canon = readType(*Loc.F, Record, Idx);
6286 if (!Canon.isNull())
6287 Canon = Context.getCanonicalType(Canon);
6288 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6289 }
6290
6291 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6292 unsigned Idx = 0;
Vedant Kumar48b4f762018-04-14 01:40:48 +00006293 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006294 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006295 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006296 unsigned NumArgs = Record[Idx++];
6297 SmallVector<TemplateArgument, 8> Args;
6298 Args.reserve(NumArgs);
6299 while (NumArgs--)
6300 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6301 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006302 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006303 }
6304
6305 case TYPE_DEPENDENT_SIZED_ARRAY: {
6306 unsigned Idx = 0;
6307
6308 // ArrayType
6309 QualType ElementType = readType(*Loc.F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00006310 ArrayType::ArraySizeModifier ASM
6311 = (ArrayType::ArraySizeModifier)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00006312 unsigned IndexTypeQuals = Record[Idx++];
6313
6314 // DependentSizedArrayType
6315 Expr *NumElts = ReadExpr(*Loc.F);
6316 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6317
6318 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6319 IndexTypeQuals, Brackets);
6320 }
6321
6322 case TYPE_TEMPLATE_SPECIALIZATION: {
6323 unsigned Idx = 0;
6324 bool IsDependent = Record[Idx++];
6325 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6326 SmallVector<TemplateArgument, 8> Args;
6327 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6328 QualType Underlying = readType(*Loc.F, Record, Idx);
6329 QualType T;
6330 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006331 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006332 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006333 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006334 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6335 return T;
6336 }
6337
6338 case TYPE_ATOMIC: {
6339 if (Record.size() != 1) {
6340 Error("Incorrect encoding of atomic type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006341 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006342 }
6343 QualType ValueType = readType(*Loc.F, Record, Idx);
6344 return Context.getAtomicType(ValueType);
6345 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006346
Joey Goulye3c85de2016-12-01 11:30:49 +00006347 case TYPE_PIPE: {
6348 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006349 Error("Incorrect encoding of pipe type");
Vedant Kumar48b4f762018-04-14 01:40:48 +00006350 return QualType();
Xiuli Pan9c14e282016-01-09 12:53:17 +00006351 }
6352
6353 // Reading the pipe element type.
6354 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006355 unsigned ReadOnly = Record[1];
6356 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006357 }
6358
Alex Lorenz00aee432017-03-22 10:04:48 +00006359 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6360 unsigned Idx = 0;
6361
6362 // DependentSizedExtVectorType
6363 QualType ElementType = readType(*Loc.F, Record, Idx);
6364 Expr *SizeExpr = ReadExpr(*Loc.F);
6365 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6366
6367 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6368 AttrLoc);
6369 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006370
6371 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6372 unsigned Idx = 0;
6373
6374 // DependentAddressSpaceType
6375 QualType PointeeType = readType(*Loc.F, Record, Idx);
6376 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6377 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6378
6379 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6380 AttrLoc);
6381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006382 }
6383 llvm_unreachable("Invalid TypeCode!");
6384}
6385
Richard Smith564417a2014-03-20 21:47:22 +00006386void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6387 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006388 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006389 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00006390 ExceptionSpecificationType EST =
6391 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006392 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006393 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006394 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006395 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006396 ESI.Exceptions = Exceptions;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006397 } else if (isComputedNoexcept(EST)) {
Richard Smith8acb4282014-07-31 21:57:55 +00006398 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006399 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006400 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6401 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006402 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006403 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006404 }
6405}
6406
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006407namespace clang {
6408
6409class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006410 ModuleFile *F;
6411 ASTReader *Reader;
6412 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006413 unsigned &Idx;
6414
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006415 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006416 return Reader->ReadSourceLocation(*F, Record, Idx);
6417 }
6418
6419 TypeSourceInfo *GetTypeSourceInfo() {
6420 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6421 }
6422
6423 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6424 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006425 }
6426
Guy Benyei11169dd2012-12-18 14:30:41 +00006427public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006428 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006429 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006430 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006431
6432 // We want compile-time assurance that we've enumerated all of
6433 // these, so unfortunately we have to declare them first, then
6434 // define them out-of-line.
6435#define ABSTRACT_TYPELOC(CLASS, PARENT)
6436#define TYPELOC(CLASS, PARENT) \
6437 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6438#include "clang/AST/TypeLocNodes.def"
6439
6440 void VisitFunctionTypeLoc(FunctionTypeLoc);
6441 void VisitArrayTypeLoc(ArrayTypeLoc);
6442};
6443
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006444} // namespace clang
6445
Guy Benyei11169dd2012-12-18 14:30:41 +00006446void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6447 // nothing to do
6448}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006449
Guy Benyei11169dd2012-12-18 14:30:41 +00006450void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006451 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006452 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006453 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6454 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6455 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6456 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 }
6458}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006459
Guy Benyei11169dd2012-12-18 14:30:41 +00006460void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006461 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006462}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006463
Guy Benyei11169dd2012-12-18 14:30:41 +00006464void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006465 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006466}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006467
Reid Kleckner8a365022013-06-24 17:51:48 +00006468void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6469 // nothing to do
6470}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006471
Reid Kleckner0503a872013-12-05 01:23:43 +00006472void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6473 // nothing to do
6474}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006475
Guy Benyei11169dd2012-12-18 14:30:41 +00006476void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006477 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006478}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006479
Guy Benyei11169dd2012-12-18 14:30:41 +00006480void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006481 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006482}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006483
Guy Benyei11169dd2012-12-18 14:30:41 +00006484void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006485 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006486}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006487
Guy Benyei11169dd2012-12-18 14:30:41 +00006488void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006489 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006490 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006491}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006492
Guy Benyei11169dd2012-12-18 14:30:41 +00006493void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006494 TL.setLBracketLoc(ReadSourceLocation());
6495 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006496 if (Record[Idx++])
6497 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006498 else
Craig Toppera13603a2014-05-22 05:54:18 +00006499 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006500}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006501
Guy Benyei11169dd2012-12-18 14:30:41 +00006502void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6503 VisitArrayTypeLoc(TL);
6504}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006505
Guy Benyei11169dd2012-12-18 14:30:41 +00006506void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6507 VisitArrayTypeLoc(TL);
6508}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006509
Guy Benyei11169dd2012-12-18 14:30:41 +00006510void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6511 VisitArrayTypeLoc(TL);
6512}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006513
Guy Benyei11169dd2012-12-18 14:30:41 +00006514void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6515 DependentSizedArrayTypeLoc TL) {
6516 VisitArrayTypeLoc(TL);
6517}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006518
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006519void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6520 DependentAddressSpaceTypeLoc TL) {
6521
6522 TL.setAttrNameLoc(ReadSourceLocation());
6523 SourceRange range;
6524 range.setBegin(ReadSourceLocation());
6525 range.setEnd(ReadSourceLocation());
6526 TL.setAttrOperandParensRange(range);
6527 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6528}
6529
Guy Benyei11169dd2012-12-18 14:30:41 +00006530void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6531 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006532 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006533}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006534
Guy Benyei11169dd2012-12-18 14:30:41 +00006535void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006536 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006537}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006538
Guy Benyei11169dd2012-12-18 14:30:41 +00006539void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006540 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006541}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006542
Guy Benyei11169dd2012-12-18 14:30:41 +00006543void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006544 TL.setLocalRangeBegin(ReadSourceLocation());
6545 TL.setLParenLoc(ReadSourceLocation());
6546 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006547 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6548 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006549 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006550 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006551 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006552 }
6553}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006554
Guy Benyei11169dd2012-12-18 14:30:41 +00006555void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6556 VisitFunctionTypeLoc(TL);
6557}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006558
Guy Benyei11169dd2012-12-18 14:30:41 +00006559void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6560 VisitFunctionTypeLoc(TL);
6561}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006562
Guy Benyei11169dd2012-12-18 14:30:41 +00006563void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006564 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006565}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006566
Guy Benyei11169dd2012-12-18 14:30:41 +00006567void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006568 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006569}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006570
Guy Benyei11169dd2012-12-18 14:30:41 +00006571void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006572 TL.setTypeofLoc(ReadSourceLocation());
6573 TL.setLParenLoc(ReadSourceLocation());
6574 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006575}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006576
Guy Benyei11169dd2012-12-18 14:30:41 +00006577void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006578 TL.setTypeofLoc(ReadSourceLocation());
6579 TL.setLParenLoc(ReadSourceLocation());
6580 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006581 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006582}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006583
Guy Benyei11169dd2012-12-18 14:30:41 +00006584void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006585 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006586}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006587
Guy Benyei11169dd2012-12-18 14:30:41 +00006588void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006589 TL.setKWLoc(ReadSourceLocation());
6590 TL.setLParenLoc(ReadSourceLocation());
6591 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006592 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006593}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006594
Guy Benyei11169dd2012-12-18 14:30:41 +00006595void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006596 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006597}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006598
Richard Smith600b5262017-01-26 20:40:47 +00006599void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6600 DeducedTemplateSpecializationTypeLoc TL) {
6601 TL.setTemplateNameLoc(ReadSourceLocation());
6602}
6603
Guy Benyei11169dd2012-12-18 14:30:41 +00006604void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006605 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006606}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006607
Guy Benyei11169dd2012-12-18 14:30:41 +00006608void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006609 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006610}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006611
Guy Benyei11169dd2012-12-18 14:30:41 +00006612void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006613 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006614 if (TL.hasAttrOperand()) {
6615 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006616 range.setBegin(ReadSourceLocation());
6617 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 TL.setAttrOperandParensRange(range);
6619 }
6620 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006621 if (Record[Idx++])
6622 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006623 else
Craig Toppera13603a2014-05-22 05:54:18 +00006624 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006625 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006626 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006627}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006628
Guy Benyei11169dd2012-12-18 14:30:41 +00006629void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006630 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006631}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006632
Guy Benyei11169dd2012-12-18 14:30:41 +00006633void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6634 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006635 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006636}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006637
Guy Benyei11169dd2012-12-18 14:30:41 +00006638void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6639 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006640 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006641}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6644 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006645 TL.setTemplateKeywordLoc(ReadSourceLocation());
6646 TL.setTemplateNameLoc(ReadSourceLocation());
6647 TL.setLAngleLoc(ReadSourceLocation());
6648 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006649 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006650 TL.setArgLocInfo(
6651 i,
6652 Reader->GetTemplateArgumentLocInfo(
6653 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006654}
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00006655
Guy Benyei11169dd2012-12-18 14:30:41 +00006656void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006657 TL.setLParenLoc(ReadSourceLocation());
6658 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006659}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006660
Guy Benyei11169dd2012-12-18 14:30:41 +00006661void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006662 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006663 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006664}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006665
Guy Benyei11169dd2012-12-18 14:30:41 +00006666void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006667 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006668}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006669
Guy Benyei11169dd2012-12-18 14:30:41 +00006670void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006671 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006672 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006673 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006674}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006675
Guy Benyei11169dd2012-12-18 14:30:41 +00006676void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6677 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006678 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006679 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006680 TL.setTemplateKeywordLoc(ReadSourceLocation());
6681 TL.setTemplateNameLoc(ReadSourceLocation());
6682 TL.setLAngleLoc(ReadSourceLocation());
6683 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006684 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006685 TL.setArgLocInfo(
6686 I,
6687 Reader->GetTemplateArgumentLocInfo(
6688 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006689}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006690
Guy Benyei11169dd2012-12-18 14:30:41 +00006691void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006692 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006693}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006694
Guy Benyei11169dd2012-12-18 14:30:41 +00006695void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006696 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006697}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006698
Manman Rene6be26c2016-09-13 17:25:08 +00006699void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6700 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006701 TL.setProtocolLAngleLoc(ReadSourceLocation());
6702 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006703 }
6704 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006705 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006706}
6707
Guy Benyei11169dd2012-12-18 14:30:41 +00006708void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006709 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006710 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6711 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006712 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006713 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006714 TL.setProtocolLAngleLoc(ReadSourceLocation());
6715 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006716 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006717 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006718}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006719
Guy Benyei11169dd2012-12-18 14:30:41 +00006720void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006721 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006722}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006723
Guy Benyei11169dd2012-12-18 14:30:41 +00006724void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006725 TL.setKWLoc(ReadSourceLocation());
6726 TL.setLParenLoc(ReadSourceLocation());
6727 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006728}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006729
Xiuli Pan9c14e282016-01-09 12:53:17 +00006730void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006731 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006732}
Guy Benyei11169dd2012-12-18 14:30:41 +00006733
David L. Jonesbe1557a2016-12-21 00:17:49 +00006734TypeSourceInfo *
6735ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6736 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006737 QualType InfoTy = readType(F, Record, Idx);
6738 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006739 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006740
6741 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006742 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006743 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6744 TLR.Visit(TL);
6745 return TInfo;
6746}
6747
6748QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006749 assert(ContextObj && "reading type with no AST context");
6750 ASTContext &Context = *ContextObj;
6751
Guy Benyei11169dd2012-12-18 14:30:41 +00006752 unsigned FastQuals = ID & Qualifiers::FastMask;
6753 unsigned Index = ID >> Qualifiers::FastWidth;
6754
6755 if (Index < NUM_PREDEF_TYPE_IDS) {
6756 QualType T;
6757 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006758 case PREDEF_TYPE_NULL_ID:
Vedant Kumar48b4f762018-04-14 01:40:48 +00006759 return QualType();
Alexey Baderbdf7c842015-09-15 12:18:29 +00006760 case PREDEF_TYPE_VOID_ID:
6761 T = Context.VoidTy;
6762 break;
6763 case PREDEF_TYPE_BOOL_ID:
6764 T = Context.BoolTy;
6765 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 case PREDEF_TYPE_CHAR_U_ID:
6767 case PREDEF_TYPE_CHAR_S_ID:
6768 // FIXME: Check that the signedness of CharTy is correct!
6769 T = Context.CharTy;
6770 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006771 case PREDEF_TYPE_UCHAR_ID:
6772 T = Context.UnsignedCharTy;
6773 break;
6774 case PREDEF_TYPE_USHORT_ID:
6775 T = Context.UnsignedShortTy;
6776 break;
6777 case PREDEF_TYPE_UINT_ID:
6778 T = Context.UnsignedIntTy;
6779 break;
6780 case PREDEF_TYPE_ULONG_ID:
6781 T = Context.UnsignedLongTy;
6782 break;
6783 case PREDEF_TYPE_ULONGLONG_ID:
6784 T = Context.UnsignedLongLongTy;
6785 break;
6786 case PREDEF_TYPE_UINT128_ID:
6787 T = Context.UnsignedInt128Ty;
6788 break;
6789 case PREDEF_TYPE_SCHAR_ID:
6790 T = Context.SignedCharTy;
6791 break;
6792 case PREDEF_TYPE_WCHAR_ID:
6793 T = Context.WCharTy;
6794 break;
6795 case PREDEF_TYPE_SHORT_ID:
6796 T = Context.ShortTy;
6797 break;
6798 case PREDEF_TYPE_INT_ID:
6799 T = Context.IntTy;
6800 break;
6801 case PREDEF_TYPE_LONG_ID:
6802 T = Context.LongTy;
6803 break;
6804 case PREDEF_TYPE_LONGLONG_ID:
6805 T = Context.LongLongTy;
6806 break;
6807 case PREDEF_TYPE_INT128_ID:
6808 T = Context.Int128Ty;
6809 break;
6810 case PREDEF_TYPE_HALF_ID:
6811 T = Context.HalfTy;
6812 break;
6813 case PREDEF_TYPE_FLOAT_ID:
6814 T = Context.FloatTy;
6815 break;
6816 case PREDEF_TYPE_DOUBLE_ID:
6817 T = Context.DoubleTy;
6818 break;
6819 case PREDEF_TYPE_LONGDOUBLE_ID:
6820 T = Context.LongDoubleTy;
6821 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006822 case PREDEF_TYPE_FLOAT16_ID:
6823 T = Context.Float16Ty;
6824 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006825 case PREDEF_TYPE_FLOAT128_ID:
6826 T = Context.Float128Ty;
6827 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006828 case PREDEF_TYPE_OVERLOAD_ID:
6829 T = Context.OverloadTy;
6830 break;
6831 case PREDEF_TYPE_BOUND_MEMBER:
6832 T = Context.BoundMemberTy;
6833 break;
6834 case PREDEF_TYPE_PSEUDO_OBJECT:
6835 T = Context.PseudoObjectTy;
6836 break;
6837 case PREDEF_TYPE_DEPENDENT_ID:
6838 T = Context.DependentTy;
6839 break;
6840 case PREDEF_TYPE_UNKNOWN_ANY:
6841 T = Context.UnknownAnyTy;
6842 break;
6843 case PREDEF_TYPE_NULLPTR_ID:
6844 T = Context.NullPtrTy;
6845 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006846 case PREDEF_TYPE_CHAR8_ID:
6847 T = Context.Char8Ty;
6848 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006849 case PREDEF_TYPE_CHAR16_ID:
6850 T = Context.Char16Ty;
6851 break;
6852 case PREDEF_TYPE_CHAR32_ID:
6853 T = Context.Char32Ty;
6854 break;
6855 case PREDEF_TYPE_OBJC_ID:
6856 T = Context.ObjCBuiltinIdTy;
6857 break;
6858 case PREDEF_TYPE_OBJC_CLASS:
6859 T = Context.ObjCBuiltinClassTy;
6860 break;
6861 case PREDEF_TYPE_OBJC_SEL:
6862 T = Context.ObjCBuiltinSelTy;
6863 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006864#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6865 case PREDEF_TYPE_##Id##_ID: \
6866 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006867 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006868#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006869 case PREDEF_TYPE_SAMPLER_ID:
6870 T = Context.OCLSamplerTy;
6871 break;
6872 case PREDEF_TYPE_EVENT_ID:
6873 T = Context.OCLEventTy;
6874 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006875 case PREDEF_TYPE_CLK_EVENT_ID:
6876 T = Context.OCLClkEventTy;
6877 break;
6878 case PREDEF_TYPE_QUEUE_ID:
6879 T = Context.OCLQueueTy;
6880 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006881 case PREDEF_TYPE_RESERVE_ID_ID:
6882 T = Context.OCLReserveIDTy;
6883 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006884 case PREDEF_TYPE_AUTO_DEDUCT:
6885 T = Context.getAutoDeductType();
6886 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006887 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6888 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006889 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006890 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6891 T = Context.ARCUnbridgedCastTy;
6892 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006893 case PREDEF_TYPE_BUILTIN_FN:
6894 T = Context.BuiltinFnTy;
6895 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006896 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6897 T = Context.OMPArraySectionTy;
6898 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006899 }
6900
6901 assert(!T.isNull() && "Unknown predefined type");
6902 return T.withFastQualifiers(FastQuals);
6903 }
6904
6905 Index -= NUM_PREDEF_TYPE_IDS;
6906 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6907 if (TypesLoaded[Index].isNull()) {
6908 TypesLoaded[Index] = readTypeRecord(Index);
6909 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006910 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006911
6912 TypesLoaded[Index]->setFromAST();
6913 if (DeserializationListener)
6914 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6915 TypesLoaded[Index]);
6916 }
6917
6918 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6919}
6920
6921QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6922 return GetType(getGlobalTypeID(F, LocalID));
6923}
6924
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006925serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006926ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6927 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6928 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006929
Guy Benyei11169dd2012-12-18 14:30:41 +00006930 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6931 return LocalID;
6932
Richard Smith37a93df2017-02-18 00:32:02 +00006933 if (!F.ModuleOffsetMap.empty())
6934 ReadModuleOffsetMap(F);
6935
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6937 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6938 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006939
Guy Benyei11169dd2012-12-18 14:30:41 +00006940 unsigned GlobalIndex = LocalIndex + I->second;
6941 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6942}
6943
6944TemplateArgumentLocInfo
6945ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6946 TemplateArgument::ArgKind Kind,
6947 const RecordData &Record,
6948 unsigned &Index) {
6949 switch (Kind) {
6950 case TemplateArgument::Expression:
6951 return ReadExpr(F);
6952 case TemplateArgument::Type:
6953 return GetTypeSourceInfo(F, Record, Index);
6954 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006955 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006956 Index);
6957 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6958 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6959 SourceLocation());
6960 }
6961 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006962 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 Index);
6964 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6965 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006966 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006967 EllipsisLoc);
6968 }
6969 case TemplateArgument::Null:
6970 case TemplateArgument::Integral:
6971 case TemplateArgument::Declaration:
6972 case TemplateArgument::NullPtr:
6973 case TemplateArgument::Pack:
6974 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00006975 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00006976 }
6977 llvm_unreachable("unexpected template argument loc");
6978}
6979
6980TemplateArgumentLoc
6981ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6982 const RecordData &Record, unsigned &Index) {
6983 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6984
6985 if (Arg.getKind() == TemplateArgument::Expression) {
6986 if (Record[Index++]) // bool InfoHasSameExpr.
6987 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6988 }
6989 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6990 Record, Index));
6991}
6992
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006993const ASTTemplateArgumentListInfo*
6994ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6995 const RecordData &Record,
6996 unsigned &Index) {
6997 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6998 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6999 unsigned NumArgsAsWritten = Record[Index++];
7000 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7001 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7002 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7003 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7004}
7005
Guy Benyei11169dd2012-12-18 14:30:41 +00007006Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7007 return GetDecl(ID);
7008}
7009
Richard Smith053f6c62014-05-16 23:01:30 +00007010void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007011 if (NumCurrentElementsDeserializing) {
7012 // We arrange to not care about the complete redeclaration chain while we're
7013 // deserializing. Just remember that the AST has marked this one as complete
7014 // but that it's not actually complete yet, so we know we still need to
7015 // complete it later.
7016 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7017 return;
7018 }
7019
Richard Smith053f6c62014-05-16 23:01:30 +00007020 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7021
Richard Smith053f6c62014-05-16 23:01:30 +00007022 // If this is a named declaration, complete it by looking it up
7023 // within its context.
7024 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007025 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007026 // all mergeable entities within it.
7027 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7028 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7029 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007030 if (!getContext().getLangOpts().CPlusPlus &&
7031 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007032 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007033 // the identifier instead. (For C++ modules, we don't store decls
7034 // in the serialized identifier table, so we do the lookup in the TU.)
7035 auto *II = Name.getAsIdentifierInfo();
7036 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007037 if (II->isOutOfDate())
7038 updateOutOfDateIdentifier(*II);
7039 } else
7040 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007041 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007042 // Find all declarations of this kind from the relevant context.
7043 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7044 auto *DC = cast<DeclContext>(DCDecl);
7045 SmallVector<Decl*, 8> Decls;
7046 FindExternalLexicalDecls(
7047 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7048 }
Richard Smith053f6c62014-05-16 23:01:30 +00007049 }
7050 }
Richard Smith50895422015-01-31 03:04:55 +00007051
7052 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7053 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7054 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7055 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7056 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7057 if (auto *Template = FD->getPrimaryTemplate())
7058 Template->LoadLazySpecializations();
7059 }
Richard Smith053f6c62014-05-16 23:01:30 +00007060}
7061
Richard Smithc2bb8182015-03-24 06:36:48 +00007062CXXCtorInitializer **
7063ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7064 RecordLocation Loc = getLocalBitOffset(Offset);
7065 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7066 SavedStreamPosition SavedPosition(Cursor);
7067 Cursor.JumpToBit(Loc.Offset);
7068 ReadingKindTracker ReadingKind(Read_Decl, *this);
7069
7070 RecordData Record;
7071 unsigned Code = Cursor.ReadCode();
7072 unsigned RecCode = Cursor.readRecord(Code, Record);
7073 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7074 Error("malformed AST file: missing C++ ctor initializers");
7075 return nullptr;
7076 }
7077
7078 unsigned Idx = 0;
7079 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7080}
7081
Guy Benyei11169dd2012-12-18 14:30:41 +00007082CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007083 assert(ContextObj && "reading base specifiers with no AST context");
7084 ASTContext &Context = *ContextObj;
7085
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007087 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007088 SavedStreamPosition SavedPosition(Cursor);
7089 Cursor.JumpToBit(Loc.Offset);
7090 ReadingKindTracker ReadingKind(Read_Decl, *this);
7091 RecordData Record;
7092 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007093 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007094 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007095 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007096 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007097 }
7098
7099 unsigned Idx = 0;
7100 unsigned NumBases = Record[Idx++];
7101 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007102 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007103 for (unsigned I = 0; I != NumBases; ++I)
7104 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7105 return Bases;
7106}
7107
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007108serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007109ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7110 if (LocalID < NUM_PREDEF_DECL_IDS)
7111 return LocalID;
7112
Richard Smith37a93df2017-02-18 00:32:02 +00007113 if (!F.ModuleOffsetMap.empty())
7114 ReadModuleOffsetMap(F);
7115
Guy Benyei11169dd2012-12-18 14:30:41 +00007116 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7117 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7118 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007119
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 return LocalID + I->second;
7121}
7122
7123bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7124 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007125 // Predefined decls aren't from any module.
7126 if (ID < NUM_PREDEF_DECL_IDS)
7127 return false;
7128
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007129 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007130 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007131}
7132
Douglas Gregor9f782892013-01-21 15:25:38 +00007133ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007135 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007136 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7137 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7138 return I->second;
7139}
7140
7141SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7142 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007143 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007144
Guy Benyei11169dd2012-12-18 14:30:41 +00007145 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7146
7147 if (Index > DeclsLoaded.size()) {
7148 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007149 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007150 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007151
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 if (Decl *D = DeclsLoaded[Index])
7153 return D->getLocation();
7154
Richard Smithcb34bd32016-03-27 07:28:06 +00007155 SourceLocation Loc;
7156 DeclCursorForID(ID, Loc);
7157 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007158}
7159
Richard Smithfe620d22015-03-05 23:24:12 +00007160static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7161 switch (ID) {
7162 case PREDEF_DECL_NULL_ID:
7163 return nullptr;
7164
7165 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7166 return Context.getTranslationUnitDecl();
7167
7168 case PREDEF_DECL_OBJC_ID_ID:
7169 return Context.getObjCIdDecl();
7170
7171 case PREDEF_DECL_OBJC_SEL_ID:
7172 return Context.getObjCSelDecl();
7173
7174 case PREDEF_DECL_OBJC_CLASS_ID:
7175 return Context.getObjCClassDecl();
7176
7177 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7178 return Context.getObjCProtocolDecl();
7179
7180 case PREDEF_DECL_INT_128_ID:
7181 return Context.getInt128Decl();
7182
7183 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7184 return Context.getUInt128Decl();
7185
7186 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7187 return Context.getObjCInstanceTypeDecl();
7188
7189 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7190 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007191
Richard Smith9b88a4c2015-07-27 05:40:23 +00007192 case PREDEF_DECL_VA_LIST_TAG:
7193 return Context.getVaListTagDecl();
7194
Charles Davisc7d5c942015-09-17 20:55:33 +00007195 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7196 return Context.getBuiltinMSVaListDecl();
7197
Richard Smithf19e1272015-03-07 00:04:49 +00007198 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7199 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007200
7201 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7202 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007203
7204 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7205 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007206
7207 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7208 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007209
7210 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7211 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007212 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007213 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007214}
7215
Richard Smithcd45dbc2014-04-19 03:48:30 +00007216Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007217 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007218 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007219 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007220 if (D) {
7221 // Track that we have merged the declaration with ID \p ID into the
7222 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007223 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007224 if (Merged.empty())
7225 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007226 }
Richard Smithfe620d22015-03-05 23:24:12 +00007227 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007229
Guy Benyei11169dd2012-12-18 14:30:41 +00007230 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7231
7232 if (Index >= DeclsLoaded.size()) {
7233 assert(0 && "declaration ID out-of-range for AST file");
7234 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007235 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007236 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007237
7238 return DeclsLoaded[Index];
7239}
7240
7241Decl *ASTReader::GetDecl(DeclID ID) {
7242 if (ID < NUM_PREDEF_DECL_IDS)
7243 return GetExistingDecl(ID);
7244
7245 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7246
7247 if (Index >= DeclsLoaded.size()) {
7248 assert(0 && "declaration ID out-of-range for AST file");
7249 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007250 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007251 }
7252
Guy Benyei11169dd2012-12-18 14:30:41 +00007253 if (!DeclsLoaded[Index]) {
7254 ReadDeclRecord(ID);
7255 if (DeserializationListener)
7256 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7257 }
7258
7259 return DeclsLoaded[Index];
7260}
7261
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007262DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007263 DeclID GlobalID) {
7264 if (GlobalID < NUM_PREDEF_DECL_IDS)
7265 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007266
Guy Benyei11169dd2012-12-18 14:30:41 +00007267 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7268 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7269 ModuleFile *Owner = I->second;
7270
7271 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7272 = M.GlobalToLocalDeclIDs.find(Owner);
7273 if (Pos == M.GlobalToLocalDeclIDs.end())
7274 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007275
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 return GlobalID - Owner->BaseDeclID + Pos->second;
7277}
7278
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007279serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 const RecordData &Record,
7281 unsigned &Idx) {
7282 if (Idx >= Record.size()) {
7283 Error("Corrupted AST file");
7284 return 0;
7285 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007286
Guy Benyei11169dd2012-12-18 14:30:41 +00007287 return getGlobalDeclID(F, Record[Idx++]);
7288}
7289
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007290/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007291///
7292/// This operation will read a new statement from the external
7293/// source each time it is called, and is meant to be used via a
7294/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7295Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7296 // Switch case IDs are per Decl.
7297 ClearSwitchCaseIDs();
7298
7299 // Offset here is a global offset across the entire chain.
7300 RecordLocation Loc = getLocalBitOffset(Offset);
7301 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007302 assert(NumCurrentElementsDeserializing == 0 &&
7303 "should not be called while already deserializing");
7304 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007305 return ReadStmtFromStream(*Loc.F);
7306}
7307
Richard Smith3cb15722015-08-05 22:41:45 +00007308void ASTReader::FindExternalLexicalDecls(
7309 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7310 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007311 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7312
Richard Smith9ccdd932015-08-06 22:14:12 +00007313 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007314 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7315 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7316 auto K = (Decl::Kind)+LexicalDecls[I];
7317 if (!IsKindWeWant(K))
7318 continue;
7319
7320 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7321
7322 // Don't add predefined declarations to the lexical context more
7323 // than once.
7324 if (ID < NUM_PREDEF_DECL_IDS) {
7325 if (PredefsVisited[ID])
7326 continue;
7327
7328 PredefsVisited[ID] = true;
7329 }
7330
7331 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007332 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007333 if (!DC->isDeclInLexicalTraversal(D))
7334 Decls.push_back(D);
7335 }
7336 }
7337 };
7338
7339 if (isa<TranslationUnitDecl>(DC)) {
7340 for (auto Lexical : TULexicalDecls)
7341 Visit(Lexical.first, Lexical.second);
7342 } else {
7343 auto I = LexicalDecls.find(DC);
7344 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007345 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007346 }
7347
Guy Benyei11169dd2012-12-18 14:30:41 +00007348 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007349}
7350
7351namespace {
7352
7353class DeclIDComp {
7354 ASTReader &Reader;
7355 ModuleFile &Mod;
7356
7357public:
7358 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7359
7360 bool operator()(LocalDeclID L, LocalDeclID R) const {
7361 SourceLocation LHS = getLocation(L);
7362 SourceLocation RHS = getLocation(R);
7363 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7364 }
7365
7366 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7367 SourceLocation RHS = getLocation(R);
7368 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7369 }
7370
7371 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7372 SourceLocation LHS = getLocation(L);
7373 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7374 }
7375
7376 SourceLocation getLocation(LocalDeclID ID) const {
7377 return Reader.getSourceManager().getFileLoc(
7378 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7379 }
7380};
7381
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007382} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007383
7384void ASTReader::FindFileRegionDecls(FileID File,
7385 unsigned Offset, unsigned Length,
7386 SmallVectorImpl<Decl *> &Decls) {
7387 SourceManager &SM = getSourceManager();
7388
7389 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7390 if (I == FileDeclIDs.end())
7391 return;
7392
7393 FileDeclsInfo &DInfo = I->second;
7394 if (DInfo.Decls.empty())
7395 return;
7396
7397 SourceLocation
7398 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7399 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7400
7401 DeclIDComp DIDComp(*this, *DInfo.Mod);
7402 ArrayRef<serialization::LocalDeclID>::iterator
7403 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7404 BeginLoc, DIDComp);
7405 if (BeginIt != DInfo.Decls.begin())
7406 --BeginIt;
7407
7408 // If we are pointing at a top-level decl inside an objc container, we need
7409 // to backtrack until we find it otherwise we will fail to report that the
7410 // region overlaps with an objc container.
7411 while (BeginIt != DInfo.Decls.begin() &&
7412 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7413 ->isTopLevelDeclInObjCContainer())
7414 --BeginIt;
7415
7416 ArrayRef<serialization::LocalDeclID>::iterator
7417 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7418 EndLoc, DIDComp);
7419 if (EndIt != DInfo.Decls.end())
7420 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007421
Guy Benyei11169dd2012-12-18 14:30:41 +00007422 for (ArrayRef<serialization::LocalDeclID>::iterator
7423 DIt = BeginIt; DIt != EndIt; ++DIt)
7424 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7425}
7426
Richard Smith9ce12e32013-02-07 03:30:24 +00007427bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007428ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7429 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007430 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007431 "DeclContext has no visible decls in storage");
7432 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007433 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007434
Richard Smithd88a7f12015-09-01 20:35:42 +00007435 auto It = Lookups.find(DC);
7436 if (It == Lookups.end())
7437 return false;
7438
Richard Smith8c913ec2014-08-14 02:21:01 +00007439 Deserializing LookupResults(this);
7440
Richard Smithd88a7f12015-09-01 20:35:42 +00007441 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007443 for (DeclID ID : It->second.Table.find(Name)) {
7444 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007445 if (ND->getDeclName() == Name)
7446 Decls.push_back(ND);
7447 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007448
Guy Benyei11169dd2012-12-18 14:30:41 +00007449 ++NumVisibleDeclContextsRead;
7450 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007451 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007452}
7453
Guy Benyei11169dd2012-12-18 14:30:41 +00007454void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7455 if (!DC->hasExternalVisibleStorage())
7456 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007457
7458 auto It = Lookups.find(DC);
7459 assert(It != Lookups.end() &&
7460 "have external visible storage but no lookup tables");
7461
Craig Topper79be4cd2013-07-05 04:33:53 +00007462 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007463
Vedant Kumar48b4f762018-04-14 01:40:48 +00007464 for (DeclID ID : It->second.Table.findAll()) {
7465 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007466 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007467 }
7468
Guy Benyei11169dd2012-12-18 14:30:41 +00007469 ++NumVisibleDeclContextsRead;
7470
Vedant Kumar48b4f762018-04-14 01:40:48 +00007471 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7472 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7473 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007474 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7475}
7476
Richard Smithd88a7f12015-09-01 20:35:42 +00007477const serialization::reader::DeclContextLookupTable *
7478ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7479 auto I = Lookups.find(Primary);
7480 return I == Lookups.end() ? nullptr : &I->second;
7481}
7482
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007483/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007484/// before receiving the implementation, and codegen depends on this.
7485/// We simulate this by deserializing and passing to consumer the methods of the
7486/// implementation before passing the deserialized implementation decl.
7487static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7488 ASTConsumer *Consumer) {
7489 assert(ImplD && Consumer);
7490
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007491 for (auto *I : ImplD->methods())
7492 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007493
7494 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7495}
7496
Guy Benyei11169dd2012-12-18 14:30:41 +00007497void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007498 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007499 PassObjCImplDeclToConsumer(ImplD, Consumer);
7500 else
7501 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7502}
7503
7504void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7505 this->Consumer = Consumer;
7506
Richard Smith9e2341d2015-03-23 03:25:59 +00007507 if (Consumer)
7508 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007509
7510 if (DeserializationListener)
7511 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007512}
7513
7514void ASTReader::PrintStats() {
7515 std::fprintf(stderr, "*** AST File Statistics:\n");
7516
7517 unsigned NumTypesLoaded
7518 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7519 QualType());
7520 unsigned NumDeclsLoaded
7521 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007522 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007523 unsigned NumIdentifiersLoaded
7524 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7525 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007526 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007527 unsigned NumMacrosLoaded
7528 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7529 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007530 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007531 unsigned NumSelectorsLoaded
7532 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7533 SelectorsLoaded.end(),
7534 Selector());
7535
7536 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7537 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7538 NumSLocEntriesRead, TotalNumSLocEntries,
7539 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7540 if (!TypesLoaded.empty())
7541 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7542 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7543 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7544 if (!DeclsLoaded.empty())
7545 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7546 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7547 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7548 if (!IdentifiersLoaded.empty())
7549 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7550 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7551 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7552 if (!MacrosLoaded.empty())
7553 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7554 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7555 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7556 if (!SelectorsLoaded.empty())
7557 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7558 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7559 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7560 if (TotalNumStatements)
7561 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7562 NumStatementsRead, TotalNumStatements,
7563 ((float)NumStatementsRead/TotalNumStatements * 100));
7564 if (TotalNumMacros)
7565 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7566 NumMacrosRead, TotalNumMacros,
7567 ((float)NumMacrosRead/TotalNumMacros * 100));
7568 if (TotalLexicalDeclContexts)
7569 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7570 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7571 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7572 * 100));
7573 if (TotalVisibleDeclContexts)
7574 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7575 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7576 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7577 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007578 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007579 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7580 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7581 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7582 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007583 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007584 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7585 NumMethodPoolHits, NumMethodPoolLookups,
7586 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007587 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007588 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7589 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7590 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7591 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007592 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007593 std::fprintf(stderr,
7594 " %u / %u identifier table lookups succeeded (%f%%)\n",
7595 NumIdentifierLookupHits, NumIdentifierLookups,
7596 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007597
Douglas Gregore060e572013-01-25 01:03:03 +00007598 if (GlobalIndex) {
7599 std::fprintf(stderr, "\n");
7600 GlobalIndex->printStats();
7601 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007602
Guy Benyei11169dd2012-12-18 14:30:41 +00007603 std::fprintf(stderr, "\n");
7604 dump();
7605 std::fprintf(stderr, "\n");
7606}
7607
7608template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007609LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007610dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007611 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007612 InitialCapacity> &Map) {
7613 if (Map.begin() == Map.end())
7614 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007615
Vedant Kumar48b4f762018-04-14 01:40:48 +00007616 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7617
Guy Benyei11169dd2012-12-18 14:30:41 +00007618 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007619 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7620 I != IEnd; ++I) {
7621 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7622 << "\n";
7623 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007624}
7625
Yaron Kerencdae9412016-01-29 19:38:18 +00007626LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007627 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7628 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7629 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7630 dumpModuleIDMap("Global type map", GlobalTypeMap);
7631 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7632 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7633 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7634 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7635 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007636 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007637 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007638
Guy Benyei11169dd2012-12-18 14:30:41 +00007639 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007640 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007641 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007642}
7643
7644/// Return the amount of memory used by memory buffers, breaking down
7645/// by heap-backed versus mmap'ed memory.
7646void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007647 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007648 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007649 size_t bytes = buf->getBufferSize();
7650 switch (buf->getBufferKind()) {
7651 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7652 sizes.malloc_bytes += bytes;
7653 break;
7654 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7655 sizes.mmap_bytes += bytes;
7656 break;
7657 }
7658 }
7659 }
7660}
7661
7662void ASTReader::InitializeSema(Sema &S) {
7663 SemaObj = &S;
7664 S.addExternalSource(this);
7665
7666 // Makes sure any declarations that were deserialized "too early"
7667 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007668 for (uint64_t ID : PreloadedDeclIDs) {
7669 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007670 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007671 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007672 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007673
Richard Smith3d8e97e2013-10-18 06:54:39 +00007674 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007675 if (!FPPragmaOptions.empty()) {
7676 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007677 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007678 }
7679
Yaxun Liu5b746652016-12-18 05:18:55 +00007680 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7681 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7682 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007683
7684 UpdateSema();
7685}
7686
7687void ASTReader::UpdateSema() {
7688 assert(SemaObj && "no Sema to update");
7689
7690 // Load the offsets of the declarations that Sema references.
7691 // They will be lazily deserialized when needed.
7692 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007693 assert(SemaDeclRefs.size() % 3 == 0);
7694 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007695 if (!SemaObj->StdNamespace)
7696 SemaObj->StdNamespace = SemaDeclRefs[I];
7697 if (!SemaObj->StdBadAlloc)
7698 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007699 if (!SemaObj->StdAlignValT)
7700 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007701 }
7702 SemaDeclRefs.clear();
7703 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007704
Nico Weber779355f2016-03-02 23:22:00 +00007705 // Update the state of pragmas. Use the same API as if we had encountered the
7706 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007707 if(OptimizeOffPragmaLocation.isValid())
7708 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007709 if (PragmaMSStructState != -1)
7710 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007711 if (PointersToMembersPragmaLocation.isValid()) {
7712 SemaObj->ActOnPragmaMSPointersToMembers(
7713 (LangOptions::PragmaMSPointersToMembersKind)
7714 PragmaMSPointersToMembersState,
7715 PointersToMembersPragmaLocation);
7716 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007717 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007718
7719 if (PragmaPackCurrentValue) {
7720 // The bottom of the stack might have a default value. It must be adjusted
7721 // to the current value to ensure that the packing state is preserved after
7722 // popping entries that were included/imported from a PCH/module.
7723 bool DropFirst = false;
7724 if (!PragmaPackStack.empty() &&
7725 PragmaPackStack.front().Location.isInvalid()) {
7726 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7727 "Expected a default alignment value");
7728 SemaObj->PackStack.Stack.emplace_back(
7729 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007730 SemaObj->PackStack.CurrentPragmaLocation,
7731 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007732 DropFirst = true;
7733 }
7734 for (const auto &Entry :
7735 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7736 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007737 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007738 if (PragmaPackCurrentLocation.isInvalid()) {
7739 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7740 "Expected a default alignment value");
7741 // Keep the current values.
7742 } else {
7743 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7744 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7745 }
7746 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007747}
7748
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007749IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007750 // Note that we are loading an identifier.
7751 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007752
Douglas Gregor7211ac12013-01-25 23:32:03 +00007753 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007754 NumIdentifierLookups,
7755 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007756
7757 // We don't need to do identifier table lookups in C++ modules (we preload
7758 // all interesting declarations, and don't need to use the scope for name
7759 // lookups). Perform the lookup in PCH files, though, since we don't build
7760 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007761 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007762 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007763 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007764 break;
7765 } else {
7766 // If there is a global index, look there first to determine which modules
7767 // provably do not have any results for this identifier.
7768 GlobalModuleIndex::HitSet Hits;
7769 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7770 if (!loadGlobalIndex()) {
7771 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7772 HitsPtr = &Hits;
7773 }
7774 }
7775
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007776 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007777 }
7778
Guy Benyei11169dd2012-12-18 14:30:41 +00007779 IdentifierInfo *II = Visitor.getIdentifierInfo();
7780 markIdentifierUpToDate(II);
7781 return II;
7782}
7783
7784namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007786 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 /// identifiers stored within a set of AST files.
7788 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007789 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007790 const ASTReader &Reader;
7791
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007792 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 /// the AST reader.
7794 unsigned Index;
7795
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007796 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 /// of the current AST file.
7798 ASTIdentifierLookupTable::key_iterator Current;
7799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007800 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007801 /// the current AST file.
7802 ASTIdentifierLookupTable::key_iterator End;
7803
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007804 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007805 bool SkipModules;
7806
Guy Benyei11169dd2012-12-18 14:30:41 +00007807 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007808 explicit ASTIdentifierIterator(const ASTReader &Reader,
7809 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007810
Craig Topper3e89dfe2014-03-13 02:13:41 +00007811 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007812 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007813
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007814} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007815
Ben Langmuir537c5b52016-05-04 00:53:13 +00007816ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7817 bool SkipModules)
7818 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007819}
7820
7821StringRef ASTIdentifierIterator::Next() {
7822 while (Current == End) {
7823 // If we have exhausted all of our AST files, we're done.
7824 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007825 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007826
7827 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007828 ModuleFile &F = Reader.ModuleMgr[Index];
7829 if (SkipModules && F.isModule())
7830 continue;
7831
Vedant Kumar48b4f762018-04-14 01:40:48 +00007832 ASTIdentifierLookupTable *IdTable =
7833 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007834 Current = IdTable->key_begin();
7835 End = IdTable->key_end();
7836 }
7837
7838 // We have any identifiers remaining in the current AST file; return
7839 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007840 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007842 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007843}
7844
Ben Langmuir537c5b52016-05-04 00:53:13 +00007845namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007846
Ben Langmuir537c5b52016-05-04 00:53:13 +00007847/// A utility for appending two IdentifierIterators.
7848class ChainedIdentifierIterator : public IdentifierIterator {
7849 std::unique_ptr<IdentifierIterator> Current;
7850 std::unique_ptr<IdentifierIterator> Queued;
7851
7852public:
7853 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7854 std::unique_ptr<IdentifierIterator> Second)
7855 : Current(std::move(First)), Queued(std::move(Second)) {}
7856
7857 StringRef Next() override {
7858 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007859 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007860
7861 StringRef result = Current->Next();
7862 if (!result.empty())
7863 return result;
7864
7865 // Try the queued iterator, which may itself be empty.
7866 Current.reset();
7867 std::swap(Current, Queued);
7868 return Next();
7869 }
7870};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007871
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007872} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007873
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007874IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007875 if (!loadGlobalIndex()) {
7876 std::unique_ptr<IdentifierIterator> ReaderIter(
7877 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7878 std::unique_ptr<IdentifierIterator> ModulesIter(
7879 GlobalIndex->createIdentifierIterator());
7880 return new ChainedIdentifierIterator(std::move(ReaderIter),
7881 std::move(ModulesIter));
7882 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007883
Guy Benyei11169dd2012-12-18 14:30:41 +00007884 return new ASTIdentifierIterator(*this);
7885}
7886
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007887namespace clang {
7888namespace serialization {
7889
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 class ReadMethodPoolVisitor {
7891 ASTReader &Reader;
7892 Selector Sel;
7893 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007894 unsigned InstanceBits = 0;
7895 unsigned FactoryBits = 0;
7896 bool InstanceHasMoreThanOneDecl = false;
7897 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007898 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7899 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007900
7901 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007902 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007903 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007904 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007905
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007906 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007907 if (!M.SelectorLookupTable)
7908 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007909
Guy Benyei11169dd2012-12-18 14:30:41 +00007910 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007911 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007912 return true;
7913
Richard Smithbdf2d932015-07-30 03:37:16 +00007914 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007915 ASTSelectorLookupTable *PoolTable
7916 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007917 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007918 if (Pos == PoolTable->end())
7919 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007920
Richard Smithbdf2d932015-07-30 03:37:16 +00007921 ++Reader.NumMethodPoolTableHits;
7922 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007923 // FIXME: Not quite happy with the statistics here. We probably should
7924 // disable this tracking when called via LoadSelector.
7925 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007926 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007927 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007928 if (Reader.DeserializationListener)
7929 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007930
Richard Smithbdf2d932015-07-30 03:37:16 +00007931 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7932 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7933 InstanceBits = Data.InstanceBits;
7934 FactoryBits = Data.FactoryBits;
7935 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7936 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 return true;
7938 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007940 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007941 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7942 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007943 }
7944
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007945 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007946 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007947 return FactoryMethods;
7948 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007949
7950 unsigned getInstanceBits() const { return InstanceBits; }
7951 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007952
Nico Weberff4b35e2014-12-27 22:14:15 +00007953 bool instanceHasMoreThanOneDecl() const {
7954 return InstanceHasMoreThanOneDecl;
7955 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007956
Nico Weberff4b35e2014-12-27 22:14:15 +00007957 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007958 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007959
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007960} // namespace serialization
7961} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007963/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00007964static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7965 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007966 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7967 S.addMethodToGlobalList(&List, Methods[I]);
7968 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007969}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007970
Guy Benyei11169dd2012-12-18 14:30:41 +00007971void ASTReader::ReadMethodPool(Selector Sel) {
7972 // Get the selector generation and update it to the current generation.
7973 unsigned &Generation = SelectorGeneration[Sel];
7974 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007975 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007976 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007977
Guy Benyei11169dd2012-12-18 14:30:41 +00007978 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007979 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007980 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007981 ModuleMgr.visit(Visitor);
7982
Guy Benyei11169dd2012-12-18 14:30:41 +00007983 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007984 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007985 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007986
7987 ++NumMethodPoolHits;
7988
Guy Benyei11169dd2012-12-18 14:30:41 +00007989 if (!getSema())
7990 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007991
Guy Benyei11169dd2012-12-18 14:30:41 +00007992 Sema &S = *getSema();
7993 Sema::GlobalMethodPool::iterator Pos
7994 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007995
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007996 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007997 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007998 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007999 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008000
8001 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8002 // when building a module we keep every method individually and may need to
8003 // update hasMoreThanOneDecl as we add the methods.
8004 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8005 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008006}
8007
Manman Rena0f31a02016-04-29 19:04:05 +00008008void ASTReader::updateOutOfDateSelector(Selector Sel) {
8009 if (SelectorOutOfDate[Sel])
8010 ReadMethodPool(Sel);
8011}
8012
Guy Benyei11169dd2012-12-18 14:30:41 +00008013void ASTReader::ReadKnownNamespaces(
8014 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8015 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008016
Vedant Kumar48b4f762018-04-14 01:40:48 +00008017 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8018 if (NamespaceDecl *Namespace
8019 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008020 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008021 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008022}
8023
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008024void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008025 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008026 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008027 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008028 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008029 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008030 Undefined.insert(std::make_pair(D, Loc));
8031 }
8032}
Nick Lewycky8334af82013-01-26 00:35:08 +00008033
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008034void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8035 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8036 Exprs) {
8037 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008038 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008039 uint64_t Count = DelayedDeleteExprs[Idx++];
8040 for (uint64_t C = 0; C < Count; ++C) {
8041 SourceLocation DeleteLoc =
8042 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8043 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8044 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8045 }
8046 }
8047}
8048
Guy Benyei11169dd2012-12-18 14:30:41 +00008049void ASTReader::ReadTentativeDefinitions(
8050 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008051 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8052 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008053 if (Var)
8054 TentativeDefs.push_back(Var);
8055 }
8056 TentativeDefinitions.clear();
8057}
8058
8059void ASTReader::ReadUnusedFileScopedDecls(
8060 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008061 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8062 DeclaratorDecl *D
8063 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 if (D)
8065 Decls.push_back(D);
8066 }
8067 UnusedFileScopedDecls.clear();
8068}
8069
8070void ASTReader::ReadDelegatingConstructors(
8071 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008072 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8073 CXXConstructorDecl *D
8074 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008075 if (D)
8076 Decls.push_back(D);
8077 }
8078 DelegatingCtorDecls.clear();
8079}
8080
8081void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008082 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8083 TypedefNameDecl *D
8084 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008085 if (D)
8086 Decls.push_back(D);
8087 }
8088 ExtVectorDecls.clear();
8089}
8090
Nico Weber72889432014-09-06 01:25:55 +00008091void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8092 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008093 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8094 ++I) {
8095 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8096 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008097 if (D)
8098 Decls.insert(D);
8099 }
8100 UnusedLocalTypedefNameCandidates.clear();
8101}
8102
Guy Benyei11169dd2012-12-18 14:30:41 +00008103void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008104 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 if (ReferencedSelectorsData.empty())
8106 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008107
Guy Benyei11169dd2012-12-18 14:30:41 +00008108 // If there are @selector references added them to its pool. This is for
8109 // implementation of -Wselector.
8110 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8111 unsigned I = 0;
8112 while (I < DataSize) {
8113 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8114 SourceLocation SelLoc
8115 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8116 Sels.push_back(std::make_pair(Sel, SelLoc));
8117 }
8118 ReferencedSelectorsData.clear();
8119}
8120
8121void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008122 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008123 if (WeakUndeclaredIdentifiers.empty())
8124 return;
8125
8126 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008127 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008129 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008130 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8131 SourceLocation Loc
8132 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8133 bool Used = WeakUndeclaredIdentifiers[I++];
8134 WeakInfo WI(AliasId, Loc);
8135 WI.setUsed(Used);
8136 WeakIDs.push_back(std::make_pair(WeakId, WI));
8137 }
8138 WeakUndeclaredIdentifiers.clear();
8139}
8140
8141void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8142 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8143 ExternalVTableUse VT;
8144 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8145 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8146 VT.DefinitionRequired = VTableUses[Idx++];
8147 VTables.push_back(VT);
8148 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008149
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 VTableUses.clear();
8151}
8152
8153void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008154 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008155 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008156 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 SourceLocation Loc
8158 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8159
8160 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008161 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 PendingInstantiations.clear();
8163}
8164
Richard Smithe40f2ba2013-08-07 21:41:30 +00008165void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008166 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8167 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008168 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8169 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008170 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008171
Justin Lebar28f09c52016-10-10 16:26:08 +00008172 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008173 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8174
8175 ModuleFile *F = getOwningModuleFile(LT->D);
8176 assert(F && "No module");
8177
8178 unsigned TokN = LateParsedTemplates[Idx++];
8179 LT->Toks.reserve(TokN);
8180 for (unsigned T = 0; T < TokN; ++T)
8181 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8182
Justin Lebar28f09c52016-10-10 16:26:08 +00008183 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008184 }
8185
8186 LateParsedTemplates.clear();
8187}
8188
Guy Benyei11169dd2012-12-18 14:30:41 +00008189void ASTReader::LoadSelector(Selector Sel) {
8190 // It would be complicated to avoid reading the methods anyway. So don't.
8191 ReadMethodPool(Sel);
8192}
8193
8194void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8195 assert(ID && "Non-zero identifier ID required");
8196 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8197 IdentifiersLoaded[ID - 1] = II;
8198 if (DeserializationListener)
8199 DeserializationListener->IdentifierRead(ID, II);
8200}
8201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008202/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008203/// identifier.
8204///
8205/// If the AST reader is currently in a state where the given declaration IDs
8206/// cannot safely be resolved, they are queued until it is safe to resolve
8207/// them.
8208///
8209/// \param II an IdentifierInfo that refers to one or more globally-visible
8210/// declarations.
8211///
8212/// \param DeclIDs the set of declaration IDs with the name @p II that are
8213/// visible at global scope.
8214///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008215/// \param Decls if non-null, this vector will be populated with the set of
8216/// deserialized declarations. These declarations will not be pushed into
8217/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008218void
8219ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8220 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008221 SmallVectorImpl<Decl *> *Decls) {
8222 if (NumCurrentElementsDeserializing && !Decls) {
8223 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 return;
8225 }
8226
Vedant Kumar48b4f762018-04-14 01:40:48 +00008227 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008228 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008229 // Queue this declaration so that it will be added to the
8230 // translation unit scope and identifier's declaration chain
8231 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008232 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008233 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008235
Vedant Kumar48b4f762018-04-14 01:40:48 +00008236 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008237
8238 // If we're simply supposed to record the declarations, do so now.
8239 if (Decls) {
8240 Decls->push_back(D);
8241 continue;
8242 }
8243
8244 // Introduce this declaration into the translation-unit scope
8245 // and add it to the declaration chain for this identifier, so
8246 // that (unqualified) name lookup will find it.
8247 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008248 }
8249}
8250
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008251IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008253 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008254
8255 if (IdentifiersLoaded.empty()) {
8256 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008257 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008258 }
8259
8260 ID -= 1;
8261 if (!IdentifiersLoaded[ID]) {
8262 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8263 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8264 ModuleFile *M = I->second;
8265 unsigned Index = ID - M->BaseIdentifierID;
8266 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8267
8268 // All of the strings in the AST file are preceded by a 16-bit length.
8269 // Extract that 16-bit length to avoid having to execute strlen().
8270 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8271 // unsigned integers. This is important to avoid integer overflow when
8272 // we cast them to 'unsigned'.
8273 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8274 unsigned StrLen = (((unsigned) StrLenPtr[0])
8275 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008276 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8277 IdentifiersLoaded[ID] = &II;
8278 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008279 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008280 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008281 }
8282
8283 return IdentifiersLoaded[ID];
8284}
8285
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008286IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8287 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008288}
8289
8290IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8291 if (LocalID < NUM_PREDEF_IDENT_IDS)
8292 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008293
Richard Smith37a93df2017-02-18 00:32:02 +00008294 if (!M.ModuleOffsetMap.empty())
8295 ReadModuleOffsetMap(M);
8296
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8298 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008299 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008300 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008301
Guy Benyei11169dd2012-12-18 14:30:41 +00008302 return LocalID + I->second;
8303}
8304
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008305MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008306 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008307 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008308
8309 if (MacrosLoaded.empty()) {
8310 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008311 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008312 }
8313
8314 ID -= NUM_PREDEF_MACRO_IDS;
8315 if (!MacrosLoaded[ID]) {
8316 GlobalMacroMapType::iterator I
8317 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8318 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8319 ModuleFile *M = I->second;
8320 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008321 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008322
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008323 if (DeserializationListener)
8324 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8325 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008326 }
8327
8328 return MacrosLoaded[ID];
8329}
8330
8331MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8332 if (LocalID < NUM_PREDEF_MACRO_IDS)
8333 return LocalID;
8334
Richard Smith37a93df2017-02-18 00:32:02 +00008335 if (!M.ModuleOffsetMap.empty())
8336 ReadModuleOffsetMap(M);
8337
Guy Benyei11169dd2012-12-18 14:30:41 +00008338 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8339 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8340 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8341
8342 return LocalID + I->second;
8343}
8344
8345serialization::SubmoduleID
8346ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8347 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8348 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008349
Richard Smith37a93df2017-02-18 00:32:02 +00008350 if (!M.ModuleOffsetMap.empty())
8351 ReadModuleOffsetMap(M);
8352
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8354 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008355 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008357
Guy Benyei11169dd2012-12-18 14:30:41 +00008358 return LocalID + I->second;
8359}
8360
8361Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8362 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8363 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008364 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008365 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008366
Guy Benyei11169dd2012-12-18 14:30:41 +00008367 if (GlobalID > SubmodulesLoaded.size()) {
8368 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008369 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008371
Guy Benyei11169dd2012-12-18 14:30:41 +00008372 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8373}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008374
8375Module *ASTReader::getModule(unsigned ID) {
8376 return getSubmodule(ID);
8377}
8378
Richard Smithd88a7f12015-09-01 20:35:42 +00008379ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8380 if (ID & 1) {
8381 // It's a module, look it up by submodule ID.
8382 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8383 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8384 } else {
8385 // It's a prefix (preamble, PCH, ...). Look it up by index.
8386 unsigned IndexFromEnd = ID >> 1;
8387 assert(IndexFromEnd && "got reference to unknown module file");
8388 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8389 }
8390}
8391
8392unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8393 if (!F)
8394 return 1;
8395
8396 // For a file representing a module, use the submodule ID of the top-level
8397 // module as the file ID. For any other kind of file, the number of such
8398 // files loaded beforehand will be the same on reload.
8399 // FIXME: Is this true even if we have an explicit module file and a PCH?
8400 if (F->isModule())
8401 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8402
8403 auto PCHModules = getModuleManager().pch_modules();
8404 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8405 assert(I != PCHModules.end() && "emitting reference to unknown file");
8406 return (I - PCHModules.end()) << 1;
8407}
8408
Adrian Prantl15bcf702015-06-30 17:39:43 +00008409llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8410ASTReader::getSourceDescriptor(unsigned ID) {
8411 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008412 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008413
8414 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008415 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008416 const auto &PCHChain = ModuleMgr.pch_modules();
8417 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008418 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008419 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008420 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8421 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8422 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008423 }
8424 return None;
8425}
8426
David Blaikie1ac9c982017-04-11 21:13:37 +00008427ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008428 auto I = DefinitionSource.find(FD);
8429 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008430 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008431 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008432}
8433
Guy Benyei11169dd2012-12-18 14:30:41 +00008434Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8435 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8436}
8437
8438Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8439 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008440 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008441
8442 if (ID > SelectorsLoaded.size()) {
8443 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008444 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008445 }
8446
Craig Toppera13603a2014-05-22 05:54:18 +00008447 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008448 // Load this selector from the selector table.
8449 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8450 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8451 ModuleFile &M = *I->second;
8452 ASTSelectorLookupTrait Trait(*this, M);
8453 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8454 SelectorsLoaded[ID - 1] =
8455 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8456 if (DeserializationListener)
8457 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8458 }
8459
8460 return SelectorsLoaded[ID - 1];
8461}
8462
8463Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8464 return DecodeSelector(ID);
8465}
8466
8467uint32_t ASTReader::GetNumExternalSelectors() {
8468 // ID 0 (the null selector) is considered an external selector.
8469 return getTotalNumSelectors() + 1;
8470}
8471
8472serialization::SelectorID
8473ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8474 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8475 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008476
Richard Smith37a93df2017-02-18 00:32:02 +00008477 if (!M.ModuleOffsetMap.empty())
8478 ReadModuleOffsetMap(M);
8479
Guy Benyei11169dd2012-12-18 14:30:41 +00008480 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8481 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008482 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008483 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008484
Guy Benyei11169dd2012-12-18 14:30:41 +00008485 return LocalID + I->second;
8486}
8487
8488DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008489ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008490 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008491 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008492 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008493 switch (Kind) {
8494 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008495 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008496
8497 case DeclarationName::ObjCZeroArgSelector:
8498 case DeclarationName::ObjCOneArgSelector:
8499 case DeclarationName::ObjCMultiArgSelector:
8500 return DeclarationName(ReadSelector(F, Record, Idx));
8501
8502 case DeclarationName::CXXConstructorName:
8503 return Context.DeclarationNames.getCXXConstructorName(
8504 Context.getCanonicalType(readType(F, Record, Idx)));
8505
8506 case DeclarationName::CXXDestructorName:
8507 return Context.DeclarationNames.getCXXDestructorName(
8508 Context.getCanonicalType(readType(F, Record, Idx)));
8509
Richard Smith35845152017-02-07 01:37:30 +00008510 case DeclarationName::CXXDeductionGuideName:
8511 return Context.DeclarationNames.getCXXDeductionGuideName(
8512 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8513
Guy Benyei11169dd2012-12-18 14:30:41 +00008514 case DeclarationName::CXXConversionFunctionName:
8515 return Context.DeclarationNames.getCXXConversionFunctionName(
8516 Context.getCanonicalType(readType(F, Record, Idx)));
8517
8518 case DeclarationName::CXXOperatorName:
8519 return Context.DeclarationNames.getCXXOperatorName(
8520 (OverloadedOperatorKind)Record[Idx++]);
8521
8522 case DeclarationName::CXXLiteralOperatorName:
8523 return Context.DeclarationNames.getCXXLiteralOperatorName(
8524 GetIdentifierInfo(F, Record, Idx));
8525
8526 case DeclarationName::CXXUsingDirective:
8527 return DeclarationName::getUsingDirectiveName();
8528 }
8529
8530 llvm_unreachable("Invalid NameKind!");
8531}
8532
8533void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8534 DeclarationNameLoc &DNLoc,
8535 DeclarationName Name,
8536 const RecordData &Record, unsigned &Idx) {
8537 switch (Name.getNameKind()) {
8538 case DeclarationName::CXXConstructorName:
8539 case DeclarationName::CXXDestructorName:
8540 case DeclarationName::CXXConversionFunctionName:
8541 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8542 break;
8543
8544 case DeclarationName::CXXOperatorName:
8545 DNLoc.CXXOperatorName.BeginOpNameLoc
8546 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8547 DNLoc.CXXOperatorName.EndOpNameLoc
8548 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8549 break;
8550
8551 case DeclarationName::CXXLiteralOperatorName:
8552 DNLoc.CXXLiteralOperatorName.OpNameLoc
8553 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8554 break;
8555
8556 case DeclarationName::Identifier:
8557 case DeclarationName::ObjCZeroArgSelector:
8558 case DeclarationName::ObjCOneArgSelector:
8559 case DeclarationName::ObjCMultiArgSelector:
8560 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008561 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008562 break;
8563 }
8564}
8565
8566void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8567 DeclarationNameInfo &NameInfo,
8568 const RecordData &Record, unsigned &Idx) {
8569 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8570 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8571 DeclarationNameLoc DNLoc;
8572 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8573 NameInfo.setInfo(DNLoc);
8574}
8575
8576void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8577 const RecordData &Record, unsigned &Idx) {
8578 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8579 unsigned NumTPLists = Record[Idx++];
8580 Info.NumTemplParamLists = NumTPLists;
8581 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008582 Info.TemplParamLists =
8583 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008584 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008585 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8586 }
8587}
8588
8589TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008590ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008591 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008592 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008593 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008594 switch (Kind) {
8595 case TemplateName::Template:
8596 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8597
8598 case TemplateName::OverloadedTemplate: {
8599 unsigned size = Record[Idx++];
8600 UnresolvedSet<8> Decls;
8601 while (size--)
8602 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8603
8604 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8605 }
8606
8607 case TemplateName::QualifiedTemplate: {
8608 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8609 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008610 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008611 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8612 }
8613
8614 case TemplateName::DependentTemplate: {
8615 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8616 if (Record[Idx++]) // isIdentifier
8617 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008618 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008619 Idx));
8620 return Context.getDependentTemplateName(NNS,
8621 (OverloadedOperatorKind)Record[Idx++]);
8622 }
8623
8624 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008625 TemplateTemplateParmDecl *param
8626 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8627 if (!param) return TemplateName();
8628 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8629 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00008630 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008631
Guy Benyei11169dd2012-12-18 14:30:41 +00008632 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008633 TemplateTemplateParmDecl *Param
8634 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008635 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008636 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008637
Guy Benyei11169dd2012-12-18 14:30:41 +00008638 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8639 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008640 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008641
Guy Benyei11169dd2012-12-18 14:30:41 +00008642 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8643 }
8644 }
8645
8646 llvm_unreachable("Unhandled template name kind!");
8647}
8648
Richard Smith2bb3c342015-08-09 01:05:31 +00008649TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8650 const RecordData &Record,
8651 unsigned &Idx,
8652 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008653 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008654 if (Canonicalize) {
8655 // The caller wants a canonical template argument. Sometimes the AST only
8656 // wants template arguments in canonical form (particularly as the template
8657 // argument lists of template specializations) so ensure we preserve that
8658 // canonical form across serialization.
8659 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8660 return Context.getCanonicalTemplateArgument(Arg);
8661 }
8662
Vedant Kumar48b4f762018-04-14 01:40:48 +00008663 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008664 switch (Kind) {
8665 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00008666 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00008667 case TemplateArgument::Type:
8668 return TemplateArgument(readType(F, Record, Idx));
8669 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008670 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008671 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008672 }
8673 case TemplateArgument::NullPtr:
8674 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8675 case TemplateArgument::Integral: {
8676 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8677 QualType T = readType(F, Record, Idx);
8678 return TemplateArgument(Context, Value, T);
8679 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008680 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008681 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8682 case TemplateArgument::TemplateExpansion: {
8683 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008684 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008685 if (unsigned NumExpansions = Record[Idx++])
8686 NumTemplateExpansions = NumExpansions - 1;
8687 return TemplateArgument(Name, NumTemplateExpansions);
8688 }
8689 case TemplateArgument::Expression:
8690 return TemplateArgument(ReadExpr(F));
8691 case TemplateArgument::Pack: {
8692 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008693 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00008694 for (unsigned I = 0; I != NumArgs; ++I)
8695 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008696 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008697 }
8698 }
8699
8700 llvm_unreachable("Unhandled template argument kind!");
8701}
8702
8703TemplateParameterList *
8704ASTReader::ReadTemplateParameterList(ModuleFile &F,
8705 const RecordData &Record, unsigned &Idx) {
8706 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8707 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8708 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8709
8710 unsigned NumParams = Record[Idx++];
8711 SmallVector<NamedDecl *, 16> Params;
8712 Params.reserve(NumParams);
8713 while (NumParams--)
8714 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8715
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008716 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008717 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8718 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008719 return TemplateParams;
8720}
8721
8722void
8723ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008724ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008725 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008726 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 unsigned NumTemplateArgs = Record[Idx++];
8728 TemplArgs.reserve(NumTemplateArgs);
8729 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008730 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008731}
8732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008733/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008734void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008735 const RecordData &Record, unsigned &Idx) {
8736 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008737 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008738 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008739 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008740 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008741 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008742 }
8743}
8744
8745CXXBaseSpecifier
8746ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8747 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008748 bool isVirtual = static_cast<bool>(Record[Idx++]);
8749 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8750 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8751 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008752 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8753 SourceRange Range = ReadSourceRange(F, Record, Idx);
8754 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008755 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008756 EllipsisLoc);
8757 Result.setInheritConstructors(inheritConstructors);
8758 return Result;
8759}
8760
Richard Smithc2bb8182015-03-24 06:36:48 +00008761CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008762ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8763 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008764 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008765 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008766 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008767 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008768 for (unsigned i = 0; i != NumInitializers; ++i) {
8769 TypeSourceInfo *TInfo = nullptr;
8770 bool IsBaseVirtual = false;
8771 FieldDecl *Member = nullptr;
8772 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008773
Vedant Kumar48b4f762018-04-14 01:40:48 +00008774 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008775 switch (Type) {
8776 case CTOR_INITIALIZER_BASE:
8777 TInfo = GetTypeSourceInfo(F, Record, Idx);
8778 IsBaseVirtual = Record[Idx++];
8779 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008780
Richard Smithc2bb8182015-03-24 06:36:48 +00008781 case CTOR_INITIALIZER_DELEGATING:
8782 TInfo = GetTypeSourceInfo(F, Record, Idx);
8783 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008784
Richard Smithc2bb8182015-03-24 06:36:48 +00008785 case CTOR_INITIALIZER_MEMBER:
8786 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8787 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008788
Richard Smithc2bb8182015-03-24 06:36:48 +00008789 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8790 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8791 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008792 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008793
8794 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8795 Expr *Init = ReadExpr(F);
8796 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8797 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008798
8799 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008800 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008801 BOMInit = new (Context)
8802 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8803 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008804 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008805 BOMInit = new (Context)
8806 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008807 else if (Member)
8808 BOMInit = new (Context)
8809 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8810 Init, RParenLoc);
8811 else
8812 BOMInit = new (Context)
8813 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8814 LParenLoc, Init, RParenLoc);
8815
Richard Smith418ed822016-12-14 19:45:03 +00008816 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008817 unsigned SourceOrder = Record[Idx++];
8818 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008819 }
8820
Richard Smithc2bb8182015-03-24 06:36:48 +00008821 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008822 }
8823
Richard Smithc2bb8182015-03-24 06:36:48 +00008824 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008825}
8826
8827NestedNameSpecifier *
8828ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8829 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008830 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008831 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008832 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008833 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008834 NestedNameSpecifier::SpecifierKind Kind
8835 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008836 switch (Kind) {
8837 case NestedNameSpecifier::Identifier: {
8838 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8839 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8840 break;
8841 }
8842
8843 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008844 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008845 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8846 break;
8847 }
8848
8849 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008850 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008851 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8852 break;
8853 }
8854
8855 case NestedNameSpecifier::TypeSpec:
8856 case NestedNameSpecifier::TypeSpecWithTemplate: {
8857 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8858 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008859 return nullptr;
8860
Guy Benyei11169dd2012-12-18 14:30:41 +00008861 bool Template = Record[Idx++];
8862 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8863 break;
8864 }
8865
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008866 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008867 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8868 // No associated value, and there can't be a prefix.
8869 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008870
8871 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008872 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008873 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8874 break;
8875 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008876 }
8877 Prev = NNS;
8878 }
8879 return NNS;
8880}
8881
8882NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008883ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008884 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008885 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008886 unsigned N = Record[Idx++];
8887 NestedNameSpecifierLocBuilder Builder;
8888 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008889 NestedNameSpecifier::SpecifierKind Kind
8890 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008891 switch (Kind) {
8892 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008893 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008894 SourceRange Range = ReadSourceRange(F, Record, Idx);
8895 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8896 break;
8897 }
8898
8899 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008900 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008901 SourceRange Range = ReadSourceRange(F, Record, Idx);
8902 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8903 break;
8904 }
8905
8906 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008907 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008908 SourceRange Range = ReadSourceRange(F, Record, Idx);
8909 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8910 break;
8911 }
8912
8913 case NestedNameSpecifier::TypeSpec:
8914 case NestedNameSpecifier::TypeSpecWithTemplate: {
8915 bool Template = Record[Idx++];
8916 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8917 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008918 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00008919 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8920
8921 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008922 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008923 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8924 T->getTypeLoc(), ColonColonLoc);
8925 break;
8926 }
8927
8928 case NestedNameSpecifier::Global: {
8929 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8930 Builder.MakeGlobal(Context, ColonColonLoc);
8931 break;
8932 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008933
8934 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008935 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008936 SourceRange Range = ReadSourceRange(F, Record, Idx);
8937 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8938 break;
8939 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008940 }
8941 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008942
Guy Benyei11169dd2012-12-18 14:30:41 +00008943 return Builder.getWithLocInContext(Context);
8944}
8945
8946SourceRange
8947ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8948 unsigned &Idx) {
8949 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8950 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8951 return SourceRange(beg, end);
8952}
8953
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008954/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00008955llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8956 unsigned BitWidth = Record[Idx++];
8957 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8958 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8959 Idx += NumWords;
8960 return Result;
8961}
8962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008963/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00008964llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8965 bool isUnsigned = Record[Idx++];
8966 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8967}
8968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008969/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008970llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8971 const llvm::fltSemantics &Sem,
8972 unsigned &Idx) {
8973 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008974}
8975
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008976// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00008977std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8978 unsigned Len = Record[Idx++];
8979 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8980 Idx += Len;
8981 return Result;
8982}
8983
Richard Smith7ed1bc92014-12-05 22:42:13 +00008984std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8985 unsigned &Idx) {
8986 std::string Filename = ReadString(Record, Idx);
8987 ResolveImportedPath(F, Filename);
8988 return Filename;
8989}
8990
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008991VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008992 unsigned &Idx) {
8993 unsigned Major = Record[Idx++];
8994 unsigned Minor = Record[Idx++];
8995 unsigned Subminor = Record[Idx++];
8996 if (Minor == 0)
8997 return VersionTuple(Major);
8998 if (Subminor == 0)
8999 return VersionTuple(Major, Minor - 1);
9000 return VersionTuple(Major, Minor - 1, Subminor - 1);
9001}
9002
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009003CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009004 const RecordData &Record,
9005 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009006 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009007 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009008}
9009
Richard Smith37a93df2017-02-18 00:32:02 +00009010DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009011 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009012}
9013
Richard Smith37a93df2017-02-18 00:32:02 +00009014DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009015 return Diags.Report(Loc, DiagID);
9016}
9017
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009018/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009019/// preprocessor.
9020IdentifierTable &ASTReader::getIdentifierTable() {
9021 return PP.getIdentifierTable();
9022}
9023
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009024/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009025/// statement.
9026void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009027 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009028 "Already have a SwitchCase with this ID");
9029 (*CurrSwitchCaseStmts)[ID] = SC;
9030}
9031
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009032/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009033SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009034 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009035 return (*CurrSwitchCaseStmts)[ID];
9036}
9037
9038void ASTReader::ClearSwitchCaseIDs() {
9039 CurrSwitchCaseStmts->clear();
9040}
9041
9042void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009043 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009044 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009045 for (SmallVectorImpl<std::pair<BitstreamCursor,
9046 serialization::ModuleFile *>>::iterator
9047 I = CommentsCursors.begin(),
9048 E = CommentsCursors.end();
9049 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009050 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009051 BitstreamCursor &Cursor = I->first;
9052 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009053 SavedStreamPosition SavedPosition(Cursor);
9054
9055 RecordData Record;
9056 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009057 llvm::BitstreamEntry Entry =
9058 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009059
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009060 switch (Entry.Kind) {
9061 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9062 case llvm::BitstreamEntry::Error:
9063 Error("malformed block record in AST file");
9064 return;
9065 case llvm::BitstreamEntry::EndBlock:
9066 goto NextCursor;
9067 case llvm::BitstreamEntry::Record:
9068 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009069 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009070 }
9071
9072 // Read a record.
9073 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009074 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009075 case COMMENTS_RAW_COMMENT: {
9076 unsigned Idx = 0;
9077 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009078 RawComment::CommentKind Kind =
9079 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009080 bool IsTrailingComment = Record[Idx++];
9081 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009082 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009083 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009084 break;
9085 }
9086 }
9087 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009088 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009089 // De-serialized SourceLocations get negative FileIDs for other modules,
9090 // potentially invalidating the original order. Sort it again.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00009091 llvm::sort(Comments.begin(), Comments.end(),
9092 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009093 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009094 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009095}
9096
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009097void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9098 bool IncludeSystem, bool Complain,
9099 llvm::function_ref<void(const serialization::InputFile &IF,
9100 bool isSystem)> Visitor) {
9101 unsigned NumUserInputs = MF.NumUserInputFiles;
9102 unsigned NumInputs = MF.InputFilesLoaded.size();
9103 assert(NumUserInputs <= NumInputs);
9104 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9105 for (unsigned I = 0; I < N; ++I) {
9106 bool IsSystem = I >= NumUserInputs;
9107 InputFile IF = getInputFile(MF, I+1, Complain);
9108 Visitor(IF, IsSystem);
9109 }
9110}
9111
Richard Smithf3f84612017-06-29 02:19:42 +00009112void ASTReader::visitTopLevelModuleMaps(
9113 serialization::ModuleFile &MF,
9114 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9115 unsigned NumInputs = MF.InputFilesLoaded.size();
9116 for (unsigned I = 0; I < NumInputs; ++I) {
9117 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9118 if (IFI.TopLevelModuleMap)
9119 // FIXME: This unnecessarily re-reads the InputFileInfo.
9120 if (auto *FE = getInputFile(MF, I + 1).getFile())
9121 Visitor(FE);
9122 }
9123}
9124
Richard Smithcd45dbc2014-04-19 03:48:30 +00009125std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9126 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009127 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009128 return M->getFullModuleName();
9129
9130 // Otherwise, use the name of the top-level module the decl is within.
9131 if (ModuleFile *M = getOwningModuleFile(D))
9132 return M->ModuleName;
9133
9134 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009135 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009136}
9137
Guy Benyei11169dd2012-12-18 14:30:41 +00009138void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00009139 while (!PendingIdentifierInfos.empty() ||
9140 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009141 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009142 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009143 // If any identifiers with corresponding top-level declarations have
9144 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009145 using TopLevelDeclsMap =
9146 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009147 TopLevelDeclsMap TopLevelDecls;
9148
Guy Benyei11169dd2012-12-18 14:30:41 +00009149 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009150 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009151 SmallVector<uint32_t, 4> DeclIDs =
9152 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009153 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009154
9155 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009156 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009157
Richard Smith851072e2014-05-19 20:59:20 +00009158 // For each decl chain that we wanted to complete while deserializing, mark
9159 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009160 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9161 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9162 }
Richard Smith851072e2014-05-19 20:59:20 +00009163 PendingIncompleteDeclChains.clear();
9164
Guy Benyei11169dd2012-12-18 14:30:41 +00009165 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009166 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9167 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009168 PendingDeclChains.clear();
9169
Douglas Gregor6168bd22013-02-18 15:53:43 +00009170 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009171 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9172 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9173 IdentifierInfo *II = TLD->first;
9174 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9175 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009176 }
9177 }
9178
Guy Benyei11169dd2012-12-18 14:30:41 +00009179 // Load any pending macro definitions.
9180 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009181 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9182 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9183 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9184 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009185 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009186 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009187 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009188 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009189 resolvePendingMacro(II, Info);
9190 }
9191 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009192 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009193 ++IDIdx) {
9194 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009195 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009196 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009197 }
9198 }
9199 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009200
9201 // Wire up the DeclContexts for Decls that we delayed setting until
9202 // recursive loading is completed.
9203 while (!PendingDeclContextInfos.empty()) {
9204 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9205 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009206 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9207 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009208 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9209 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009210
Richard Smithd1c46742014-04-30 02:24:17 +00009211 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009212 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009213 auto Update = PendingUpdateRecords.pop_back_val();
9214 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009215 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009216 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009217 }
Richard Smith8a639892015-01-24 01:07:20 +00009218
9219 // At this point, all update records for loaded decls are in place, so any
9220 // fake class definitions should have become real.
9221 assert(PendingFakeDefinitionData.empty() &&
9222 "faked up a class definition but never saw the real one");
9223
Guy Benyei11169dd2012-12-18 14:30:41 +00009224 // If we deserialized any C++ or Objective-C class definitions, any
9225 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009226 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009227 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009228 for (Decl *D : PendingDefinitions) {
9229 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9230 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009231 // Make sure that the TagType points at the definition.
9232 const_cast<TagType*>(TagT)->decl = TD;
9233 }
Richard Smith8ce51082015-03-11 01:44:51 +00009234
Vedant Kumar48b4f762018-04-14 01:40:48 +00009235 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009236 for (auto *R = getMostRecentExistingDecl(RD); R;
9237 R = R->getPreviousDecl()) {
9238 assert((R == D) ==
9239 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009240 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009241 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009242 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009243 }
9244
9245 continue;
9246 }
Richard Smith8ce51082015-03-11 01:44:51 +00009247
Vedant Kumar48b4f762018-04-14 01:40:48 +00009248 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009249 // Make sure that the ObjCInterfaceType points at the definition.
9250 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9251 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009252
9253 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9254 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9255
Guy Benyei11169dd2012-12-18 14:30:41 +00009256 continue;
9257 }
Richard Smith8ce51082015-03-11 01:44:51 +00009258
Vedant Kumar48b4f762018-04-14 01:40:48 +00009259 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009260 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9261 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9262
Guy Benyei11169dd2012-12-18 14:30:41 +00009263 continue;
9264 }
Richard Smith8ce51082015-03-11 01:44:51 +00009265
Vedant Kumar48b4f762018-04-14 01:40:48 +00009266 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009267 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9268 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009269 }
9270 PendingDefinitions.clear();
9271
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009272 // Load the bodies of any functions or methods we've encountered. We do
9273 // this now (delayed) so that we can be sure that the declaration chains
9274 // have been fully wired up (hasBody relies on this).
9275 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009276 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9277 PBEnd = PendingBodies.end();
9278 PB != PBEnd; ++PB) {
9279 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009280 // FIXME: Check for =delete/=default?
9281 // FIXME: Complain about ODR violations here?
9282 const FunctionDecl *Defn = nullptr;
9283 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009284 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009285 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009286 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009287 mergeDefinitionVisibility(NonConstDefn, FD);
9288
9289 if (!FD->isLateTemplateParsed() &&
9290 !NonConstDefn->isLateTemplateParsed() &&
9291 FD->getODRHash() != NonConstDefn->getODRHash()) {
9292 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9293 }
9294 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009295 continue;
9296 }
9297
Vedant Kumar48b4f762018-04-14 01:40:48 +00009298 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009299 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009300 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009301 }
9302 PendingBodies.clear();
9303
Richard Smith42413142015-05-15 20:05:43 +00009304 // Do some cleanup.
9305 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9306 getContext().deduplicateMergedDefinitonsFor(ND);
9307 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009308}
9309
9310void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009311 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9312 PendingFunctionOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009313 return;
9314
Richard Smitha0ce9c42014-07-29 23:23:27 +00009315 // Trigger the import of the full definition of each class that had any
9316 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009317 // These updates may in turn find and diagnose some ODR failures, so take
9318 // ownership of the set first.
9319 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9320 PendingOdrMergeFailures.clear();
9321 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009322 Merge.first->buildLookup();
9323 Merge.first->decls_begin();
9324 Merge.first->bases_begin();
9325 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009326 for (auto &RecordPair : Merge.second) {
9327 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009328 RD->decls_begin();
9329 RD->bases_begin();
9330 RD->vbases_begin();
9331 }
9332 }
9333
Richard Trieue6caa262017-12-23 00:41:01 +00009334 // Trigger the import of functions.
9335 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9336 PendingFunctionOdrMergeFailures.clear();
9337 for (auto &Merge : FunctionOdrMergeFailures) {
9338 Merge.first->buildLookup();
9339 Merge.first->decls_begin();
9340 Merge.first->getBody();
9341 for (auto &FD : Merge.second) {
9342 FD->buildLookup();
9343 FD->decls_begin();
9344 FD->getBody();
9345 }
9346 }
9347
Richard Smitha0ce9c42014-07-29 23:23:27 +00009348 // For each declaration from a merged context, check that the canonical
9349 // definition of that context also contains a declaration of the same
9350 // entity.
9351 //
9352 // Caution: this loop does things that might invalidate iterators into
9353 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9354 while (!PendingOdrMergeChecks.empty()) {
9355 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9356
9357 // FIXME: Skip over implicit declarations for now. This matters for things
9358 // like implicitly-declared special member functions. This isn't entirely
9359 // correct; we can end up with multiple unmerged declarations of the same
9360 // implicit entity.
9361 if (D->isImplicit())
9362 continue;
9363
9364 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009365
9366 bool Found = false;
9367 const Decl *DCanon = D->getCanonicalDecl();
9368
Richard Smith01bdb7a2014-08-28 05:44:07 +00009369 for (auto RI : D->redecls()) {
9370 if (RI->getLexicalDeclContext() == CanonDef) {
9371 Found = true;
9372 break;
9373 }
9374 }
9375 if (Found)
9376 continue;
9377
Richard Smith0f4e2c42015-08-06 04:23:48 +00009378 // Quick check failed, time to do the slow thing. Note, we can't just
9379 // look up the name of D in CanonDef here, because the member that is
9380 // in CanonDef might not be found by name lookup (it might have been
9381 // replaced by a more recent declaration in the lookup table), and we
9382 // can't necessarily find it in the redeclaration chain because it might
9383 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009384 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009385 for (auto *CanonMember : CanonDef->decls()) {
9386 if (CanonMember->getCanonicalDecl() == DCanon) {
9387 // This can happen if the declaration is merely mergeable and not
9388 // actually redeclarable (we looked for redeclarations earlier).
9389 //
9390 // FIXME: We should be able to detect this more efficiently, without
9391 // pulling in all of the members of CanonDef.
9392 Found = true;
9393 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009394 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009395 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9396 if (ND->getDeclName() == D->getDeclName())
9397 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009398 }
9399
9400 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009401 // The AST doesn't like TagDecls becoming invalid after they've been
9402 // completed. We only really need to mark FieldDecls as invalid here.
9403 if (!isa<TagDecl>(D))
9404 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009405
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009406 // Ensure we don't accidentally recursively enter deserialization while
9407 // we're producing our diagnostic.
9408 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009409
9410 std::string CanonDefModule =
9411 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9412 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9413 << D << getOwningModuleNameForDiagnostic(D)
9414 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9415
9416 if (Candidates.empty())
9417 Diag(cast<Decl>(CanonDef)->getLocation(),
9418 diag::note_module_odr_violation_no_possible_decls) << D;
9419 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009420 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9421 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009422 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009423 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009424 }
9425
9426 DiagnosedOdrMergeFailures.insert(CanonDef);
9427 }
9428 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009429
Richard Trieue6caa262017-12-23 00:41:01 +00009430 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009431 return;
9432
9433 // Ensure we don't accidentally recursively enter deserialization while
9434 // we're producing our diagnostics.
9435 Deserializing RecursionGuard(this);
9436
Richard Trieue6caa262017-12-23 00:41:01 +00009437 // Common code for hashing helpers.
9438 ODRHash Hash;
9439 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9440 Hash.clear();
9441 Hash.AddQualType(Ty);
9442 return Hash.CalculateHash();
9443 };
9444
9445 auto ComputeODRHash = [&Hash](const Stmt *S) {
9446 assert(S);
9447 Hash.clear();
9448 Hash.AddStmt(S);
9449 return Hash.CalculateHash();
9450 };
9451
9452 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9453 assert(D);
9454 Hash.clear();
9455 Hash.AddSubDecl(D);
9456 return Hash.CalculateHash();
9457 };
9458
Richard Trieu7282d322018-04-25 00:31:15 +00009459 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9460 Hash.clear();
9461 Hash.AddTemplateArgument(TA);
9462 return Hash.CalculateHash();
9463 };
9464
Richard Trieu9359e8f2018-05-30 01:12:26 +00009465 auto ComputeTemplateParameterListODRHash =
9466 [&Hash](const TemplateParameterList *TPL) {
9467 assert(TPL);
9468 Hash.clear();
9469 Hash.AddTemplateParameterList(TPL);
9470 return Hash.CalculateHash();
9471 };
9472
Richard Smithcd45dbc2014-04-19 03:48:30 +00009473 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009474 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009475 // If we've already pointed out a specific problem with this class, don't
9476 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009477 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009478 continue;
9479
9480 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009481 CXXRecordDecl *FirstRecord = Merge.first;
9482 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009483 for (auto &RecordPair : Merge.second) {
9484 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009485 // Multiple different declarations got merged together; tell the user
9486 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009487 if (FirstRecord == SecondRecord)
9488 continue;
9489
9490 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009491
9492 auto *FirstDD = FirstRecord->DefinitionData;
9493 auto *SecondDD = RecordPair.second;
9494
9495 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9496
9497 // Diagnostics from DefinitionData are emitted here.
9498 if (FirstDD != SecondDD) {
9499 enum ODRDefinitionDataDifference {
9500 NumBases,
9501 NumVBases,
9502 BaseType,
9503 BaseVirtual,
9504 BaseAccess,
9505 };
9506 auto ODRDiagError = [FirstRecord, &FirstModule,
9507 this](SourceLocation Loc, SourceRange Range,
9508 ODRDefinitionDataDifference DiffType) {
9509 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9510 << FirstRecord << FirstModule.empty() << FirstModule << Range
9511 << DiffType;
9512 };
9513 auto ODRDiagNote = [&SecondModule,
9514 this](SourceLocation Loc, SourceRange Range,
9515 ODRDefinitionDataDifference DiffType) {
9516 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9517 << SecondModule << Range << DiffType;
9518 };
9519
Richard Trieue13eabe2017-09-30 02:19:17 +00009520 unsigned FirstNumBases = FirstDD->NumBases;
9521 unsigned FirstNumVBases = FirstDD->NumVBases;
9522 unsigned SecondNumBases = SecondDD->NumBases;
9523 unsigned SecondNumVBases = SecondDD->NumVBases;
9524
9525 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9526 unsigned NumBases = DD->NumBases;
9527 if (NumBases == 0) return SourceRange();
9528 auto bases = DD->bases();
9529 return SourceRange(bases[0].getLocStart(),
9530 bases[NumBases - 1].getLocEnd());
9531 };
9532
9533 if (FirstNumBases != SecondNumBases) {
9534 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9535 NumBases)
9536 << FirstNumBases;
9537 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9538 NumBases)
9539 << SecondNumBases;
9540 Diagnosed = true;
9541 break;
9542 }
9543
9544 if (FirstNumVBases != SecondNumVBases) {
9545 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9546 NumVBases)
9547 << FirstNumVBases;
9548 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9549 NumVBases)
9550 << SecondNumVBases;
9551 Diagnosed = true;
9552 break;
9553 }
9554
9555 auto FirstBases = FirstDD->bases();
9556 auto SecondBases = SecondDD->bases();
9557 unsigned i = 0;
9558 for (i = 0; i < FirstNumBases; ++i) {
9559 auto FirstBase = FirstBases[i];
9560 auto SecondBase = SecondBases[i];
9561 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9562 ComputeQualTypeODRHash(SecondBase.getType())) {
9563 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9564 BaseType)
9565 << (i + 1) << FirstBase.getType();
9566 ODRDiagNote(SecondRecord->getLocation(),
9567 SecondBase.getSourceRange(), BaseType)
9568 << (i + 1) << SecondBase.getType();
9569 break;
9570 }
9571
9572 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9573 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9574 BaseVirtual)
9575 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9576 ODRDiagNote(SecondRecord->getLocation(),
9577 SecondBase.getSourceRange(), BaseVirtual)
9578 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9579 break;
9580 }
9581
9582 if (FirstBase.getAccessSpecifierAsWritten() !=
9583 SecondBase.getAccessSpecifierAsWritten()) {
9584 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9585 BaseAccess)
9586 << (i + 1) << FirstBase.getType()
9587 << (int)FirstBase.getAccessSpecifierAsWritten();
9588 ODRDiagNote(SecondRecord->getLocation(),
9589 SecondBase.getSourceRange(), BaseAccess)
9590 << (i + 1) << SecondBase.getType()
9591 << (int)SecondBase.getAccessSpecifierAsWritten();
9592 break;
9593 }
9594 }
9595
9596 if (i != FirstNumBases) {
9597 Diagnosed = true;
9598 break;
9599 }
9600 }
9601
Richard Trieue7f7ed22017-02-22 01:11:25 +00009602 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009603
9604 const ClassTemplateDecl *FirstTemplate =
9605 FirstRecord->getDescribedClassTemplate();
9606 const ClassTemplateDecl *SecondTemplate =
9607 SecondRecord->getDescribedClassTemplate();
9608
9609 assert(!FirstTemplate == !SecondTemplate &&
9610 "Both pointers should be null or non-null");
9611
9612 enum ODRTemplateDifference {
9613 ParamEmptyName,
9614 ParamName,
9615 ParamSingleDefaultArgument,
9616 ParamDifferentDefaultArgument,
9617 };
9618
9619 if (FirstTemplate && SecondTemplate) {
9620 DeclHashes FirstTemplateHashes;
9621 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009622
9623 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009624 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9625 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009626 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009627 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009628 }
9629 };
9630
9631 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9632 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9633
9634 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9635 "Number of template parameters should be equal.");
9636
9637 auto FirstIt = FirstTemplateHashes.begin();
9638 auto FirstEnd = FirstTemplateHashes.end();
9639 auto SecondIt = SecondTemplateHashes.begin();
9640 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9641 if (FirstIt->second == SecondIt->second)
9642 continue;
9643
9644 auto ODRDiagError = [FirstRecord, &FirstModule,
9645 this](SourceLocation Loc, SourceRange Range,
9646 ODRTemplateDifference DiffType) {
9647 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9648 << FirstRecord << FirstModule.empty() << FirstModule << Range
9649 << DiffType;
9650 };
9651 auto ODRDiagNote = [&SecondModule,
9652 this](SourceLocation Loc, SourceRange Range,
9653 ODRTemplateDifference DiffType) {
9654 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9655 << SecondModule << Range << DiffType;
9656 };
9657
Vedant Kumar48b4f762018-04-14 01:40:48 +00009658 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9659 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009660
9661 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9662 "Parameter Decl's should be the same kind.");
9663
9664 DeclarationName FirstName = FirstDecl->getDeclName();
9665 DeclarationName SecondName = SecondDecl->getDeclName();
9666
9667 if (FirstName != SecondName) {
9668 const bool FirstNameEmpty =
9669 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9670 const bool SecondNameEmpty =
9671 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9672 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9673 "Both template parameters cannot be unnamed.");
9674 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9675 FirstNameEmpty ? ParamEmptyName : ParamName)
9676 << FirstName;
9677 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9678 SecondNameEmpty ? ParamEmptyName : ParamName)
9679 << SecondName;
9680 break;
9681 }
9682
9683 switch (FirstDecl->getKind()) {
9684 default:
9685 llvm_unreachable("Invalid template parameter type.");
9686 case Decl::TemplateTypeParm: {
9687 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9688 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9689 const bool HasFirstDefaultArgument =
9690 FirstParam->hasDefaultArgument() &&
9691 !FirstParam->defaultArgumentWasInherited();
9692 const bool HasSecondDefaultArgument =
9693 SecondParam->hasDefaultArgument() &&
9694 !SecondParam->defaultArgumentWasInherited();
9695
9696 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9697 ODRDiagError(FirstDecl->getLocation(),
9698 FirstDecl->getSourceRange(),
9699 ParamSingleDefaultArgument)
9700 << HasFirstDefaultArgument;
9701 ODRDiagNote(SecondDecl->getLocation(),
9702 SecondDecl->getSourceRange(),
9703 ParamSingleDefaultArgument)
9704 << HasSecondDefaultArgument;
9705 break;
9706 }
9707
9708 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9709 "Expecting default arguments.");
9710
9711 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9712 ParamDifferentDefaultArgument);
9713 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9714 ParamDifferentDefaultArgument);
9715
9716 break;
9717 }
9718 case Decl::NonTypeTemplateParm: {
9719 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9720 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9721 const bool HasFirstDefaultArgument =
9722 FirstParam->hasDefaultArgument() &&
9723 !FirstParam->defaultArgumentWasInherited();
9724 const bool HasSecondDefaultArgument =
9725 SecondParam->hasDefaultArgument() &&
9726 !SecondParam->defaultArgumentWasInherited();
9727
9728 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9729 ODRDiagError(FirstDecl->getLocation(),
9730 FirstDecl->getSourceRange(),
9731 ParamSingleDefaultArgument)
9732 << HasFirstDefaultArgument;
9733 ODRDiagNote(SecondDecl->getLocation(),
9734 SecondDecl->getSourceRange(),
9735 ParamSingleDefaultArgument)
9736 << HasSecondDefaultArgument;
9737 break;
9738 }
9739
9740 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9741 "Expecting default arguments.");
9742
9743 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9744 ParamDifferentDefaultArgument);
9745 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9746 ParamDifferentDefaultArgument);
9747
9748 break;
9749 }
9750 case Decl::TemplateTemplateParm: {
9751 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9752 const auto *SecondParam =
9753 cast<TemplateTemplateParmDecl>(SecondDecl);
9754 const bool HasFirstDefaultArgument =
9755 FirstParam->hasDefaultArgument() &&
9756 !FirstParam->defaultArgumentWasInherited();
9757 const bool HasSecondDefaultArgument =
9758 SecondParam->hasDefaultArgument() &&
9759 !SecondParam->defaultArgumentWasInherited();
9760
9761 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9762 ODRDiagError(FirstDecl->getLocation(),
9763 FirstDecl->getSourceRange(),
9764 ParamSingleDefaultArgument)
9765 << HasFirstDefaultArgument;
9766 ODRDiagNote(SecondDecl->getLocation(),
9767 SecondDecl->getSourceRange(),
9768 ParamSingleDefaultArgument)
9769 << HasSecondDefaultArgument;
9770 break;
9771 }
9772
9773 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9774 "Expecting default arguments.");
9775
9776 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9777 ParamDifferentDefaultArgument);
9778 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9779 ParamDifferentDefaultArgument);
9780
9781 break;
9782 }
9783 }
9784
9785 break;
9786 }
9787
9788 if (FirstIt != FirstEnd) {
9789 Diagnosed = true;
9790 break;
9791 }
9792 }
9793
Richard Trieue7f7ed22017-02-22 01:11:25 +00009794 DeclHashes FirstHashes;
9795 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009796
Richard Trieue6caa262017-12-23 00:41:01 +00009797 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9798 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009799 for (auto *D : Record->decls()) {
9800 // Due to decl merging, the first CXXRecordDecl is the parent of
9801 // Decls in both records.
9802 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9803 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009804 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009805 }
9806 };
9807 PopulateHashes(FirstHashes, FirstRecord);
9808 PopulateHashes(SecondHashes, SecondRecord);
9809
9810 // Used with err_module_odr_violation_mismatch_decl and
9811 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009812 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009813 enum {
9814 EndOfClass,
9815 PublicSpecifer,
9816 PrivateSpecifer,
9817 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009818 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009819 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009820 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009821 TypeAlias,
9822 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009823 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009824 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009825 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009826 Other
9827 } FirstDiffType = Other,
9828 SecondDiffType = Other;
9829
9830 auto DifferenceSelector = [](Decl *D) {
9831 assert(D && "valid Decl required");
9832 switch (D->getKind()) {
9833 default:
9834 return Other;
9835 case Decl::AccessSpec:
9836 switch (D->getAccess()) {
9837 case AS_public:
9838 return PublicSpecifer;
9839 case AS_private:
9840 return PrivateSpecifer;
9841 case AS_protected:
9842 return ProtectedSpecifer;
9843 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009844 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009845 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009846 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009847 case Decl::StaticAssert:
9848 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009849 case Decl::Field:
9850 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009851 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009852 case Decl::CXXConstructor:
9853 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009854 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009855 case Decl::TypeAlias:
9856 return TypeAlias;
9857 case Decl::Typedef:
9858 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009859 case Decl::Var:
9860 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009861 case Decl::Friend:
9862 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +00009863 case Decl::FunctionTemplate:
9864 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009865 }
9866 };
9867
9868 Decl *FirstDecl = nullptr;
9869 Decl *SecondDecl = nullptr;
9870 auto FirstIt = FirstHashes.begin();
9871 auto SecondIt = SecondHashes.begin();
9872
9873 // If there is a diagnoseable difference, FirstDiffType and
9874 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9875 // filled in if not EndOfClass.
9876 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009877 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9878 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009879 ++FirstIt;
9880 ++SecondIt;
9881 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009882 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009883
Richard Trieue7f7ed22017-02-22 01:11:25 +00009884 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9885 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9886
9887 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9888 SecondDiffType =
9889 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9890
9891 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009892 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009893
9894 if (FirstDiffType == Other || SecondDiffType == Other) {
9895 // Reaching this point means an unexpected Decl was encountered
9896 // or no difference was detected. This causes a generic error
9897 // message to be emitted.
9898 Diag(FirstRecord->getLocation(),
9899 diag::err_module_odr_violation_different_definitions)
9900 << FirstRecord << FirstModule.empty() << FirstModule;
9901
Richard Trieuca48d362017-06-21 01:43:13 +00009902 if (FirstDecl) {
9903 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9904 << FirstRecord << FirstDecl->getSourceRange();
9905 }
9906
Richard Trieue7f7ed22017-02-22 01:11:25 +00009907 Diag(SecondRecord->getLocation(),
9908 diag::note_module_odr_violation_different_definitions)
9909 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009910
9911 if (SecondDecl) {
9912 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9913 << SecondDecl->getSourceRange();
9914 }
9915
Richard Trieue7f7ed22017-02-22 01:11:25 +00009916 Diagnosed = true;
9917 break;
9918 }
9919
9920 if (FirstDiffType != SecondDiffType) {
9921 SourceLocation FirstLoc;
9922 SourceRange FirstRange;
9923 if (FirstDiffType == EndOfClass) {
9924 FirstLoc = FirstRecord->getBraceRange().getEnd();
9925 } else {
9926 FirstLoc = FirstIt->first->getLocation();
9927 FirstRange = FirstIt->first->getSourceRange();
9928 }
9929 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9930 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9931 << FirstDiffType;
9932
9933 SourceLocation SecondLoc;
9934 SourceRange SecondRange;
9935 if (SecondDiffType == EndOfClass) {
9936 SecondLoc = SecondRecord->getBraceRange().getEnd();
9937 } else {
9938 SecondLoc = SecondDecl->getLocation();
9939 SecondRange = SecondDecl->getSourceRange();
9940 }
9941 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9942 << SecondModule << SecondRange << SecondDiffType;
9943 Diagnosed = true;
9944 break;
9945 }
9946
Richard Trieu639d7b62017-02-22 22:22:42 +00009947 assert(FirstDiffType == SecondDiffType);
9948
9949 // Used with err_module_odr_violation_mismatch_decl_diff and
9950 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +00009951 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +00009952 StaticAssertCondition,
9953 StaticAssertMessage,
9954 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009955 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009956 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009957 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009958 FieldDifferentWidthBitField,
9959 FieldSingleMutable,
9960 FieldSingleInitializer,
9961 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009962 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009963 MethodDeleted,
9964 MethodVirtual,
9965 MethodStatic,
9966 MethodVolatile,
9967 MethodConst,
9968 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009969 MethodNumberParameters,
9970 MethodParameterType,
9971 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009972 MethodParameterSingleDefaultArgument,
9973 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +00009974 MethodNoTemplateArguments,
9975 MethodDifferentNumberTemplateArguments,
9976 MethodDifferentTemplateArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009977 TypedefName,
9978 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009979 VarName,
9980 VarType,
9981 VarSingleInitializer,
9982 VarDifferentInitializer,
9983 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009984 FriendTypeFunction,
9985 FriendType,
9986 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009987 FunctionTemplateDifferentNumberParameters,
9988 FunctionTemplateParameterDifferentKind,
9989 FunctionTemplateParameterName,
9990 FunctionTemplateParameterSingleDefaultArgument,
9991 FunctionTemplateParameterDifferentDefaultArgument,
9992 FunctionTemplateParameterDifferentType,
9993 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +00009994 };
9995
9996 // These lambdas have the common portions of the ODR diagnostics. This
9997 // has the same return as Diag(), so addition parameters can be passed
9998 // in with operator<<
9999 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10000 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10001 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10002 << FirstRecord << FirstModule.empty() << FirstModule << Range
10003 << DiffType;
10004 };
10005 auto ODRDiagNote = [&SecondModule, this](
10006 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10007 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10008 << SecondModule << Range << DiffType;
10009 };
10010
Richard Trieu639d7b62017-02-22 22:22:42 +000010011 switch (FirstDiffType) {
10012 case Other:
10013 case EndOfClass:
10014 case PublicSpecifer:
10015 case PrivateSpecifer:
10016 case ProtectedSpecifer:
10017 llvm_unreachable("Invalid diff type");
10018
10019 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010020 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10021 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010022
10023 Expr *FirstExpr = FirstSA->getAssertExpr();
10024 Expr *SecondExpr = SecondSA->getAssertExpr();
10025 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10026 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10027 if (FirstODRHash != SecondODRHash) {
10028 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
10029 StaticAssertCondition);
10030 ODRDiagNote(SecondExpr->getLocStart(),
10031 SecondExpr->getSourceRange(), StaticAssertCondition);
10032 Diagnosed = true;
10033 break;
10034 }
10035
10036 StringLiteral *FirstStr = FirstSA->getMessage();
10037 StringLiteral *SecondStr = SecondSA->getMessage();
10038 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10039 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10040 SourceLocation FirstLoc, SecondLoc;
10041 SourceRange FirstRange, SecondRange;
10042 if (FirstStr) {
10043 FirstLoc = FirstStr->getLocStart();
10044 FirstRange = FirstStr->getSourceRange();
10045 } else {
10046 FirstLoc = FirstSA->getLocStart();
10047 FirstRange = FirstSA->getSourceRange();
10048 }
10049 if (SecondStr) {
10050 SecondLoc = SecondStr->getLocStart();
10051 SecondRange = SecondStr->getSourceRange();
10052 } else {
10053 SecondLoc = SecondSA->getLocStart();
10054 SecondRange = SecondSA->getSourceRange();
10055 }
10056 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10057 << (FirstStr == nullptr);
10058 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10059 << (SecondStr == nullptr);
10060 Diagnosed = true;
10061 break;
10062 }
10063
10064 if (FirstStr && SecondStr &&
10065 FirstStr->getString() != SecondStr->getString()) {
10066 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
10067 StaticAssertMessage);
10068 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
10069 StaticAssertMessage);
10070 Diagnosed = true;
10071 break;
10072 }
10073 break;
10074 }
Richard Trieud0786092017-02-23 00:23:01 +000010075 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010076 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10077 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010078 IdentifierInfo *FirstII = FirstField->getIdentifier();
10079 IdentifierInfo *SecondII = SecondField->getIdentifier();
10080 if (FirstII->getName() != SecondII->getName()) {
10081 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10082 FieldName)
10083 << FirstII;
10084 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10085 FieldName)
10086 << SecondII;
10087
10088 Diagnosed = true;
10089 break;
10090 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010091
Richard Smithdbafb6c2017-06-29 23:23:46 +000010092 assert(getContext().hasSameType(FirstField->getType(),
10093 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010094
10095 QualType FirstType = FirstField->getType();
10096 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010097 if (ComputeQualTypeODRHash(FirstType) !=
10098 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010099 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10100 FieldTypeName)
10101 << FirstII << FirstType;
10102 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10103 FieldTypeName)
10104 << SecondII << SecondType;
10105
10106 Diagnosed = true;
10107 break;
10108 }
10109
Richard Trieu93772fc2017-02-24 20:59:28 +000010110 const bool IsFirstBitField = FirstField->isBitField();
10111 const bool IsSecondBitField = SecondField->isBitField();
10112 if (IsFirstBitField != IsSecondBitField) {
10113 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10114 FieldSingleBitField)
10115 << FirstII << IsFirstBitField;
10116 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10117 FieldSingleBitField)
10118 << SecondII << IsSecondBitField;
10119 Diagnosed = true;
10120 break;
10121 }
10122
10123 if (IsFirstBitField && IsSecondBitField) {
10124 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10125 FieldDifferentWidthBitField)
10126 << FirstII << FirstField->getBitWidth()->getSourceRange();
10127 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10128 FieldDifferentWidthBitField)
10129 << SecondII << SecondField->getBitWidth()->getSourceRange();
10130 Diagnosed = true;
10131 break;
10132 }
10133
Richard Trieu8d543e22017-02-24 23:35:37 +000010134 const bool IsFirstMutable = FirstField->isMutable();
10135 const bool IsSecondMutable = SecondField->isMutable();
10136 if (IsFirstMutable != IsSecondMutable) {
10137 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10138 FieldSingleMutable)
10139 << FirstII << IsFirstMutable;
10140 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10141 FieldSingleMutable)
10142 << SecondII << IsSecondMutable;
10143 Diagnosed = true;
10144 break;
10145 }
10146
10147 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10148 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10149 if ((!FirstInitializer && SecondInitializer) ||
10150 (FirstInitializer && !SecondInitializer)) {
10151 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10152 FieldSingleInitializer)
10153 << FirstII << (FirstInitializer != nullptr);
10154 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10155 FieldSingleInitializer)
10156 << SecondII << (SecondInitializer != nullptr);
10157 Diagnosed = true;
10158 break;
10159 }
10160
10161 if (FirstInitializer && SecondInitializer) {
10162 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10163 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10164 if (FirstInitHash != SecondInitHash) {
10165 ODRDiagError(FirstField->getLocation(),
10166 FirstField->getSourceRange(),
10167 FieldDifferentInitializers)
10168 << FirstII << FirstInitializer->getSourceRange();
10169 ODRDiagNote(SecondField->getLocation(),
10170 SecondField->getSourceRange(),
10171 FieldDifferentInitializers)
10172 << SecondII << SecondInitializer->getSourceRange();
10173 Diagnosed = true;
10174 break;
10175 }
10176 }
10177
Richard Trieud0786092017-02-23 00:23:01 +000010178 break;
10179 }
Richard Trieu48143742017-02-28 21:24:38 +000010180 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010181 enum {
10182 DiagMethod,
10183 DiagConstructor,
10184 DiagDestructor,
10185 } FirstMethodType,
10186 SecondMethodType;
10187 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10188 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10189 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10190 return DiagMethod;
10191 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010192 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10193 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010194 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10195 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010196 auto FirstName = FirstMethod->getDeclName();
10197 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010198 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010199 ODRDiagError(FirstMethod->getLocation(),
10200 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010201 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010202 ODRDiagNote(SecondMethod->getLocation(),
10203 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010204 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010205
10206 Diagnosed = true;
10207 break;
10208 }
10209
Richard Trieu583e2c12017-03-04 00:08:58 +000010210 const bool FirstDeleted = FirstMethod->isDeleted();
10211 const bool SecondDeleted = SecondMethod->isDeleted();
10212 if (FirstDeleted != SecondDeleted) {
10213 ODRDiagError(FirstMethod->getLocation(),
10214 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010215 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010216
10217 ODRDiagNote(SecondMethod->getLocation(),
10218 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010219 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010220 Diagnosed = true;
10221 break;
10222 }
10223
10224 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10225 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10226 const bool FirstPure = FirstMethod->isPure();
10227 const bool SecondPure = SecondMethod->isPure();
10228 if ((FirstVirtual || SecondVirtual) &&
10229 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10230 ODRDiagError(FirstMethod->getLocation(),
10231 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010232 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010233 ODRDiagNote(SecondMethod->getLocation(),
10234 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010235 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010236 Diagnosed = true;
10237 break;
10238 }
10239
10240 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10241 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10242 // class needs to be checked instead.
10243 const auto FirstStorage = FirstMethod->getStorageClass();
10244 const auto SecondStorage = SecondMethod->getStorageClass();
10245 const bool FirstStatic = FirstStorage == SC_Static;
10246 const bool SecondStatic = SecondStorage == SC_Static;
10247 if (FirstStatic != SecondStatic) {
10248 ODRDiagError(FirstMethod->getLocation(),
10249 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010250 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010251 ODRDiagNote(SecondMethod->getLocation(),
10252 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010253 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010254 Diagnosed = true;
10255 break;
10256 }
10257
10258 const bool FirstVolatile = FirstMethod->isVolatile();
10259 const bool SecondVolatile = SecondMethod->isVolatile();
10260 if (FirstVolatile != SecondVolatile) {
10261 ODRDiagError(FirstMethod->getLocation(),
10262 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010263 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010264 ODRDiagNote(SecondMethod->getLocation(),
10265 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010266 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010267 Diagnosed = true;
10268 break;
10269 }
10270
10271 const bool FirstConst = FirstMethod->isConst();
10272 const bool SecondConst = SecondMethod->isConst();
10273 if (FirstConst != SecondConst) {
10274 ODRDiagError(FirstMethod->getLocation(),
10275 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010276 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010277 ODRDiagNote(SecondMethod->getLocation(),
10278 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010279 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010280 Diagnosed = true;
10281 break;
10282 }
10283
10284 const bool FirstInline = FirstMethod->isInlineSpecified();
10285 const bool SecondInline = SecondMethod->isInlineSpecified();
10286 if (FirstInline != SecondInline) {
10287 ODRDiagError(FirstMethod->getLocation(),
10288 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010289 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010290 ODRDiagNote(SecondMethod->getLocation(),
10291 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010292 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010293 Diagnosed = true;
10294 break;
10295 }
10296
Richard Trieu02552272017-05-02 23:58:52 +000010297 const unsigned FirstNumParameters = FirstMethod->param_size();
10298 const unsigned SecondNumParameters = SecondMethod->param_size();
10299 if (FirstNumParameters != SecondNumParameters) {
10300 ODRDiagError(FirstMethod->getLocation(),
10301 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010302 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010303 ODRDiagNote(SecondMethod->getLocation(),
10304 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010305 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010306 Diagnosed = true;
10307 break;
10308 }
10309
10310 // Need this status boolean to know when break out of the switch.
10311 bool ParameterMismatch = false;
10312 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10313 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10314 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10315
10316 QualType FirstParamType = FirstParam->getType();
10317 QualType SecondParamType = SecondParam->getType();
10318 if (FirstParamType != SecondParamType &&
10319 ComputeQualTypeODRHash(FirstParamType) !=
10320 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010321 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010322 FirstParamType->getAs<DecayedType>()) {
10323 ODRDiagError(FirstMethod->getLocation(),
10324 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010325 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10326 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010327 } else {
10328 ODRDiagError(FirstMethod->getLocation(),
10329 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010330 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10331 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010332 }
10333
Vedant Kumar48b4f762018-04-14 01:40:48 +000010334 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010335 SecondParamType->getAs<DecayedType>()) {
10336 ODRDiagNote(SecondMethod->getLocation(),
10337 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010338 << SecondMethodType << SecondName << (I + 1)
10339 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010340 << ParamDecayedType->getOriginalType();
10341 } else {
10342 ODRDiagNote(SecondMethod->getLocation(),
10343 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010344 << SecondMethodType << SecondName << (I + 1)
10345 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010346 }
10347 ParameterMismatch = true;
10348 break;
10349 }
10350
10351 DeclarationName FirstParamName = FirstParam->getDeclName();
10352 DeclarationName SecondParamName = SecondParam->getDeclName();
10353 if (FirstParamName != SecondParamName) {
10354 ODRDiagError(FirstMethod->getLocation(),
10355 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010356 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010357 ODRDiagNote(SecondMethod->getLocation(),
10358 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010359 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010360 ParameterMismatch = true;
10361 break;
10362 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010363
10364 const Expr *FirstInit = FirstParam->getInit();
10365 const Expr *SecondInit = SecondParam->getInit();
10366 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10367 ODRDiagError(FirstMethod->getLocation(),
10368 FirstMethod->getSourceRange(),
10369 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010370 << FirstMethodType << FirstName << (I + 1)
10371 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010372 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10373 ODRDiagNote(SecondMethod->getLocation(),
10374 SecondMethod->getSourceRange(),
10375 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010376 << SecondMethodType << SecondName << (I + 1)
10377 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010378 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10379 ParameterMismatch = true;
10380 break;
10381 }
10382
10383 if (FirstInit && SecondInit &&
10384 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10385 ODRDiagError(FirstMethod->getLocation(),
10386 FirstMethod->getSourceRange(),
10387 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010388 << FirstMethodType << FirstName << (I + 1)
10389 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010390 ODRDiagNote(SecondMethod->getLocation(),
10391 SecondMethod->getSourceRange(),
10392 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010393 << SecondMethodType << SecondName << (I + 1)
10394 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010395 ParameterMismatch = true;
10396 break;
10397
10398 }
Richard Trieu02552272017-05-02 23:58:52 +000010399 }
10400
10401 if (ParameterMismatch) {
10402 Diagnosed = true;
10403 break;
10404 }
10405
Richard Trieu7282d322018-04-25 00:31:15 +000010406 const auto *FirstTemplateArgs =
10407 FirstMethod->getTemplateSpecializationArgs();
10408 const auto *SecondTemplateArgs =
10409 SecondMethod->getTemplateSpecializationArgs();
10410
10411 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10412 (!FirstTemplateArgs && SecondTemplateArgs)) {
10413 ODRDiagError(FirstMethod->getLocation(),
10414 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10415 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10416 ODRDiagNote(SecondMethod->getLocation(),
10417 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10418 << SecondMethodType << SecondName
10419 << (SecondTemplateArgs != nullptr);
10420
10421 Diagnosed = true;
10422 break;
10423 }
10424
10425 if (FirstTemplateArgs && SecondTemplateArgs) {
10426 // Remove pack expansions from argument list.
10427 auto ExpandTemplateArgumentList =
10428 [](const TemplateArgumentList *TAL) {
10429 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10430 for (const TemplateArgument &TA : TAL->asArray()) {
10431 if (TA.getKind() != TemplateArgument::Pack) {
10432 ExpandedList.push_back(&TA);
10433 continue;
10434 }
10435 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10436 ExpandedList.push_back(&PackTA);
10437 }
10438 }
10439 return ExpandedList;
10440 };
10441 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10442 ExpandTemplateArgumentList(FirstTemplateArgs);
10443 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10444 ExpandTemplateArgumentList(SecondTemplateArgs);
10445
10446 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10447 ODRDiagError(FirstMethod->getLocation(),
10448 FirstMethod->getSourceRange(),
10449 MethodDifferentNumberTemplateArguments)
10450 << FirstMethodType << FirstName
10451 << (unsigned)FirstExpandedList.size();
10452 ODRDiagNote(SecondMethod->getLocation(),
10453 SecondMethod->getSourceRange(),
10454 MethodDifferentNumberTemplateArguments)
10455 << SecondMethodType << SecondName
10456 << (unsigned)SecondExpandedList.size();
10457
10458 Diagnosed = true;
10459 break;
10460 }
10461
10462 bool TemplateArgumentMismatch = false;
10463 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10464 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10465 &SecondTA = *SecondExpandedList[i];
10466 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10467 ComputeTemplateArgumentODRHash(SecondTA)) {
10468 continue;
10469 }
10470
10471 ODRDiagError(FirstMethod->getLocation(),
10472 FirstMethod->getSourceRange(),
10473 MethodDifferentTemplateArgument)
10474 << FirstMethodType << FirstName << FirstTA << i + 1;
10475 ODRDiagNote(SecondMethod->getLocation(),
10476 SecondMethod->getSourceRange(),
10477 MethodDifferentTemplateArgument)
10478 << SecondMethodType << SecondName << SecondTA << i + 1;
10479
10480 TemplateArgumentMismatch = true;
10481 break;
10482 }
10483
10484 if (TemplateArgumentMismatch) {
10485 Diagnosed = true;
10486 break;
10487 }
10488 }
Richard Trieu48143742017-02-28 21:24:38 +000010489 break;
10490 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010491 case TypeAlias:
10492 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010493 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10494 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010495 auto FirstName = FirstTD->getDeclName();
10496 auto SecondName = SecondTD->getDeclName();
10497 if (FirstName != SecondName) {
10498 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10499 TypedefName)
10500 << (FirstDiffType == TypeAlias) << FirstName;
10501 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10502 TypedefName)
10503 << (FirstDiffType == TypeAlias) << SecondName;
10504 Diagnosed = true;
10505 break;
10506 }
10507
10508 QualType FirstType = FirstTD->getUnderlyingType();
10509 QualType SecondType = SecondTD->getUnderlyingType();
10510 if (ComputeQualTypeODRHash(FirstType) !=
10511 ComputeQualTypeODRHash(SecondType)) {
10512 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10513 TypedefType)
10514 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10515 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10516 TypedefType)
10517 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10518 Diagnosed = true;
10519 break;
10520 }
10521 break;
10522 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010523 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010524 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10525 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010526 auto FirstName = FirstVD->getDeclName();
10527 auto SecondName = SecondVD->getDeclName();
10528 if (FirstName != SecondName) {
10529 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10530 VarName)
10531 << FirstName;
10532 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10533 VarName)
10534 << SecondName;
10535 Diagnosed = true;
10536 break;
10537 }
10538
10539 QualType FirstType = FirstVD->getType();
10540 QualType SecondType = SecondVD->getType();
10541 if (ComputeQualTypeODRHash(FirstType) !=
10542 ComputeQualTypeODRHash(SecondType)) {
10543 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10544 VarType)
10545 << FirstName << FirstType;
10546 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10547 VarType)
10548 << SecondName << SecondType;
10549 Diagnosed = true;
10550 break;
10551 }
10552
10553 const Expr *FirstInit = FirstVD->getInit();
10554 const Expr *SecondInit = SecondVD->getInit();
10555 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10556 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10557 VarSingleInitializer)
10558 << FirstName << (FirstInit == nullptr)
10559 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10560 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10561 VarSingleInitializer)
10562 << SecondName << (SecondInit == nullptr)
10563 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10564 Diagnosed = true;
10565 break;
10566 }
10567
10568 if (FirstInit && SecondInit &&
10569 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10570 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10571 VarDifferentInitializer)
10572 << FirstName << FirstInit->getSourceRange();
10573 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10574 VarDifferentInitializer)
10575 << SecondName << SecondInit->getSourceRange();
10576 Diagnosed = true;
10577 break;
10578 }
10579
10580 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10581 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10582 if (FirstIsConstexpr != SecondIsConstexpr) {
10583 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10584 VarConstexpr)
10585 << FirstName << FirstIsConstexpr;
10586 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10587 VarConstexpr)
10588 << SecondName << SecondIsConstexpr;
10589 Diagnosed = true;
10590 break;
10591 }
10592 break;
10593 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010594 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010595 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10596 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010597
10598 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10599 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10600
10601 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10602 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10603
10604 if (FirstND && SecondND) {
10605 ODRDiagError(FirstFriend->getFriendLoc(),
10606 FirstFriend->getSourceRange(), FriendFunction)
10607 << FirstND;
10608 ODRDiagNote(SecondFriend->getFriendLoc(),
10609 SecondFriend->getSourceRange(), FriendFunction)
10610 << SecondND;
10611
10612 Diagnosed = true;
10613 break;
10614 }
10615
10616 if (FirstTSI && SecondTSI) {
10617 QualType FirstFriendType = FirstTSI->getType();
10618 QualType SecondFriendType = SecondTSI->getType();
10619 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10620 ComputeQualTypeODRHash(SecondFriendType));
10621 ODRDiagError(FirstFriend->getFriendLoc(),
10622 FirstFriend->getSourceRange(), FriendType)
10623 << FirstFriendType;
10624 ODRDiagNote(SecondFriend->getFriendLoc(),
10625 SecondFriend->getSourceRange(), FriendType)
10626 << SecondFriendType;
10627 Diagnosed = true;
10628 break;
10629 }
10630
10631 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10632 FriendTypeFunction)
10633 << (FirstTSI == nullptr);
10634 ODRDiagNote(SecondFriend->getFriendLoc(),
10635 SecondFriend->getSourceRange(), FriendTypeFunction)
10636 << (SecondTSI == nullptr);
10637
10638 Diagnosed = true;
10639 break;
10640 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010641 case FunctionTemplate: {
10642 FunctionTemplateDecl *FirstTemplate =
10643 cast<FunctionTemplateDecl>(FirstDecl);
10644 FunctionTemplateDecl *SecondTemplate =
10645 cast<FunctionTemplateDecl>(SecondDecl);
10646
10647 TemplateParameterList *FirstTPL =
10648 FirstTemplate->getTemplateParameters();
10649 TemplateParameterList *SecondTPL =
10650 SecondTemplate->getTemplateParameters();
10651
10652 if (FirstTPL->size() != SecondTPL->size()) {
10653 ODRDiagError(FirstTemplate->getLocation(),
10654 FirstTemplate->getSourceRange(),
10655 FunctionTemplateDifferentNumberParameters)
10656 << FirstTemplate << FirstTPL->size();
10657 ODRDiagNote(SecondTemplate->getLocation(),
10658 SecondTemplate->getSourceRange(),
10659 FunctionTemplateDifferentNumberParameters)
10660 << SecondTemplate << SecondTPL->size();
10661
10662 Diagnosed = true;
10663 break;
10664 }
10665
10666 bool ParameterMismatch = false;
10667 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10668 NamedDecl *FirstParam = FirstTPL->getParam(i);
10669 NamedDecl *SecondParam = SecondTPL->getParam(i);
10670
10671 if (FirstParam->getKind() != SecondParam->getKind()) {
10672 enum {
10673 TemplateTypeParameter,
10674 NonTypeTemplateParameter,
10675 TemplateTemplateParameter,
10676 };
10677 auto GetParamType = [](NamedDecl *D) {
10678 switch (D->getKind()) {
10679 default:
10680 llvm_unreachable("Unexpected template parameter type");
10681 case Decl::TemplateTypeParm:
10682 return TemplateTypeParameter;
10683 case Decl::NonTypeTemplateParm:
10684 return NonTypeTemplateParameter;
10685 case Decl::TemplateTemplateParm:
10686 return TemplateTemplateParameter;
10687 }
10688 };
10689
10690 ODRDiagError(FirstTemplate->getLocation(),
10691 FirstTemplate->getSourceRange(),
10692 FunctionTemplateParameterDifferentKind)
10693 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10694 ODRDiagNote(SecondTemplate->getLocation(),
10695 SecondTemplate->getSourceRange(),
10696 FunctionTemplateParameterDifferentKind)
10697 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10698
10699 ParameterMismatch = true;
10700 break;
10701 }
10702
10703 if (FirstParam->getName() != SecondParam->getName()) {
10704 ODRDiagError(FirstTemplate->getLocation(),
10705 FirstTemplate->getSourceRange(),
10706 FunctionTemplateParameterName)
10707 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10708 << FirstParam;
10709 ODRDiagNote(SecondTemplate->getLocation(),
10710 SecondTemplate->getSourceRange(),
10711 FunctionTemplateParameterName)
10712 << SecondTemplate << (i + 1)
10713 << (bool)SecondParam->getIdentifier() << SecondParam;
10714 ParameterMismatch = true;
10715 break;
10716 }
10717
10718 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10719 isa<TemplateTypeParmDecl>(SecondParam)) {
10720 TemplateTypeParmDecl *FirstTTPD =
10721 cast<TemplateTypeParmDecl>(FirstParam);
10722 TemplateTypeParmDecl *SecondTTPD =
10723 cast<TemplateTypeParmDecl>(SecondParam);
10724 bool HasFirstDefaultArgument =
10725 FirstTTPD->hasDefaultArgument() &&
10726 !FirstTTPD->defaultArgumentWasInherited();
10727 bool HasSecondDefaultArgument =
10728 SecondTTPD->hasDefaultArgument() &&
10729 !SecondTTPD->defaultArgumentWasInherited();
10730 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10731 ODRDiagError(FirstTemplate->getLocation(),
10732 FirstTemplate->getSourceRange(),
10733 FunctionTemplateParameterSingleDefaultArgument)
10734 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10735 ODRDiagNote(SecondTemplate->getLocation(),
10736 SecondTemplate->getSourceRange(),
10737 FunctionTemplateParameterSingleDefaultArgument)
10738 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10739 ParameterMismatch = true;
10740 break;
10741 }
10742
10743 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10744 QualType FirstType = FirstTTPD->getDefaultArgument();
10745 QualType SecondType = SecondTTPD->getDefaultArgument();
10746 if (ComputeQualTypeODRHash(FirstType) !=
10747 ComputeQualTypeODRHash(SecondType)) {
10748 ODRDiagError(FirstTemplate->getLocation(),
10749 FirstTemplate->getSourceRange(),
10750 FunctionTemplateParameterDifferentDefaultArgument)
10751 << FirstTemplate << (i + 1) << FirstType;
10752 ODRDiagNote(SecondTemplate->getLocation(),
10753 SecondTemplate->getSourceRange(),
10754 FunctionTemplateParameterDifferentDefaultArgument)
10755 << SecondTemplate << (i + 1) << SecondType;
10756 ParameterMismatch = true;
10757 break;
10758 }
10759 }
10760
10761 if (FirstTTPD->isParameterPack() !=
10762 SecondTTPD->isParameterPack()) {
10763 ODRDiagError(FirstTemplate->getLocation(),
10764 FirstTemplate->getSourceRange(),
10765 FunctionTemplatePackParameter)
10766 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10767 ODRDiagNote(SecondTemplate->getLocation(),
10768 SecondTemplate->getSourceRange(),
10769 FunctionTemplatePackParameter)
10770 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10771 ParameterMismatch = true;
10772 break;
10773 }
10774 }
10775
10776 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10777 isa<TemplateTemplateParmDecl>(SecondParam)) {
10778 TemplateTemplateParmDecl *FirstTTPD =
10779 cast<TemplateTemplateParmDecl>(FirstParam);
10780 TemplateTemplateParmDecl *SecondTTPD =
10781 cast<TemplateTemplateParmDecl>(SecondParam);
10782
10783 TemplateParameterList *FirstTPL =
10784 FirstTTPD->getTemplateParameters();
10785 TemplateParameterList *SecondTPL =
10786 SecondTTPD->getTemplateParameters();
10787
10788 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10789 ComputeTemplateParameterListODRHash(SecondTPL)) {
10790 ODRDiagError(FirstTemplate->getLocation(),
10791 FirstTemplate->getSourceRange(),
10792 FunctionTemplateParameterDifferentType)
10793 << FirstTemplate << (i + 1);
10794 ODRDiagNote(SecondTemplate->getLocation(),
10795 SecondTemplate->getSourceRange(),
10796 FunctionTemplateParameterDifferentType)
10797 << SecondTemplate << (i + 1);
10798 ParameterMismatch = true;
10799 break;
10800 }
10801
10802 bool HasFirstDefaultArgument =
10803 FirstTTPD->hasDefaultArgument() &&
10804 !FirstTTPD->defaultArgumentWasInherited();
10805 bool HasSecondDefaultArgument =
10806 SecondTTPD->hasDefaultArgument() &&
10807 !SecondTTPD->defaultArgumentWasInherited();
10808 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10809 ODRDiagError(FirstTemplate->getLocation(),
10810 FirstTemplate->getSourceRange(),
10811 FunctionTemplateParameterSingleDefaultArgument)
10812 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10813 ODRDiagNote(SecondTemplate->getLocation(),
10814 SecondTemplate->getSourceRange(),
10815 FunctionTemplateParameterSingleDefaultArgument)
10816 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10817 ParameterMismatch = true;
10818 break;
10819 }
10820
10821 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10822 TemplateArgument FirstTA =
10823 FirstTTPD->getDefaultArgument().getArgument();
10824 TemplateArgument SecondTA =
10825 SecondTTPD->getDefaultArgument().getArgument();
10826 if (ComputeTemplateArgumentODRHash(FirstTA) !=
10827 ComputeTemplateArgumentODRHash(SecondTA)) {
10828 ODRDiagError(FirstTemplate->getLocation(),
10829 FirstTemplate->getSourceRange(),
10830 FunctionTemplateParameterDifferentDefaultArgument)
10831 << FirstTemplate << (i + 1) << FirstTA;
10832 ODRDiagNote(SecondTemplate->getLocation(),
10833 SecondTemplate->getSourceRange(),
10834 FunctionTemplateParameterDifferentDefaultArgument)
10835 << SecondTemplate << (i + 1) << SecondTA;
10836 ParameterMismatch = true;
10837 break;
10838 }
10839 }
10840
10841 if (FirstTTPD->isParameterPack() !=
10842 SecondTTPD->isParameterPack()) {
10843 ODRDiagError(FirstTemplate->getLocation(),
10844 FirstTemplate->getSourceRange(),
10845 FunctionTemplatePackParameter)
10846 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10847 ODRDiagNote(SecondTemplate->getLocation(),
10848 SecondTemplate->getSourceRange(),
10849 FunctionTemplatePackParameter)
10850 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10851 ParameterMismatch = true;
10852 break;
10853 }
10854 }
10855
10856 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10857 isa<NonTypeTemplateParmDecl>(SecondParam)) {
10858 NonTypeTemplateParmDecl *FirstNTTPD =
10859 cast<NonTypeTemplateParmDecl>(FirstParam);
10860 NonTypeTemplateParmDecl *SecondNTTPD =
10861 cast<NonTypeTemplateParmDecl>(SecondParam);
10862
10863 QualType FirstType = FirstNTTPD->getType();
10864 QualType SecondType = SecondNTTPD->getType();
10865 if (ComputeQualTypeODRHash(FirstType) !=
10866 ComputeQualTypeODRHash(SecondType)) {
10867 ODRDiagError(FirstTemplate->getLocation(),
10868 FirstTemplate->getSourceRange(),
10869 FunctionTemplateParameterDifferentType)
10870 << FirstTemplate << (i + 1);
10871 ODRDiagNote(SecondTemplate->getLocation(),
10872 SecondTemplate->getSourceRange(),
10873 FunctionTemplateParameterDifferentType)
10874 << SecondTemplate << (i + 1);
10875 ParameterMismatch = true;
10876 break;
10877 }
10878
10879 bool HasFirstDefaultArgument =
10880 FirstNTTPD->hasDefaultArgument() &&
10881 !FirstNTTPD->defaultArgumentWasInherited();
10882 bool HasSecondDefaultArgument =
10883 SecondNTTPD->hasDefaultArgument() &&
10884 !SecondNTTPD->defaultArgumentWasInherited();
10885 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10886 ODRDiagError(FirstTemplate->getLocation(),
10887 FirstTemplate->getSourceRange(),
10888 FunctionTemplateParameterSingleDefaultArgument)
10889 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10890 ODRDiagNote(SecondTemplate->getLocation(),
10891 SecondTemplate->getSourceRange(),
10892 FunctionTemplateParameterSingleDefaultArgument)
10893 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10894 ParameterMismatch = true;
10895 break;
10896 }
10897
10898 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10899 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
10900 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
10901 if (ComputeODRHash(FirstDefaultArgument) !=
10902 ComputeODRHash(SecondDefaultArgument)) {
10903 ODRDiagError(FirstTemplate->getLocation(),
10904 FirstTemplate->getSourceRange(),
10905 FunctionTemplateParameterDifferentDefaultArgument)
10906 << FirstTemplate << (i + 1) << FirstDefaultArgument;
10907 ODRDiagNote(SecondTemplate->getLocation(),
10908 SecondTemplate->getSourceRange(),
10909 FunctionTemplateParameterDifferentDefaultArgument)
10910 << SecondTemplate << (i + 1) << SecondDefaultArgument;
10911 ParameterMismatch = true;
10912 break;
10913 }
10914 }
10915
10916 if (FirstNTTPD->isParameterPack() !=
10917 SecondNTTPD->isParameterPack()) {
10918 ODRDiagError(FirstTemplate->getLocation(),
10919 FirstTemplate->getSourceRange(),
10920 FunctionTemplatePackParameter)
10921 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
10922 ODRDiagNote(SecondTemplate->getLocation(),
10923 SecondTemplate->getSourceRange(),
10924 FunctionTemplatePackParameter)
10925 << SecondTemplate << (i + 1)
10926 << SecondNTTPD->isParameterPack();
10927 ParameterMismatch = true;
10928 break;
10929 }
10930 }
10931 }
10932
10933 if (ParameterMismatch) {
10934 Diagnosed = true;
10935 break;
10936 }
10937
10938 break;
10939 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010940 }
10941
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000010942 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000010943 continue;
10944
Richard Trieu708859a2017-06-08 00:56:21 +000010945 Diag(FirstDecl->getLocation(),
10946 diag::err_module_odr_violation_mismatch_decl_unknown)
10947 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10948 << FirstDecl->getSourceRange();
10949 Diag(SecondDecl->getLocation(),
10950 diag::note_module_odr_violation_mismatch_decl_unknown)
10951 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010952 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010953 }
10954
10955 if (!Diagnosed) {
10956 // All definitions are updates to the same declaration. This happens if a
10957 // module instantiates the declaration of a class template specialization
10958 // and two or more other modules instantiate its definition.
10959 //
10960 // FIXME: Indicate which modules had instantiations of this definition.
10961 // FIXME: How can this even happen?
10962 Diag(Merge.first->getLocation(),
10963 diag::err_module_odr_violation_different_instantiations)
10964 << Merge.first;
10965 }
10966 }
Richard Trieue6caa262017-12-23 00:41:01 +000010967
10968 // Issue ODR failures diagnostics for functions.
10969 for (auto &Merge : FunctionOdrMergeFailures) {
10970 enum ODRFunctionDifference {
10971 ReturnType,
10972 ParameterName,
10973 ParameterType,
10974 ParameterSingleDefaultArgument,
10975 ParameterDifferentDefaultArgument,
10976 FunctionBody,
10977 };
10978
10979 FunctionDecl *FirstFunction = Merge.first;
10980 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
10981
10982 bool Diagnosed = false;
10983 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010984
Richard Trieue6caa262017-12-23 00:41:01 +000010985 if (FirstFunction == SecondFunction)
10986 continue;
10987
10988 std::string SecondModule =
10989 getOwningModuleNameForDiagnostic(SecondFunction);
10990
10991 auto ODRDiagError = [FirstFunction, &FirstModule,
10992 this](SourceLocation Loc, SourceRange Range,
10993 ODRFunctionDifference DiffType) {
10994 return Diag(Loc, diag::err_module_odr_violation_function)
10995 << FirstFunction << FirstModule.empty() << FirstModule << Range
10996 << DiffType;
10997 };
10998 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
10999 SourceRange Range,
11000 ODRFunctionDifference DiffType) {
11001 return Diag(Loc, diag::note_module_odr_violation_function)
11002 << SecondModule << Range << DiffType;
11003 };
11004
11005 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11006 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11007 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11008 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11009 << FirstFunction->getReturnType();
11010 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11011 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11012 << SecondFunction->getReturnType();
11013 Diagnosed = true;
11014 break;
11015 }
11016
11017 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11018 "Merged functions with different number of parameters");
11019
11020 auto ParamSize = FirstFunction->param_size();
11021 bool ParameterMismatch = false;
11022 for (unsigned I = 0; I < ParamSize; ++I) {
11023 auto *FirstParam = FirstFunction->getParamDecl(I);
11024 auto *SecondParam = SecondFunction->getParamDecl(I);
11025
11026 assert(getContext().hasSameType(FirstParam->getType(),
11027 SecondParam->getType()) &&
11028 "Merged function has different parameter types.");
11029
11030 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11031 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11032 ParameterName)
11033 << I + 1 << FirstParam->getDeclName();
11034 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11035 ParameterName)
11036 << I + 1 << SecondParam->getDeclName();
11037 ParameterMismatch = true;
11038 break;
11039 };
11040
11041 QualType FirstParamType = FirstParam->getType();
11042 QualType SecondParamType = SecondParam->getType();
11043 if (FirstParamType != SecondParamType &&
11044 ComputeQualTypeODRHash(FirstParamType) !=
11045 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011046 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011047 FirstParamType->getAs<DecayedType>()) {
11048 ODRDiagError(FirstParam->getLocation(),
11049 FirstParam->getSourceRange(), ParameterType)
11050 << (I + 1) << FirstParamType << true
11051 << ParamDecayedType->getOriginalType();
11052 } else {
11053 ODRDiagError(FirstParam->getLocation(),
11054 FirstParam->getSourceRange(), ParameterType)
11055 << (I + 1) << FirstParamType << false;
11056 }
11057
Vedant Kumar48b4f762018-04-14 01:40:48 +000011058 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011059 SecondParamType->getAs<DecayedType>()) {
11060 ODRDiagNote(SecondParam->getLocation(),
11061 SecondParam->getSourceRange(), ParameterType)
11062 << (I + 1) << SecondParamType << true
11063 << ParamDecayedType->getOriginalType();
11064 } else {
11065 ODRDiagNote(SecondParam->getLocation(),
11066 SecondParam->getSourceRange(), ParameterType)
11067 << (I + 1) << SecondParamType << false;
11068 }
11069 ParameterMismatch = true;
11070 break;
11071 }
11072
11073 const Expr *FirstInit = FirstParam->getInit();
11074 const Expr *SecondInit = SecondParam->getInit();
11075 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11076 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11077 ParameterSingleDefaultArgument)
11078 << (I + 1) << (FirstInit == nullptr)
11079 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11080 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11081 ParameterSingleDefaultArgument)
11082 << (I + 1) << (SecondInit == nullptr)
11083 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11084 ParameterMismatch = true;
11085 break;
11086 }
11087
11088 if (FirstInit && SecondInit &&
11089 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11090 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11091 ParameterDifferentDefaultArgument)
11092 << (I + 1) << FirstInit->getSourceRange();
11093 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11094 ParameterDifferentDefaultArgument)
11095 << (I + 1) << SecondInit->getSourceRange();
11096 ParameterMismatch = true;
11097 break;
11098 }
11099
11100 assert(ComputeSubDeclODRHash(FirstParam) ==
11101 ComputeSubDeclODRHash(SecondParam) &&
11102 "Undiagnosed parameter difference.");
11103 }
11104
11105 if (ParameterMismatch) {
11106 Diagnosed = true;
11107 break;
11108 }
11109
11110 // If no error has been generated before now, assume the problem is in
11111 // the body and generate a message.
11112 ODRDiagError(FirstFunction->getLocation(),
11113 FirstFunction->getSourceRange(), FunctionBody);
11114 ODRDiagNote(SecondFunction->getLocation(),
11115 SecondFunction->getSourceRange(), FunctionBody);
11116 Diagnosed = true;
11117 break;
11118 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011119 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011120 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11121 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011122}
11123
Richard Smithce18a182015-07-14 00:26:00 +000011124void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011125 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011126 ReadTimer->startTimer();
11127}
11128
Guy Benyei11169dd2012-12-18 14:30:41 +000011129void ASTReader::FinishedDeserializing() {
11130 assert(NumCurrentElementsDeserializing &&
11131 "FinishedDeserializing not paired with StartedDeserializing");
11132 if (NumCurrentElementsDeserializing == 1) {
11133 // We decrease NumCurrentElementsDeserializing only after pending actions
11134 // are finished, to avoid recursively re-calling finishPendingActions().
11135 finishPendingActions();
11136 }
11137 --NumCurrentElementsDeserializing;
11138
Richard Smitha0ce9c42014-07-29 23:23:27 +000011139 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011140 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000011141 while (!PendingExceptionSpecUpdates.empty()) {
11142 auto Updates = std::move(PendingExceptionSpecUpdates);
11143 PendingExceptionSpecUpdates.clear();
11144 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011145 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011146 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011147 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011148 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011149 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011150 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011151 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011152 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011153 }
11154
Richard Smithce18a182015-07-14 00:26:00 +000011155 if (ReadTimer)
11156 ReadTimer->stopTimer();
11157
Richard Smith0f4e2c42015-08-06 04:23:48 +000011158 diagnoseOdrViolations();
11159
Richard Smith04d05b52014-03-23 00:27:18 +000011160 // We are not in recursive loading, so it's safe to pass the "interesting"
11161 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011162 if (Consumer)
11163 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011164 }
11165}
11166
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011167void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011168 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11169 // Remove any fake results before adding any real ones.
11170 auto It = PendingFakeLookupResults.find(II);
11171 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011172 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011173 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011174 // FIXME: this works around module+PCH performance issue.
11175 // Rather than erase the result from the map, which is O(n), just clear
11176 // the vector of NamedDecls.
11177 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011178 }
11179 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011180
11181 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11182 SemaObj->TUScope->AddDecl(D);
11183 } else if (SemaObj->TUScope) {
11184 // Adding the decl to IdResolver may have failed because it was already in
11185 // (even though it was not added in scope). If it is already in, make sure
11186 // it gets in the scope as well.
11187 if (std::find(SemaObj->IdResolver.begin(Name),
11188 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11189 SemaObj->TUScope->AddDecl(D);
11190 }
11191}
11192
Richard Smithdbafb6c2017-06-29 23:23:46 +000011193ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011194 const PCHContainerReader &PCHContainerRdr,
11195 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11196 StringRef isysroot, bool DisableValidation,
11197 bool AllowASTWithCompilerErrors,
11198 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11199 bool UseGlobalIndex,
11200 std::unique_ptr<llvm::Timer> ReadTimer)
11201 : Listener(DisableValidation
11202 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11203 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011204 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011205 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000011206 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000011207 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
11208 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000011209 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
11210 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011211 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011212 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11213 AllowConfigurationMismatch(AllowConfigurationMismatch),
11214 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011215 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011216 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011217
11218 for (const auto &Ext : Extensions) {
11219 auto BlockName = Ext->getExtensionMetadata().BlockName;
11220 auto Known = ModuleFileExtensions.find(BlockName);
11221 if (Known != ModuleFileExtensions.end()) {
11222 Diags.Report(diag::warn_duplicate_module_file_extension)
11223 << BlockName;
11224 continue;
11225 }
11226
11227 ModuleFileExtensions.insert({BlockName, Ext});
11228 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011229}
11230
11231ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011232 if (OwnsDeserializationListener)
11233 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011234}
Richard Smith10379092016-05-06 23:14:07 +000011235
11236IdentifierResolver &ASTReader::getIdResolver() {
11237 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11238}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011239
11240unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11241 unsigned AbbrevID) {
11242 Idx = 0;
11243 Record.clear();
11244 return Cursor.readRecord(AbbrevID, Record);
11245}