blob: 4dd79720270219cc58245973a794919a3977ea95 [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;
Leonard Chanf921d852018-06-04 16:07:52 +00006822 case PREDEF_TYPE_SHORT_ACCUM_ID:
6823 T = Context.ShortAccumTy;
6824 break;
6825 case PREDEF_TYPE_ACCUM_ID:
6826 T = Context.AccumTy;
6827 break;
6828 case PREDEF_TYPE_LONG_ACCUM_ID:
6829 T = Context.LongAccumTy;
6830 break;
6831 case PREDEF_TYPE_USHORT_ACCUM_ID:
6832 T = Context.UnsignedShortAccumTy;
6833 break;
6834 case PREDEF_TYPE_UACCUM_ID:
6835 T = Context.UnsignedAccumTy;
6836 break;
6837 case PREDEF_TYPE_ULONG_ACCUM_ID:
6838 T = Context.UnsignedLongAccumTy;
6839 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006840 case PREDEF_TYPE_FLOAT16_ID:
6841 T = Context.Float16Ty;
6842 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006843 case PREDEF_TYPE_FLOAT128_ID:
6844 T = Context.Float128Ty;
6845 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006846 case PREDEF_TYPE_OVERLOAD_ID:
6847 T = Context.OverloadTy;
6848 break;
6849 case PREDEF_TYPE_BOUND_MEMBER:
6850 T = Context.BoundMemberTy;
6851 break;
6852 case PREDEF_TYPE_PSEUDO_OBJECT:
6853 T = Context.PseudoObjectTy;
6854 break;
6855 case PREDEF_TYPE_DEPENDENT_ID:
6856 T = Context.DependentTy;
6857 break;
6858 case PREDEF_TYPE_UNKNOWN_ANY:
6859 T = Context.UnknownAnyTy;
6860 break;
6861 case PREDEF_TYPE_NULLPTR_ID:
6862 T = Context.NullPtrTy;
6863 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00006864 case PREDEF_TYPE_CHAR8_ID:
6865 T = Context.Char8Ty;
6866 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006867 case PREDEF_TYPE_CHAR16_ID:
6868 T = Context.Char16Ty;
6869 break;
6870 case PREDEF_TYPE_CHAR32_ID:
6871 T = Context.Char32Ty;
6872 break;
6873 case PREDEF_TYPE_OBJC_ID:
6874 T = Context.ObjCBuiltinIdTy;
6875 break;
6876 case PREDEF_TYPE_OBJC_CLASS:
6877 T = Context.ObjCBuiltinClassTy;
6878 break;
6879 case PREDEF_TYPE_OBJC_SEL:
6880 T = Context.ObjCBuiltinSelTy;
6881 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006882#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6883 case PREDEF_TYPE_##Id##_ID: \
6884 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006885 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006886#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006887 case PREDEF_TYPE_SAMPLER_ID:
6888 T = Context.OCLSamplerTy;
6889 break;
6890 case PREDEF_TYPE_EVENT_ID:
6891 T = Context.OCLEventTy;
6892 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006893 case PREDEF_TYPE_CLK_EVENT_ID:
6894 T = Context.OCLClkEventTy;
6895 break;
6896 case PREDEF_TYPE_QUEUE_ID:
6897 T = Context.OCLQueueTy;
6898 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006899 case PREDEF_TYPE_RESERVE_ID_ID:
6900 T = Context.OCLReserveIDTy;
6901 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006902 case PREDEF_TYPE_AUTO_DEDUCT:
6903 T = Context.getAutoDeductType();
6904 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006905 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6906 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006907 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006908 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6909 T = Context.ARCUnbridgedCastTy;
6910 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006911 case PREDEF_TYPE_BUILTIN_FN:
6912 T = Context.BuiltinFnTy;
6913 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006914 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6915 T = Context.OMPArraySectionTy;
6916 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006917 }
6918
6919 assert(!T.isNull() && "Unknown predefined type");
6920 return T.withFastQualifiers(FastQuals);
6921 }
6922
6923 Index -= NUM_PREDEF_TYPE_IDS;
6924 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6925 if (TypesLoaded[Index].isNull()) {
6926 TypesLoaded[Index] = readTypeRecord(Index);
6927 if (TypesLoaded[Index].isNull())
Vedant Kumar48b4f762018-04-14 01:40:48 +00006928 return QualType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006929
6930 TypesLoaded[Index]->setFromAST();
6931 if (DeserializationListener)
6932 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6933 TypesLoaded[Index]);
6934 }
6935
6936 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6937}
6938
6939QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6940 return GetType(getGlobalTypeID(F, LocalID));
6941}
6942
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006943serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006944ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6945 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6946 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006947
Guy Benyei11169dd2012-12-18 14:30:41 +00006948 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6949 return LocalID;
6950
Richard Smith37a93df2017-02-18 00:32:02 +00006951 if (!F.ModuleOffsetMap.empty())
6952 ReadModuleOffsetMap(F);
6953
Guy Benyei11169dd2012-12-18 14:30:41 +00006954 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6955 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6956 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006957
Guy Benyei11169dd2012-12-18 14:30:41 +00006958 unsigned GlobalIndex = LocalIndex + I->second;
6959 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6960}
6961
6962TemplateArgumentLocInfo
6963ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6964 TemplateArgument::ArgKind Kind,
6965 const RecordData &Record,
6966 unsigned &Index) {
6967 switch (Kind) {
6968 case TemplateArgument::Expression:
6969 return ReadExpr(F);
6970 case TemplateArgument::Type:
6971 return GetTypeSourceInfo(F, Record, Index);
6972 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006973 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006974 Index);
6975 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6976 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6977 SourceLocation());
6978 }
6979 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006980 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006981 Index);
6982 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6983 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006984 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006985 EllipsisLoc);
6986 }
6987 case TemplateArgument::Null:
6988 case TemplateArgument::Integral:
6989 case TemplateArgument::Declaration:
6990 case TemplateArgument::NullPtr:
6991 case TemplateArgument::Pack:
6992 // FIXME: Is this right?
Vedant Kumar48b4f762018-04-14 01:40:48 +00006993 return TemplateArgumentLocInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +00006994 }
6995 llvm_unreachable("unexpected template argument loc");
6996}
6997
6998TemplateArgumentLoc
6999ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
7000 const RecordData &Record, unsigned &Index) {
7001 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
7002
7003 if (Arg.getKind() == TemplateArgument::Expression) {
7004 if (Record[Index++]) // bool InfoHasSameExpr.
7005 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
7006 }
7007 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
7008 Record, Index));
7009}
7010
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00007011const ASTTemplateArgumentListInfo*
7012ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
7013 const RecordData &Record,
7014 unsigned &Index) {
7015 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
7016 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
7017 unsigned NumArgsAsWritten = Record[Index++];
7018 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
7019 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
7020 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
7021 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
7022}
7023
Guy Benyei11169dd2012-12-18 14:30:41 +00007024Decl *ASTReader::GetExternalDecl(uint32_t ID) {
7025 return GetDecl(ID);
7026}
7027
Richard Smith053f6c62014-05-16 23:01:30 +00007028void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00007029 if (NumCurrentElementsDeserializing) {
7030 // We arrange to not care about the complete redeclaration chain while we're
7031 // deserializing. Just remember that the AST has marked this one as complete
7032 // but that it's not actually complete yet, so we know we still need to
7033 // complete it later.
7034 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
7035 return;
7036 }
7037
Richard Smith053f6c62014-05-16 23:01:30 +00007038 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
7039
Richard Smith053f6c62014-05-16 23:01:30 +00007040 // If this is a named declaration, complete it by looking it up
7041 // within its context.
7042 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00007043 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00007044 // all mergeable entities within it.
7045 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
7046 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
7047 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00007048 if (!getContext().getLangOpts().CPlusPlus &&
7049 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00007050 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00007051 // the identifier instead. (For C++ modules, we don't store decls
7052 // in the serialized identifier table, so we do the lookup in the TU.)
7053 auto *II = Name.getAsIdentifierInfo();
7054 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00007055 if (II->isOutOfDate())
7056 updateOutOfDateIdentifier(*II);
7057 } else
7058 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00007059 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00007060 // Find all declarations of this kind from the relevant context.
7061 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
7062 auto *DC = cast<DeclContext>(DCDecl);
7063 SmallVector<Decl*, 8> Decls;
7064 FindExternalLexicalDecls(
7065 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
7066 }
Richard Smith053f6c62014-05-16 23:01:30 +00007067 }
7068 }
Richard Smith50895422015-01-31 03:04:55 +00007069
7070 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
7071 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
7072 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
7073 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
7074 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7075 if (auto *Template = FD->getPrimaryTemplate())
7076 Template->LoadLazySpecializations();
7077 }
Richard Smith053f6c62014-05-16 23:01:30 +00007078}
7079
Richard Smithc2bb8182015-03-24 06:36:48 +00007080CXXCtorInitializer **
7081ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
7082 RecordLocation Loc = getLocalBitOffset(Offset);
7083 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
7084 SavedStreamPosition SavedPosition(Cursor);
7085 Cursor.JumpToBit(Loc.Offset);
7086 ReadingKindTracker ReadingKind(Read_Decl, *this);
7087
7088 RecordData Record;
7089 unsigned Code = Cursor.ReadCode();
7090 unsigned RecCode = Cursor.readRecord(Code, Record);
7091 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
7092 Error("malformed AST file: missing C++ ctor initializers");
7093 return nullptr;
7094 }
7095
7096 unsigned Idx = 0;
7097 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
7098}
7099
Guy Benyei11169dd2012-12-18 14:30:41 +00007100CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007101 assert(ContextObj && "reading base specifiers with no AST context");
7102 ASTContext &Context = *ContextObj;
7103
Guy Benyei11169dd2012-12-18 14:30:41 +00007104 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00007105 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00007106 SavedStreamPosition SavedPosition(Cursor);
7107 Cursor.JumpToBit(Loc.Offset);
7108 ReadingKindTracker ReadingKind(Read_Decl, *this);
7109 RecordData Record;
7110 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00007111 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00007112 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00007113 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00007114 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007115 }
7116
7117 unsigned Idx = 0;
7118 unsigned NumBases = Record[Idx++];
7119 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
Vedant Kumar48b4f762018-04-14 01:40:48 +00007120 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
Guy Benyei11169dd2012-12-18 14:30:41 +00007121 for (unsigned I = 0; I != NumBases; ++I)
7122 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
7123 return Bases;
7124}
7125
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007126serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007127ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7128 if (LocalID < NUM_PREDEF_DECL_IDS)
7129 return LocalID;
7130
Richard Smith37a93df2017-02-18 00:32:02 +00007131 if (!F.ModuleOffsetMap.empty())
7132 ReadModuleOffsetMap(F);
7133
Guy Benyei11169dd2012-12-18 14:30:41 +00007134 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7135 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7136 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007137
Guy Benyei11169dd2012-12-18 14:30:41 +00007138 return LocalID + I->second;
7139}
7140
7141bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7142 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007143 // Predefined decls aren't from any module.
7144 if (ID < NUM_PREDEF_DECL_IDS)
7145 return false;
7146
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007147 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007148 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007149}
7150
Douglas Gregor9f782892013-01-21 15:25:38 +00007151ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007152 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007153 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007154 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7155 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7156 return I->second;
7157}
7158
7159SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7160 if (ID < NUM_PREDEF_DECL_IDS)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007161 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007162
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7164
7165 if (Index > DeclsLoaded.size()) {
7166 Error("declaration ID out-of-range for AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00007167 return SourceLocation();
Guy Benyei11169dd2012-12-18 14:30:41 +00007168 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007169
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 if (Decl *D = DeclsLoaded[Index])
7171 return D->getLocation();
7172
Richard Smithcb34bd32016-03-27 07:28:06 +00007173 SourceLocation Loc;
7174 DeclCursorForID(ID, Loc);
7175 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007176}
7177
Richard Smithfe620d22015-03-05 23:24:12 +00007178static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7179 switch (ID) {
7180 case PREDEF_DECL_NULL_ID:
7181 return nullptr;
7182
7183 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7184 return Context.getTranslationUnitDecl();
7185
7186 case PREDEF_DECL_OBJC_ID_ID:
7187 return Context.getObjCIdDecl();
7188
7189 case PREDEF_DECL_OBJC_SEL_ID:
7190 return Context.getObjCSelDecl();
7191
7192 case PREDEF_DECL_OBJC_CLASS_ID:
7193 return Context.getObjCClassDecl();
7194
7195 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7196 return Context.getObjCProtocolDecl();
7197
7198 case PREDEF_DECL_INT_128_ID:
7199 return Context.getInt128Decl();
7200
7201 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7202 return Context.getUInt128Decl();
7203
7204 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7205 return Context.getObjCInstanceTypeDecl();
7206
7207 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7208 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007209
Richard Smith9b88a4c2015-07-27 05:40:23 +00007210 case PREDEF_DECL_VA_LIST_TAG:
7211 return Context.getVaListTagDecl();
7212
Charles Davisc7d5c942015-09-17 20:55:33 +00007213 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7214 return Context.getBuiltinMSVaListDecl();
7215
Richard Smithf19e1272015-03-07 00:04:49 +00007216 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7217 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007218
7219 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7220 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007221
7222 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7223 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007224
7225 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7226 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007227
7228 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7229 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007230 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007231 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007232}
7233
Richard Smithcd45dbc2014-04-19 03:48:30 +00007234Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007235 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007236 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007237 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007238 if (D) {
7239 // Track that we have merged the declaration with ID \p ID into the
7240 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007241 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007242 if (Merged.empty())
7243 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 }
Richard Smithfe620d22015-03-05 23:24:12 +00007245 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007246 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007247
Guy Benyei11169dd2012-12-18 14:30:41 +00007248 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7249
7250 if (Index >= DeclsLoaded.size()) {
7251 assert(0 && "declaration ID out-of-range for AST file");
7252 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007253 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007254 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007255
7256 return DeclsLoaded[Index];
7257}
7258
7259Decl *ASTReader::GetDecl(DeclID ID) {
7260 if (ID < NUM_PREDEF_DECL_IDS)
7261 return GetExistingDecl(ID);
7262
7263 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7264
7265 if (Index >= DeclsLoaded.size()) {
7266 assert(0 && "declaration ID out-of-range for AST file");
7267 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007268 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007269 }
7270
Guy Benyei11169dd2012-12-18 14:30:41 +00007271 if (!DeclsLoaded[Index]) {
7272 ReadDeclRecord(ID);
7273 if (DeserializationListener)
7274 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7275 }
7276
7277 return DeclsLoaded[Index];
7278}
7279
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007280DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007281 DeclID GlobalID) {
7282 if (GlobalID < NUM_PREDEF_DECL_IDS)
7283 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007284
Guy Benyei11169dd2012-12-18 14:30:41 +00007285 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7286 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7287 ModuleFile *Owner = I->second;
7288
7289 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7290 = M.GlobalToLocalDeclIDs.find(Owner);
7291 if (Pos == M.GlobalToLocalDeclIDs.end())
7292 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007293
Guy Benyei11169dd2012-12-18 14:30:41 +00007294 return GlobalID - Owner->BaseDeclID + Pos->second;
7295}
7296
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007297serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007298 const RecordData &Record,
7299 unsigned &Idx) {
7300 if (Idx >= Record.size()) {
7301 Error("Corrupted AST file");
7302 return 0;
7303 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007304
Guy Benyei11169dd2012-12-18 14:30:41 +00007305 return getGlobalDeclID(F, Record[Idx++]);
7306}
7307
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007308/// Resolve the offset of a statement into a statement.
Guy Benyei11169dd2012-12-18 14:30:41 +00007309///
7310/// This operation will read a new statement from the external
7311/// source each time it is called, and is meant to be used via a
7312/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7313Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7314 // Switch case IDs are per Decl.
7315 ClearSwitchCaseIDs();
7316
7317 // Offset here is a global offset across the entire chain.
7318 RecordLocation Loc = getLocalBitOffset(Offset);
7319 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007320 assert(NumCurrentElementsDeserializing == 0 &&
7321 "should not be called while already deserializing");
7322 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007323 return ReadStmtFromStream(*Loc.F);
7324}
7325
Richard Smith3cb15722015-08-05 22:41:45 +00007326void ASTReader::FindExternalLexicalDecls(
7327 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7328 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007329 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7330
Richard Smith9ccdd932015-08-06 22:14:12 +00007331 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007332 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7333 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7334 auto K = (Decl::Kind)+LexicalDecls[I];
7335 if (!IsKindWeWant(K))
7336 continue;
7337
7338 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7339
7340 // Don't add predefined declarations to the lexical context more
7341 // than once.
7342 if (ID < NUM_PREDEF_DECL_IDS) {
7343 if (PredefsVisited[ID])
7344 continue;
7345
7346 PredefsVisited[ID] = true;
7347 }
7348
7349 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007350 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007351 if (!DC->isDeclInLexicalTraversal(D))
7352 Decls.push_back(D);
7353 }
7354 }
7355 };
7356
7357 if (isa<TranslationUnitDecl>(DC)) {
7358 for (auto Lexical : TULexicalDecls)
7359 Visit(Lexical.first, Lexical.second);
7360 } else {
7361 auto I = LexicalDecls.find(DC);
7362 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007363 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007364 }
7365
Guy Benyei11169dd2012-12-18 14:30:41 +00007366 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007367}
7368
7369namespace {
7370
7371class DeclIDComp {
7372 ASTReader &Reader;
7373 ModuleFile &Mod;
7374
7375public:
7376 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7377
7378 bool operator()(LocalDeclID L, LocalDeclID R) const {
7379 SourceLocation LHS = getLocation(L);
7380 SourceLocation RHS = getLocation(R);
7381 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7382 }
7383
7384 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7385 SourceLocation RHS = getLocation(R);
7386 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7387 }
7388
7389 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7390 SourceLocation LHS = getLocation(L);
7391 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7392 }
7393
7394 SourceLocation getLocation(LocalDeclID ID) const {
7395 return Reader.getSourceManager().getFileLoc(
7396 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7397 }
7398};
7399
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007400} // namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007401
7402void ASTReader::FindFileRegionDecls(FileID File,
7403 unsigned Offset, unsigned Length,
7404 SmallVectorImpl<Decl *> &Decls) {
7405 SourceManager &SM = getSourceManager();
7406
7407 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7408 if (I == FileDeclIDs.end())
7409 return;
7410
7411 FileDeclsInfo &DInfo = I->second;
7412 if (DInfo.Decls.empty())
7413 return;
7414
7415 SourceLocation
7416 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7417 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7418
7419 DeclIDComp DIDComp(*this, *DInfo.Mod);
7420 ArrayRef<serialization::LocalDeclID>::iterator
7421 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7422 BeginLoc, DIDComp);
7423 if (BeginIt != DInfo.Decls.begin())
7424 --BeginIt;
7425
7426 // If we are pointing at a top-level decl inside an objc container, we need
7427 // to backtrack until we find it otherwise we will fail to report that the
7428 // region overlaps with an objc container.
7429 while (BeginIt != DInfo.Decls.begin() &&
7430 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7431 ->isTopLevelDeclInObjCContainer())
7432 --BeginIt;
7433
7434 ArrayRef<serialization::LocalDeclID>::iterator
7435 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7436 EndLoc, DIDComp);
7437 if (EndIt != DInfo.Decls.end())
7438 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007439
Guy Benyei11169dd2012-12-18 14:30:41 +00007440 for (ArrayRef<serialization::LocalDeclID>::iterator
7441 DIt = BeginIt; DIt != EndIt; ++DIt)
7442 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7443}
7444
Richard Smith9ce12e32013-02-07 03:30:24 +00007445bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007446ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7447 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007448 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007449 "DeclContext has no visible decls in storage");
7450 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007451 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007452
Richard Smithd88a7f12015-09-01 20:35:42 +00007453 auto It = Lookups.find(DC);
7454 if (It == Lookups.end())
7455 return false;
7456
Richard Smith8c913ec2014-08-14 02:21:01 +00007457 Deserializing LookupResults(this);
7458
Richard Smithd88a7f12015-09-01 20:35:42 +00007459 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007460 SmallVector<NamedDecl *, 64> Decls;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007461 for (DeclID ID : It->second.Table.find(Name)) {
7462 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007463 if (ND->getDeclName() == Name)
7464 Decls.push_back(ND);
7465 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007466
Guy Benyei11169dd2012-12-18 14:30:41 +00007467 ++NumVisibleDeclContextsRead;
7468 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007469 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007470}
7471
Guy Benyei11169dd2012-12-18 14:30:41 +00007472void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7473 if (!DC->hasExternalVisibleStorage())
7474 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007475
7476 auto It = Lookups.find(DC);
7477 assert(It != Lookups.end() &&
7478 "have external visible storage but no lookup tables");
7479
Craig Topper79be4cd2013-07-05 04:33:53 +00007480 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007481
Vedant Kumar48b4f762018-04-14 01:40:48 +00007482 for (DeclID ID : It->second.Table.findAll()) {
7483 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
Richard Smithd88a7f12015-09-01 20:35:42 +00007484 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007485 }
7486
Guy Benyei11169dd2012-12-18 14:30:41 +00007487 ++NumVisibleDeclContextsRead;
7488
Vedant Kumar48b4f762018-04-14 01:40:48 +00007489 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
7490 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7491 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007492 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7493}
7494
Richard Smithd88a7f12015-09-01 20:35:42 +00007495const serialization::reader::DeclContextLookupTable *
7496ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7497 auto I = Lookups.find(Primary);
7498 return I == Lookups.end() ? nullptr : &I->second;
7499}
7500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007501/// Under non-PCH compilation the consumer receives the objc methods
Guy Benyei11169dd2012-12-18 14:30:41 +00007502/// before receiving the implementation, and codegen depends on this.
7503/// We simulate this by deserializing and passing to consumer the methods of the
7504/// implementation before passing the deserialized implementation decl.
7505static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7506 ASTConsumer *Consumer) {
7507 assert(ImplD && Consumer);
7508
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007509 for (auto *I : ImplD->methods())
7510 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007511
7512 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7513}
7514
Guy Benyei11169dd2012-12-18 14:30:41 +00007515void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007516 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +00007517 PassObjCImplDeclToConsumer(ImplD, Consumer);
7518 else
7519 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7520}
7521
7522void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7523 this->Consumer = Consumer;
7524
Richard Smith9e2341d2015-03-23 03:25:59 +00007525 if (Consumer)
7526 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007527
7528 if (DeserializationListener)
7529 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007530}
7531
7532void ASTReader::PrintStats() {
7533 std::fprintf(stderr, "*** AST File Statistics:\n");
7534
7535 unsigned NumTypesLoaded
7536 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7537 QualType());
7538 unsigned NumDeclsLoaded
7539 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007540 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007541 unsigned NumIdentifiersLoaded
7542 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7543 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007544 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007545 unsigned NumMacrosLoaded
7546 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7547 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007548 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007549 unsigned NumSelectorsLoaded
7550 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7551 SelectorsLoaded.end(),
7552 Selector());
7553
7554 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7555 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7556 NumSLocEntriesRead, TotalNumSLocEntries,
7557 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7558 if (!TypesLoaded.empty())
7559 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7560 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7561 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7562 if (!DeclsLoaded.empty())
7563 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7564 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7565 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7566 if (!IdentifiersLoaded.empty())
7567 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7568 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7569 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7570 if (!MacrosLoaded.empty())
7571 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7572 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7573 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7574 if (!SelectorsLoaded.empty())
7575 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7576 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7577 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7578 if (TotalNumStatements)
7579 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7580 NumStatementsRead, TotalNumStatements,
7581 ((float)NumStatementsRead/TotalNumStatements * 100));
7582 if (TotalNumMacros)
7583 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7584 NumMacrosRead, TotalNumMacros,
7585 ((float)NumMacrosRead/TotalNumMacros * 100));
7586 if (TotalLexicalDeclContexts)
7587 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7588 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7589 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7590 * 100));
7591 if (TotalVisibleDeclContexts)
7592 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7593 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7594 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7595 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007596 if (TotalNumMethodPoolEntries)
Guy Benyei11169dd2012-12-18 14:30:41 +00007597 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7598 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7599 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7600 * 100));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007601 if (NumMethodPoolLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007602 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7603 NumMethodPoolHits, NumMethodPoolLookups,
7604 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007605 if (NumMethodPoolTableLookups)
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007606 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7607 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7608 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7609 * 100.0));
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007610 if (NumIdentifierLookupHits)
Douglas Gregor00a50f72013-01-25 00:38:33 +00007611 std::fprintf(stderr,
7612 " %u / %u identifier table lookups succeeded (%f%%)\n",
7613 NumIdentifierLookupHits, NumIdentifierLookups,
7614 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
Douglas Gregor00a50f72013-01-25 00:38:33 +00007615
Douglas Gregore060e572013-01-25 01:03:03 +00007616 if (GlobalIndex) {
7617 std::fprintf(stderr, "\n");
7618 GlobalIndex->printStats();
7619 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007620
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 std::fprintf(stderr, "\n");
7622 dump();
7623 std::fprintf(stderr, "\n");
7624}
7625
7626template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007627LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007628dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007629 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007630 InitialCapacity> &Map) {
7631 if (Map.begin() == Map.end())
7632 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007633
Vedant Kumar48b4f762018-04-14 01:40:48 +00007634 using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
7635
Guy Benyei11169dd2012-12-18 14:30:41 +00007636 llvm::errs() << Name << ":\n";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007637 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
7638 I != IEnd; ++I) {
7639 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7640 << "\n";
7641 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007642}
7643
Yaron Kerencdae9412016-01-29 19:38:18 +00007644LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007645 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7646 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7647 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7648 dumpModuleIDMap("Global type map", GlobalTypeMap);
7649 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7650 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7651 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7652 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7653 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007654 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007655 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007656
Guy Benyei11169dd2012-12-18 14:30:41 +00007657 llvm::errs() << "\n*** PCH/Modules Loaded:";
Vedant Kumar48b4f762018-04-14 01:40:48 +00007658 for (ModuleFile &M : ModuleMgr)
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007659 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007660}
7661
7662/// Return the amount of memory used by memory buffers, breaking down
7663/// by heap-backed versus mmap'ed memory.
7664void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007665 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007666 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007667 size_t bytes = buf->getBufferSize();
7668 switch (buf->getBufferKind()) {
7669 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7670 sizes.malloc_bytes += bytes;
7671 break;
7672 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7673 sizes.mmap_bytes += bytes;
7674 break;
7675 }
7676 }
7677 }
7678}
7679
7680void ASTReader::InitializeSema(Sema &S) {
7681 SemaObj = &S;
7682 S.addExternalSource(this);
7683
7684 // Makes sure any declarations that were deserialized "too early"
7685 // still get added to the identifier's declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00007686 for (uint64_t ID : PreloadedDeclIDs) {
7687 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
Ben Langmuir5418f402014-09-10 21:29:41 +00007688 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007689 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007690 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007691
Richard Smith3d8e97e2013-10-18 06:54:39 +00007692 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007693 if (!FPPragmaOptions.empty()) {
7694 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007695 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007696 }
7697
Yaxun Liu5b746652016-12-18 05:18:55 +00007698 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7699 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7700 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007701
7702 UpdateSema();
7703}
7704
7705void ASTReader::UpdateSema() {
7706 assert(SemaObj && "no Sema to update");
7707
7708 // Load the offsets of the declarations that Sema references.
7709 // They will be lazily deserialized when needed.
7710 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007711 assert(SemaDeclRefs.size() % 3 == 0);
7712 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007713 if (!SemaObj->StdNamespace)
7714 SemaObj->StdNamespace = SemaDeclRefs[I];
7715 if (!SemaObj->StdBadAlloc)
7716 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007717 if (!SemaObj->StdAlignValT)
7718 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007719 }
7720 SemaDeclRefs.clear();
7721 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007722
Nico Weber779355f2016-03-02 23:22:00 +00007723 // Update the state of pragmas. Use the same API as if we had encountered the
7724 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007725 if(OptimizeOffPragmaLocation.isValid())
7726 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007727 if (PragmaMSStructState != -1)
7728 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007729 if (PointersToMembersPragmaLocation.isValid()) {
7730 SemaObj->ActOnPragmaMSPointersToMembers(
7731 (LangOptions::PragmaMSPointersToMembersKind)
7732 PragmaMSPointersToMembersState,
7733 PointersToMembersPragmaLocation);
7734 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007735 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007736
7737 if (PragmaPackCurrentValue) {
7738 // The bottom of the stack might have a default value. It must be adjusted
7739 // to the current value to ensure that the packing state is preserved after
7740 // popping entries that were included/imported from a PCH/module.
7741 bool DropFirst = false;
7742 if (!PragmaPackStack.empty() &&
7743 PragmaPackStack.front().Location.isInvalid()) {
7744 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7745 "Expected a default alignment value");
7746 SemaObj->PackStack.Stack.emplace_back(
7747 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007748 SemaObj->PackStack.CurrentPragmaLocation,
7749 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007750 DropFirst = true;
7751 }
7752 for (const auto &Entry :
7753 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7754 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007755 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007756 if (PragmaPackCurrentLocation.isInvalid()) {
7757 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7758 "Expected a default alignment value");
7759 // Keep the current values.
7760 } else {
7761 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7762 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7763 }
7764 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007765}
7766
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007767IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007768 // Note that we are loading an identifier.
7769 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007770
Douglas Gregor7211ac12013-01-25 23:32:03 +00007771 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007772 NumIdentifierLookups,
7773 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007774
7775 // We don't need to do identifier table lookups in C++ modules (we preload
7776 // all interesting declarations, and don't need to use the scope for name
7777 // lookups). Perform the lookup in PCH files, though, since we don't build
7778 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007779 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007780 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007781 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007782 break;
7783 } else {
7784 // If there is a global index, look there first to determine which modules
7785 // provably do not have any results for this identifier.
7786 GlobalModuleIndex::HitSet Hits;
7787 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7788 if (!loadGlobalIndex()) {
7789 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7790 HitsPtr = &Hits;
7791 }
7792 }
7793
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007794 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007795 }
7796
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 IdentifierInfo *II = Visitor.getIdentifierInfo();
7798 markIdentifierUpToDate(II);
7799 return II;
7800}
7801
7802namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007803
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007804 /// An identifier-lookup iterator that enumerates all of the
Guy Benyei11169dd2012-12-18 14:30:41 +00007805 /// identifiers stored within a set of AST files.
7806 class ASTIdentifierIterator : public IdentifierIterator {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007807 /// The AST reader whose identifiers are being enumerated.
Guy Benyei11169dd2012-12-18 14:30:41 +00007808 const ASTReader &Reader;
7809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007810 /// The current index into the chain of AST files stored in
Guy Benyei11169dd2012-12-18 14:30:41 +00007811 /// the AST reader.
7812 unsigned Index;
7813
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007814 /// The current position within the identifier lookup table
Guy Benyei11169dd2012-12-18 14:30:41 +00007815 /// of the current AST file.
7816 ASTIdentifierLookupTable::key_iterator Current;
7817
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007818 /// The end position within the identifier lookup table of
Guy Benyei11169dd2012-12-18 14:30:41 +00007819 /// the current AST file.
7820 ASTIdentifierLookupTable::key_iterator End;
7821
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007822 /// Whether to skip any modules in the ASTReader.
Ben Langmuir537c5b52016-05-04 00:53:13 +00007823 bool SkipModules;
7824
Guy Benyei11169dd2012-12-18 14:30:41 +00007825 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007826 explicit ASTIdentifierIterator(const ASTReader &Reader,
7827 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007828
Craig Topper3e89dfe2014-03-13 02:13:41 +00007829 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007830 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007831
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007832} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007833
Ben Langmuir537c5b52016-05-04 00:53:13 +00007834ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7835 bool SkipModules)
7836 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007837}
7838
7839StringRef ASTIdentifierIterator::Next() {
7840 while (Current == End) {
7841 // If we have exhausted all of our AST files, we're done.
7842 if (Index == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007843 return StringRef();
Guy Benyei11169dd2012-12-18 14:30:41 +00007844
7845 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007846 ModuleFile &F = Reader.ModuleMgr[Index];
7847 if (SkipModules && F.isModule())
7848 continue;
7849
Vedant Kumar48b4f762018-04-14 01:40:48 +00007850 ASTIdentifierLookupTable *IdTable =
7851 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007852 Current = IdTable->key_begin();
7853 End = IdTable->key_end();
7854 }
7855
7856 // We have any identifiers remaining in the current AST file; return
7857 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007858 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007859 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007860 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007861}
7862
Ben Langmuir537c5b52016-05-04 00:53:13 +00007863namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007864
Ben Langmuir537c5b52016-05-04 00:53:13 +00007865/// A utility for appending two IdentifierIterators.
7866class ChainedIdentifierIterator : public IdentifierIterator {
7867 std::unique_ptr<IdentifierIterator> Current;
7868 std::unique_ptr<IdentifierIterator> Queued;
7869
7870public:
7871 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7872 std::unique_ptr<IdentifierIterator> Second)
7873 : Current(std::move(First)), Queued(std::move(Second)) {}
7874
7875 StringRef Next() override {
7876 if (!Current)
Vedant Kumar48b4f762018-04-14 01:40:48 +00007877 return StringRef();
Ben Langmuir537c5b52016-05-04 00:53:13 +00007878
7879 StringRef result = Current->Next();
7880 if (!result.empty())
7881 return result;
7882
7883 // Try the queued iterator, which may itself be empty.
7884 Current.reset();
7885 std::swap(Current, Queued);
7886 return Next();
7887 }
7888};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007889
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007890} // namespace
Ben Langmuir537c5b52016-05-04 00:53:13 +00007891
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007892IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007893 if (!loadGlobalIndex()) {
7894 std::unique_ptr<IdentifierIterator> ReaderIter(
7895 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7896 std::unique_ptr<IdentifierIterator> ModulesIter(
7897 GlobalIndex->createIdentifierIterator());
7898 return new ChainedIdentifierIterator(std::move(ReaderIter),
7899 std::move(ModulesIter));
7900 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007901
Guy Benyei11169dd2012-12-18 14:30:41 +00007902 return new ASTIdentifierIterator(*this);
7903}
7904
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007905namespace clang {
7906namespace serialization {
7907
Guy Benyei11169dd2012-12-18 14:30:41 +00007908 class ReadMethodPoolVisitor {
7909 ASTReader &Reader;
7910 Selector Sel;
7911 unsigned PriorGeneration;
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007912 unsigned InstanceBits = 0;
7913 unsigned FactoryBits = 0;
7914 bool InstanceHasMoreThanOneDecl = false;
7915 bool FactoryHasMoreThanOneDecl = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007916 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7917 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007918
7919 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007920 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007921 unsigned PriorGeneration)
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007922 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007923
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007924 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007925 if (!M.SelectorLookupTable)
7926 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007927
Guy Benyei11169dd2012-12-18 14:30:41 +00007928 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007929 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007930 return true;
7931
Richard Smithbdf2d932015-07-30 03:37:16 +00007932 ++Reader.NumMethodPoolTableLookups;
Vedant Kumar48b4f762018-04-14 01:40:48 +00007933 ASTSelectorLookupTable *PoolTable
7934 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007935 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007936 if (Pos == PoolTable->end())
7937 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007938
Richard Smithbdf2d932015-07-30 03:37:16 +00007939 ++Reader.NumMethodPoolTableHits;
7940 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007941 // FIXME: Not quite happy with the statistics here. We probably should
7942 // disable this tracking when called via LoadSelector.
7943 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007944 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007945 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007946 if (Reader.DeserializationListener)
7947 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007948
Richard Smithbdf2d932015-07-30 03:37:16 +00007949 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7950 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7951 InstanceBits = Data.InstanceBits;
7952 FactoryBits = Data.FactoryBits;
7953 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7954 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007955 return true;
7956 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007957
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007958 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007959 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7960 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007961 }
7962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007963 /// Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007964 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007965 return FactoryMethods;
7966 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007967
7968 unsigned getInstanceBits() const { return InstanceBits; }
7969 unsigned getFactoryBits() const { return FactoryBits; }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007970
Nico Weberff4b35e2014-12-27 22:14:15 +00007971 bool instanceHasMoreThanOneDecl() const {
7972 return InstanceHasMoreThanOneDecl;
7973 }
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007974
Nico Weberff4b35e2014-12-27 22:14:15 +00007975 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007976 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007977
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00007978} // namespace serialization
7979} // namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007981/// Add the given set of methods to the method list.
Guy Benyei11169dd2012-12-18 14:30:41 +00007982static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7983 ObjCMethodList &List) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00007984 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7985 S.addMethodToGlobalList(&List, Methods[I]);
7986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007987}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007988
Guy Benyei11169dd2012-12-18 14:30:41 +00007989void ASTReader::ReadMethodPool(Selector Sel) {
7990 // Get the selector generation and update it to the current generation.
7991 unsigned &Generation = SelectorGeneration[Sel];
7992 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007993 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007994 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007995
Guy Benyei11169dd2012-12-18 14:30:41 +00007996 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007997 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007998 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007999 ModuleMgr.visit(Visitor);
8000
Guy Benyei11169dd2012-12-18 14:30:41 +00008001 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008002 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00008003 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00008004
8005 ++NumMethodPoolHits;
8006
Guy Benyei11169dd2012-12-18 14:30:41 +00008007 if (!getSema())
8008 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008009
Guy Benyei11169dd2012-12-18 14:30:41 +00008010 Sema &S = *getSema();
8011 Sema::GlobalMethodPool::iterator Pos
8012 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00008013
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008014 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008015 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00008016 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00008017 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00008018
8019 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
8020 // when building a module we keep every method individually and may need to
8021 // update hasMoreThanOneDecl as we add the methods.
8022 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
8023 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008024}
8025
Manman Rena0f31a02016-04-29 19:04:05 +00008026void ASTReader::updateOutOfDateSelector(Selector Sel) {
8027 if (SelectorOutOfDate[Sel])
8028 ReadMethodPool(Sel);
8029}
8030
Guy Benyei11169dd2012-12-18 14:30:41 +00008031void ASTReader::ReadKnownNamespaces(
8032 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
8033 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008034
Vedant Kumar48b4f762018-04-14 01:40:48 +00008035 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
8036 if (NamespaceDecl *Namespace
8037 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 Namespaces.push_back(Namespace);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008039 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008040}
8041
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008042void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00008043 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008044 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008045 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00008046 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00008047 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00008048 Undefined.insert(std::make_pair(D, Loc));
8049 }
8050}
Nick Lewycky8334af82013-01-26 00:35:08 +00008051
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008052void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
8053 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
8054 Exprs) {
8055 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008056 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00008057 uint64_t Count = DelayedDeleteExprs[Idx++];
8058 for (uint64_t C = 0; C < Count; ++C) {
8059 SourceLocation DeleteLoc =
8060 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
8061 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
8062 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
8063 }
8064 }
8065}
8066
Guy Benyei11169dd2012-12-18 14:30:41 +00008067void ASTReader::ReadTentativeDefinitions(
8068 SmallVectorImpl<VarDecl *> &TentativeDefs) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008069 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
8070 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008071 if (Var)
8072 TentativeDefs.push_back(Var);
8073 }
8074 TentativeDefinitions.clear();
8075}
8076
8077void ASTReader::ReadUnusedFileScopedDecls(
8078 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008079 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
8080 DeclaratorDecl *D
8081 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008082 if (D)
8083 Decls.push_back(D);
8084 }
8085 UnusedFileScopedDecls.clear();
8086}
8087
8088void ASTReader::ReadDelegatingConstructors(
8089 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008090 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
8091 CXXConstructorDecl *D
8092 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008093 if (D)
8094 Decls.push_back(D);
8095 }
8096 DelegatingCtorDecls.clear();
8097}
8098
8099void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008100 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
8101 TypedefNameDecl *D
8102 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008103 if (D)
8104 Decls.push_back(D);
8105 }
8106 ExtVectorDecls.clear();
8107}
8108
Nico Weber72889432014-09-06 01:25:55 +00008109void ASTReader::ReadUnusedLocalTypedefNameCandidates(
8110 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008111 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
8112 ++I) {
8113 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
8114 GetDecl(UnusedLocalTypedefNameCandidates[I]));
Nico Weber72889432014-09-06 01:25:55 +00008115 if (D)
8116 Decls.insert(D);
8117 }
8118 UnusedLocalTypedefNameCandidates.clear();
8119}
8120
Guy Benyei11169dd2012-12-18 14:30:41 +00008121void ASTReader::ReadReferencedSelectors(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008122 SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008123 if (ReferencedSelectorsData.empty())
8124 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008125
Guy Benyei11169dd2012-12-18 14:30:41 +00008126 // If there are @selector references added them to its pool. This is for
8127 // implementation of -Wselector.
8128 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8129 unsigned I = 0;
8130 while (I < DataSize) {
8131 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8132 SourceLocation SelLoc
8133 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8134 Sels.push_back(std::make_pair(Sel, SelLoc));
8135 }
8136 ReferencedSelectorsData.clear();
8137}
8138
8139void ASTReader::ReadWeakUndeclaredIdentifiers(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008140 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008141 if (WeakUndeclaredIdentifiers.empty())
8142 return;
8143
8144 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008145 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008147 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8149 SourceLocation Loc
8150 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8151 bool Used = WeakUndeclaredIdentifiers[I++];
8152 WeakInfo WI(AliasId, Loc);
8153 WI.setUsed(Used);
8154 WeakIDs.push_back(std::make_pair(WeakId, WI));
8155 }
8156 WeakUndeclaredIdentifiers.clear();
8157}
8158
8159void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8160 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8161 ExternalVTableUse VT;
8162 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8163 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8164 VT.DefinitionRequired = VTableUses[Idx++];
8165 VTables.push_back(VT);
8166 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008167
Guy Benyei11169dd2012-12-18 14:30:41 +00008168 VTableUses.clear();
8169}
8170
8171void ASTReader::ReadPendingInstantiations(
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008172 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008173 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008174 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00008175 SourceLocation Loc
8176 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8177
8178 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008179 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008180 PendingInstantiations.clear();
8181}
8182
Richard Smithe40f2ba2013-08-07 21:41:30 +00008183void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008184 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8185 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008186 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8187 /* In loop */) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008188 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008189
Justin Lebar28f09c52016-10-10 16:26:08 +00008190 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008191 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8192
8193 ModuleFile *F = getOwningModuleFile(LT->D);
8194 assert(F && "No module");
8195
8196 unsigned TokN = LateParsedTemplates[Idx++];
8197 LT->Toks.reserve(TokN);
8198 for (unsigned T = 0; T < TokN; ++T)
8199 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8200
Justin Lebar28f09c52016-10-10 16:26:08 +00008201 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008202 }
8203
8204 LateParsedTemplates.clear();
8205}
8206
Guy Benyei11169dd2012-12-18 14:30:41 +00008207void ASTReader::LoadSelector(Selector Sel) {
8208 // It would be complicated to avoid reading the methods anyway. So don't.
8209 ReadMethodPool(Sel);
8210}
8211
8212void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8213 assert(ID && "Non-zero identifier ID required");
8214 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8215 IdentifiersLoaded[ID - 1] = II;
8216 if (DeserializationListener)
8217 DeserializationListener->IdentifierRead(ID, II);
8218}
8219
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008220/// Set the globally-visible declarations associated with the given
Guy Benyei11169dd2012-12-18 14:30:41 +00008221/// identifier.
8222///
8223/// If the AST reader is currently in a state where the given declaration IDs
8224/// cannot safely be resolved, they are queued until it is safe to resolve
8225/// them.
8226///
8227/// \param II an IdentifierInfo that refers to one or more globally-visible
8228/// declarations.
8229///
8230/// \param DeclIDs the set of declaration IDs with the name @p II that are
8231/// visible at global scope.
8232///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008233/// \param Decls if non-null, this vector will be populated with the set of
8234/// deserialized declarations. These declarations will not be pushed into
8235/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008236void
8237ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8238 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008239 SmallVectorImpl<Decl *> *Decls) {
8240 if (NumCurrentElementsDeserializing && !Decls) {
8241 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 return;
8243 }
8244
Vedant Kumar48b4f762018-04-14 01:40:48 +00008245 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008246 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008247 // Queue this declaration so that it will be added to the
8248 // translation unit scope and identifier's declaration chain
8249 // once a Sema object is known.
Vedant Kumar48b4f762018-04-14 01:40:48 +00008250 PreloadedDeclIDs.push_back(DeclIDs[I]);
Ben Langmuir5418f402014-09-10 21:29:41 +00008251 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008252 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008253
Vedant Kumar48b4f762018-04-14 01:40:48 +00008254 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
Ben Langmuir5418f402014-09-10 21:29:41 +00008255
8256 // If we're simply supposed to record the declarations, do so now.
8257 if (Decls) {
8258 Decls->push_back(D);
8259 continue;
8260 }
8261
8262 // Introduce this declaration into the translation-unit scope
8263 // and add it to the declaration chain for this identifier, so
8264 // that (unqualified) name lookup will find it.
8265 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008266 }
8267}
8268
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008269IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008270 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008271 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008272
8273 if (IdentifiersLoaded.empty()) {
8274 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008275 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008276 }
8277
8278 ID -= 1;
8279 if (!IdentifiersLoaded[ID]) {
8280 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8281 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8282 ModuleFile *M = I->second;
8283 unsigned Index = ID - M->BaseIdentifierID;
8284 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8285
8286 // All of the strings in the AST file are preceded by a 16-bit length.
8287 // Extract that 16-bit length to avoid having to execute strlen().
8288 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8289 // unsigned integers. This is important to avoid integer overflow when
8290 // we cast them to 'unsigned'.
8291 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8292 unsigned StrLen = (((unsigned) StrLenPtr[0])
8293 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008294 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8295 IdentifiersLoaded[ID] = &II;
8296 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008297 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008298 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 }
8300
8301 return IdentifiersLoaded[ID];
8302}
8303
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008304IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8305 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008306}
8307
8308IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8309 if (LocalID < NUM_PREDEF_IDENT_IDS)
8310 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008311
Richard Smith37a93df2017-02-18 00:32:02 +00008312 if (!M.ModuleOffsetMap.empty())
8313 ReadModuleOffsetMap(M);
8314
Guy Benyei11169dd2012-12-18 14:30:41 +00008315 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8316 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008317 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008318 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008319
Guy Benyei11169dd2012-12-18 14:30:41 +00008320 return LocalID + I->second;
8321}
8322
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008323MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008324 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008325 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008326
8327 if (MacrosLoaded.empty()) {
8328 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008329 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008330 }
8331
8332 ID -= NUM_PREDEF_MACRO_IDS;
8333 if (!MacrosLoaded[ID]) {
8334 GlobalMacroMapType::iterator I
8335 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8336 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8337 ModuleFile *M = I->second;
8338 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008339 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008340
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008341 if (DeserializationListener)
8342 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8343 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008344 }
8345
8346 return MacrosLoaded[ID];
8347}
8348
8349MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8350 if (LocalID < NUM_PREDEF_MACRO_IDS)
8351 return LocalID;
8352
Richard Smith37a93df2017-02-18 00:32:02 +00008353 if (!M.ModuleOffsetMap.empty())
8354 ReadModuleOffsetMap(M);
8355
Guy Benyei11169dd2012-12-18 14:30:41 +00008356 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8357 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8358 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8359
8360 return LocalID + I->second;
8361}
8362
8363serialization::SubmoduleID
8364ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8365 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8366 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008367
Richard Smith37a93df2017-02-18 00:32:02 +00008368 if (!M.ModuleOffsetMap.empty())
8369 ReadModuleOffsetMap(M);
8370
Guy Benyei11169dd2012-12-18 14:30:41 +00008371 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8372 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008373 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008374 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008375
Guy Benyei11169dd2012-12-18 14:30:41 +00008376 return LocalID + I->second;
8377}
8378
8379Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8380 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8381 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008382 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008384
Guy Benyei11169dd2012-12-18 14:30:41 +00008385 if (GlobalID > SubmodulesLoaded.size()) {
8386 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008387 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008389
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8391}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008392
8393Module *ASTReader::getModule(unsigned ID) {
8394 return getSubmodule(ID);
8395}
8396
Richard Smithd88a7f12015-09-01 20:35:42 +00008397ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8398 if (ID & 1) {
8399 // It's a module, look it up by submodule ID.
8400 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8401 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8402 } else {
8403 // It's a prefix (preamble, PCH, ...). Look it up by index.
8404 unsigned IndexFromEnd = ID >> 1;
8405 assert(IndexFromEnd && "got reference to unknown module file");
8406 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8407 }
8408}
8409
8410unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8411 if (!F)
8412 return 1;
8413
8414 // For a file representing a module, use the submodule ID of the top-level
8415 // module as the file ID. For any other kind of file, the number of such
8416 // files loaded beforehand will be the same on reload.
8417 // FIXME: Is this true even if we have an explicit module file and a PCH?
8418 if (F->isModule())
8419 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8420
8421 auto PCHModules = getModuleManager().pch_modules();
8422 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8423 assert(I != PCHModules.end() && "emitting reference to unknown file");
8424 return (I - PCHModules.end()) << 1;
8425}
8426
Adrian Prantl15bcf702015-06-30 17:39:43 +00008427llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8428ASTReader::getSourceDescriptor(unsigned ID) {
8429 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008430 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008431
8432 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008433 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008434 const auto &PCHChain = ModuleMgr.pch_modules();
8435 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008436 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008437 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008438 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8439 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8440 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008441 }
8442 return None;
8443}
8444
David Blaikie1ac9c982017-04-11 21:13:37 +00008445ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008446 auto I = DefinitionSource.find(FD);
8447 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008448 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008449 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008450}
8451
Guy Benyei11169dd2012-12-18 14:30:41 +00008452Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8453 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8454}
8455
8456Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8457 if (ID == 0)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008458 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008459
8460 if (ID > SelectorsLoaded.size()) {
8461 Error("selector ID out of range in AST file");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008462 return Selector();
Guy Benyei11169dd2012-12-18 14:30:41 +00008463 }
8464
Craig Toppera13603a2014-05-22 05:54:18 +00008465 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008466 // Load this selector from the selector table.
8467 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8468 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8469 ModuleFile &M = *I->second;
8470 ASTSelectorLookupTrait Trait(*this, M);
8471 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8472 SelectorsLoaded[ID - 1] =
8473 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8474 if (DeserializationListener)
8475 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8476 }
8477
8478 return SelectorsLoaded[ID - 1];
8479}
8480
8481Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8482 return DecodeSelector(ID);
8483}
8484
8485uint32_t ASTReader::GetNumExternalSelectors() {
8486 // ID 0 (the null selector) is considered an external selector.
8487 return getTotalNumSelectors() + 1;
8488}
8489
8490serialization::SelectorID
8491ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8492 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8493 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008494
Richard Smith37a93df2017-02-18 00:32:02 +00008495 if (!M.ModuleOffsetMap.empty())
8496 ReadModuleOffsetMap(M);
8497
Guy Benyei11169dd2012-12-18 14:30:41 +00008498 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8499 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008500 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008501 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008502
Guy Benyei11169dd2012-12-18 14:30:41 +00008503 return LocalID + I->second;
8504}
8505
8506DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008507ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008508 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008509 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008510 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008511 switch (Kind) {
8512 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008513 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008514
8515 case DeclarationName::ObjCZeroArgSelector:
8516 case DeclarationName::ObjCOneArgSelector:
8517 case DeclarationName::ObjCMultiArgSelector:
8518 return DeclarationName(ReadSelector(F, Record, Idx));
8519
8520 case DeclarationName::CXXConstructorName:
8521 return Context.DeclarationNames.getCXXConstructorName(
8522 Context.getCanonicalType(readType(F, Record, Idx)));
8523
8524 case DeclarationName::CXXDestructorName:
8525 return Context.DeclarationNames.getCXXDestructorName(
8526 Context.getCanonicalType(readType(F, Record, Idx)));
8527
Richard Smith35845152017-02-07 01:37:30 +00008528 case DeclarationName::CXXDeductionGuideName:
8529 return Context.DeclarationNames.getCXXDeductionGuideName(
8530 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8531
Guy Benyei11169dd2012-12-18 14:30:41 +00008532 case DeclarationName::CXXConversionFunctionName:
8533 return Context.DeclarationNames.getCXXConversionFunctionName(
8534 Context.getCanonicalType(readType(F, Record, Idx)));
8535
8536 case DeclarationName::CXXOperatorName:
8537 return Context.DeclarationNames.getCXXOperatorName(
8538 (OverloadedOperatorKind)Record[Idx++]);
8539
8540 case DeclarationName::CXXLiteralOperatorName:
8541 return Context.DeclarationNames.getCXXLiteralOperatorName(
8542 GetIdentifierInfo(F, Record, Idx));
8543
8544 case DeclarationName::CXXUsingDirective:
8545 return DeclarationName::getUsingDirectiveName();
8546 }
8547
8548 llvm_unreachable("Invalid NameKind!");
8549}
8550
8551void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8552 DeclarationNameLoc &DNLoc,
8553 DeclarationName Name,
8554 const RecordData &Record, unsigned &Idx) {
8555 switch (Name.getNameKind()) {
8556 case DeclarationName::CXXConstructorName:
8557 case DeclarationName::CXXDestructorName:
8558 case DeclarationName::CXXConversionFunctionName:
8559 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8560 break;
8561
8562 case DeclarationName::CXXOperatorName:
8563 DNLoc.CXXOperatorName.BeginOpNameLoc
8564 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8565 DNLoc.CXXOperatorName.EndOpNameLoc
8566 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8567 break;
8568
8569 case DeclarationName::CXXLiteralOperatorName:
8570 DNLoc.CXXLiteralOperatorName.OpNameLoc
8571 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8572 break;
8573
8574 case DeclarationName::Identifier:
8575 case DeclarationName::ObjCZeroArgSelector:
8576 case DeclarationName::ObjCOneArgSelector:
8577 case DeclarationName::ObjCMultiArgSelector:
8578 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008579 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008580 break;
8581 }
8582}
8583
8584void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8585 DeclarationNameInfo &NameInfo,
8586 const RecordData &Record, unsigned &Idx) {
8587 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8588 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8589 DeclarationNameLoc DNLoc;
8590 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8591 NameInfo.setInfo(DNLoc);
8592}
8593
8594void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8595 const RecordData &Record, unsigned &Idx) {
8596 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8597 unsigned NumTPLists = Record[Idx++];
8598 Info.NumTemplParamLists = NumTPLists;
8599 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008600 Info.TemplParamLists =
8601 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008602 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008603 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8604 }
8605}
8606
8607TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008608ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008609 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008610 ASTContext &Context = getContext();
Vedant Kumar48b4f762018-04-14 01:40:48 +00008611 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008612 switch (Kind) {
8613 case TemplateName::Template:
8614 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8615
8616 case TemplateName::OverloadedTemplate: {
8617 unsigned size = Record[Idx++];
8618 UnresolvedSet<8> Decls;
8619 while (size--)
8620 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8621
8622 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8623 }
8624
8625 case TemplateName::QualifiedTemplate: {
8626 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8627 bool hasTemplKeyword = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008628 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008629 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8630 }
8631
8632 case TemplateName::DependentTemplate: {
8633 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8634 if (Record[Idx++]) // isIdentifier
8635 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008636 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008637 Idx));
8638 return Context.getDependentTemplateName(NNS,
8639 (OverloadedOperatorKind)Record[Idx++]);
8640 }
8641
8642 case TemplateName::SubstTemplateTemplateParm: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008643 TemplateTemplateParmDecl *param
8644 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8645 if (!param) return TemplateName();
8646 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8647 return Context.getSubstTemplateTemplateParm(param, replacement);
Guy Benyei11169dd2012-12-18 14:30:41 +00008648 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008649
Guy Benyei11169dd2012-12-18 14:30:41 +00008650 case TemplateName::SubstTemplateTemplateParmPack: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008651 TemplateTemplateParmDecl *Param
8652 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008653 if (!Param)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008654 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008655
Guy Benyei11169dd2012-12-18 14:30:41 +00008656 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8657 if (ArgPack.getKind() != TemplateArgument::Pack)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008658 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008659
Guy Benyei11169dd2012-12-18 14:30:41 +00008660 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8661 }
8662 }
8663
8664 llvm_unreachable("Unhandled template name kind!");
8665}
8666
Richard Smith2bb3c342015-08-09 01:05:31 +00008667TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8668 const RecordData &Record,
8669 unsigned &Idx,
8670 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008671 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008672 if (Canonicalize) {
8673 // The caller wants a canonical template argument. Sometimes the AST only
8674 // wants template arguments in canonical form (particularly as the template
8675 // argument lists of template specializations) so ensure we preserve that
8676 // canonical form across serialization.
8677 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8678 return Context.getCanonicalTemplateArgument(Arg);
8679 }
8680
Vedant Kumar48b4f762018-04-14 01:40:48 +00008681 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008682 switch (Kind) {
8683 case TemplateArgument::Null:
Vedant Kumar48b4f762018-04-14 01:40:48 +00008684 return TemplateArgument();
Guy Benyei11169dd2012-12-18 14:30:41 +00008685 case TemplateArgument::Type:
8686 return TemplateArgument(readType(F, Record, Idx));
8687 case TemplateArgument::Declaration: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008688 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008689 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008690 }
8691 case TemplateArgument::NullPtr:
8692 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8693 case TemplateArgument::Integral: {
8694 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8695 QualType T = readType(F, Record, Idx);
8696 return TemplateArgument(Context, Value, T);
8697 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008698 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008699 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8700 case TemplateArgument::TemplateExpansion: {
8701 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008702 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008703 if (unsigned NumExpansions = Record[Idx++])
8704 NumTemplateExpansions = NumExpansions - 1;
8705 return TemplateArgument(Name, NumTemplateExpansions);
8706 }
8707 case TemplateArgument::Expression:
8708 return TemplateArgument(ReadExpr(F));
8709 case TemplateArgument::Pack: {
8710 unsigned NumArgs = Record[Idx++];
Vedant Kumar48b4f762018-04-14 01:40:48 +00008711 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
Guy Benyei11169dd2012-12-18 14:30:41 +00008712 for (unsigned I = 0; I != NumArgs; ++I)
8713 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008714 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008715 }
8716 }
8717
8718 llvm_unreachable("Unhandled template argument kind!");
8719}
8720
8721TemplateParameterList *
8722ASTReader::ReadTemplateParameterList(ModuleFile &F,
8723 const RecordData &Record, unsigned &Idx) {
8724 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8725 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8726 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8727
8728 unsigned NumParams = Record[Idx++];
8729 SmallVector<NamedDecl *, 16> Params;
8730 Params.reserve(NumParams);
8731 while (NumParams--)
8732 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8733
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008734 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008735 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8736 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008737 return TemplateParams;
8738}
8739
8740void
8741ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008742ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008743 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008744 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008745 unsigned NumTemplateArgs = Record[Idx++];
8746 TemplArgs.reserve(NumTemplateArgs);
8747 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008748 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008749}
8750
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008751/// Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008752void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008753 const RecordData &Record, unsigned &Idx) {
8754 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008755 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008756 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008757 DeclID ID = ReadDeclID(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00008758 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008759 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008760 }
8761}
8762
8763CXXBaseSpecifier
8764ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8765 const RecordData &Record, unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008766 bool isVirtual = static_cast<bool>(Record[Idx++]);
8767 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8768 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8769 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008770 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8771 SourceRange Range = ReadSourceRange(F, Record, Idx);
8772 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008773 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008774 EllipsisLoc);
8775 Result.setInheritConstructors(inheritConstructors);
8776 return Result;
8777}
8778
Richard Smithc2bb8182015-03-24 06:36:48 +00008779CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008780ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8781 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008782 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008784 assert(NumInitializers && "wrote ctor initializers but have no inits");
Vedant Kumar48b4f762018-04-14 01:40:48 +00008785 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
Richard Smithc2bb8182015-03-24 06:36:48 +00008786 for (unsigned i = 0; i != NumInitializers; ++i) {
8787 TypeSourceInfo *TInfo = nullptr;
8788 bool IsBaseVirtual = false;
8789 FieldDecl *Member = nullptr;
8790 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008791
Vedant Kumar48b4f762018-04-14 01:40:48 +00008792 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008793 switch (Type) {
8794 case CTOR_INITIALIZER_BASE:
8795 TInfo = GetTypeSourceInfo(F, Record, Idx);
8796 IsBaseVirtual = Record[Idx++];
8797 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008798
Richard Smithc2bb8182015-03-24 06:36:48 +00008799 case CTOR_INITIALIZER_DELEGATING:
8800 TInfo = GetTypeSourceInfo(F, Record, Idx);
8801 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008802
Richard Smithc2bb8182015-03-24 06:36:48 +00008803 case CTOR_INITIALIZER_MEMBER:
8804 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8805 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008806
Richard Smithc2bb8182015-03-24 06:36:48 +00008807 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8808 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8809 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008810 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008811
8812 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8813 Expr *Init = ReadExpr(F);
8814 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8815 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008816
8817 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008818 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008819 BOMInit = new (Context)
8820 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8821 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008822 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008823 BOMInit = new (Context)
8824 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008825 else if (Member)
8826 BOMInit = new (Context)
8827 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8828 Init, RParenLoc);
8829 else
8830 BOMInit = new (Context)
8831 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8832 LParenLoc, Init, RParenLoc);
8833
Richard Smith418ed822016-12-14 19:45:03 +00008834 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008835 unsigned SourceOrder = Record[Idx++];
8836 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008837 }
8838
Richard Smithc2bb8182015-03-24 06:36:48 +00008839 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008840 }
8841
Richard Smithc2bb8182015-03-24 06:36:48 +00008842 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008843}
8844
8845NestedNameSpecifier *
8846ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8847 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008848 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008850 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008851 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008852 NestedNameSpecifier::SpecifierKind Kind
8853 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008854 switch (Kind) {
8855 case NestedNameSpecifier::Identifier: {
8856 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8857 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8858 break;
8859 }
8860
8861 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008862 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008863 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8864 break;
8865 }
8866
8867 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008868 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008869 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8870 break;
8871 }
8872
8873 case NestedNameSpecifier::TypeSpec:
8874 case NestedNameSpecifier::TypeSpecWithTemplate: {
8875 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8876 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008877 return nullptr;
8878
Guy Benyei11169dd2012-12-18 14:30:41 +00008879 bool Template = Record[Idx++];
8880 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8881 break;
8882 }
8883
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00008884 case NestedNameSpecifier::Global:
Guy Benyei11169dd2012-12-18 14:30:41 +00008885 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8886 // No associated value, and there can't be a prefix.
8887 break;
Nikola Smiljanic67860242014-09-26 00:28:20 +00008888
8889 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008890 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008891 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8892 break;
8893 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008894 }
8895 Prev = NNS;
8896 }
8897 return NNS;
8898}
8899
8900NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008901ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008902 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008903 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008904 unsigned N = Record[Idx++];
8905 NestedNameSpecifierLocBuilder Builder;
8906 for (unsigned I = 0; I != N; ++I) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008907 NestedNameSpecifier::SpecifierKind Kind
8908 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00008909 switch (Kind) {
8910 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008911 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008912 SourceRange Range = ReadSourceRange(F, Record, Idx);
8913 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8914 break;
8915 }
8916
8917 case NestedNameSpecifier::Namespace: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008918 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008919 SourceRange Range = ReadSourceRange(F, Record, Idx);
8920 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8921 break;
8922 }
8923
8924 case NestedNameSpecifier::NamespaceAlias: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008925 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008926 SourceRange Range = ReadSourceRange(F, Record, Idx);
8927 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8928 break;
8929 }
8930
8931 case NestedNameSpecifier::TypeSpec:
8932 case NestedNameSpecifier::TypeSpecWithTemplate: {
8933 bool Template = Record[Idx++];
8934 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8935 if (!T)
Vedant Kumar48b4f762018-04-14 01:40:48 +00008936 return NestedNameSpecifierLoc();
Guy Benyei11169dd2012-12-18 14:30:41 +00008937 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8938
8939 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008940 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008941 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8942 T->getTypeLoc(), ColonColonLoc);
8943 break;
8944 }
8945
8946 case NestedNameSpecifier::Global: {
8947 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8948 Builder.MakeGlobal(Context, ColonColonLoc);
8949 break;
8950 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008951
8952 case NestedNameSpecifier::Super: {
Vedant Kumar48b4f762018-04-14 01:40:48 +00008953 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
Nikola Smiljanic67860242014-09-26 00:28:20 +00008954 SourceRange Range = ReadSourceRange(F, Record, Idx);
8955 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8956 break;
8957 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008958 }
8959 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008960
Guy Benyei11169dd2012-12-18 14:30:41 +00008961 return Builder.getWithLocInContext(Context);
8962}
8963
8964SourceRange
8965ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8966 unsigned &Idx) {
8967 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8968 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8969 return SourceRange(beg, end);
8970}
8971
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008972/// Read an integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00008973llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8974 unsigned BitWidth = Record[Idx++];
8975 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8976 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8977 Idx += NumWords;
8978 return Result;
8979}
8980
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008981/// Read a signed integral value
Guy Benyei11169dd2012-12-18 14:30:41 +00008982llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8983 bool isUnsigned = Record[Idx++];
8984 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8985}
8986
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008987/// Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008988llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8989 const llvm::fltSemantics &Sem,
8990 unsigned &Idx) {
8991 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008992}
8993
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008994// Read a string
Guy Benyei11169dd2012-12-18 14:30:41 +00008995std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8996 unsigned Len = Record[Idx++];
8997 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8998 Idx += Len;
8999 return Result;
9000}
9001
Richard Smith7ed1bc92014-12-05 22:42:13 +00009002std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
9003 unsigned &Idx) {
9004 std::string Filename = ReadString(Record, Idx);
9005 ResolveImportedPath(F, Filename);
9006 return Filename;
9007}
9008
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009009VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00009010 unsigned &Idx) {
9011 unsigned Major = Record[Idx++];
9012 unsigned Minor = Record[Idx++];
9013 unsigned Subminor = Record[Idx++];
9014 if (Minor == 0)
9015 return VersionTuple(Major);
9016 if (Subminor == 0)
9017 return VersionTuple(Major, Minor - 1);
9018 return VersionTuple(Major, Minor - 1, Subminor - 1);
9019}
9020
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009021CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00009022 const RecordData &Record,
9023 unsigned &Idx) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009024 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00009025 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00009026}
9027
Richard Smith37a93df2017-02-18 00:32:02 +00009028DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00009029 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00009030}
9031
Richard Smith37a93df2017-02-18 00:32:02 +00009032DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00009033 return Diags.Report(Loc, DiagID);
9034}
9035
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009036/// Retrieve the identifier table associated with the
Guy Benyei11169dd2012-12-18 14:30:41 +00009037/// preprocessor.
9038IdentifierTable &ASTReader::getIdentifierTable() {
9039 return PP.getIdentifierTable();
9040}
9041
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009042/// Record that the given ID maps to the given switch-case
Guy Benyei11169dd2012-12-18 14:30:41 +00009043/// statement.
9044void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009045 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00009046 "Already have a SwitchCase with this ID");
9047 (*CurrSwitchCaseStmts)[ID] = SC;
9048}
9049
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009050/// Retrieve the switch-case statement with the given ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00009051SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00009052 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00009053 return (*CurrSwitchCaseStmts)[ID];
9054}
9055
9056void ASTReader::ClearSwitchCaseIDs() {
9057 CurrSwitchCaseStmts->clear();
9058}
9059
9060void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00009061 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00009062 std::vector<RawComment *> Comments;
Vedant Kumar48b4f762018-04-14 01:40:48 +00009063 for (SmallVectorImpl<std::pair<BitstreamCursor,
9064 serialization::ModuleFile *>>::iterator
9065 I = CommentsCursors.begin(),
9066 E = CommentsCursors.end();
9067 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009068 Comments.clear();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009069 BitstreamCursor &Cursor = I->first;
9070 serialization::ModuleFile &F = *I->second;
Guy Benyei11169dd2012-12-18 14:30:41 +00009071 SavedStreamPosition SavedPosition(Cursor);
9072
9073 RecordData Record;
9074 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009075 llvm::BitstreamEntry Entry =
9076 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009077
Chris Lattner7fb3bef2013-01-20 00:56:42 +00009078 switch (Entry.Kind) {
9079 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
9080 case llvm::BitstreamEntry::Error:
9081 Error("malformed block record in AST file");
9082 return;
9083 case llvm::BitstreamEntry::EndBlock:
9084 goto NextCursor;
9085 case llvm::BitstreamEntry::Record:
9086 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00009087 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00009088 }
9089
9090 // Read a record.
9091 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00009092 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009093 case COMMENTS_RAW_COMMENT: {
9094 unsigned Idx = 0;
9095 SourceRange SR = ReadSourceRange(F, Record, Idx);
Vedant Kumar48b4f762018-04-14 01:40:48 +00009096 RawComment::CommentKind Kind =
9097 (RawComment::CommentKind) Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00009098 bool IsTrailingComment = Record[Idx++];
9099 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00009100 Comments.push_back(new (Context) RawComment(
David L. Jones13d5a872018-03-02 00:07:45 +00009101 SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
Guy Benyei11169dd2012-12-18 14:30:41 +00009102 break;
9103 }
9104 }
9105 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009106 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00009107 // De-serialized SourceLocations get negative FileIDs for other modules,
9108 // potentially invalidating the original order. Sort it again.
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +00009109 llvm::sort(Comments.begin(), Comments.end(),
9110 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00009111 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00009112 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009113}
9114
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00009115void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
9116 bool IncludeSystem, bool Complain,
9117 llvm::function_ref<void(const serialization::InputFile &IF,
9118 bool isSystem)> Visitor) {
9119 unsigned NumUserInputs = MF.NumUserInputFiles;
9120 unsigned NumInputs = MF.InputFilesLoaded.size();
9121 assert(NumUserInputs <= NumInputs);
9122 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9123 for (unsigned I = 0; I < N; ++I) {
9124 bool IsSystem = I >= NumUserInputs;
9125 InputFile IF = getInputFile(MF, I+1, Complain);
9126 Visitor(IF, IsSystem);
9127 }
9128}
9129
Richard Smithf3f84612017-06-29 02:19:42 +00009130void ASTReader::visitTopLevelModuleMaps(
9131 serialization::ModuleFile &MF,
9132 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9133 unsigned NumInputs = MF.InputFilesLoaded.size();
9134 for (unsigned I = 0; I < NumInputs; ++I) {
9135 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9136 if (IFI.TopLevelModuleMap)
9137 // FIXME: This unnecessarily re-reads the InputFileInfo.
9138 if (auto *FE = getInputFile(MF, I + 1).getFile())
9139 Visitor(FE);
9140 }
9141}
9142
Richard Smithcd45dbc2014-04-19 03:48:30 +00009143std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9144 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009145 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009146 return M->getFullModuleName();
9147
9148 // Otherwise, use the name of the top-level module the decl is within.
9149 if (ModuleFile *M = getOwningModuleFile(D))
9150 return M->ModuleName;
9151
9152 // Not from a module.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009153 return {};
Richard Smithcd45dbc2014-04-19 03:48:30 +00009154}
9155
Guy Benyei11169dd2012-12-18 14:30:41 +00009156void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00009157 while (!PendingIdentifierInfos.empty() ||
9158 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009159 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009160 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009161 // If any identifiers with corresponding top-level declarations have
9162 // been loaded, load those declarations now.
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +00009163 using TopLevelDeclsMap =
9164 llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
Craig Topper79be4cd2013-07-05 04:33:53 +00009165 TopLevelDeclsMap TopLevelDecls;
9166
Guy Benyei11169dd2012-12-18 14:30:41 +00009167 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009168 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009169 SmallVector<uint32_t, 4> DeclIDs =
9170 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009171 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009172
9173 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009174 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009175
Richard Smith851072e2014-05-19 20:59:20 +00009176 // For each decl chain that we wanted to complete while deserializing, mark
9177 // it as "still needs to be completed".
Vedant Kumar48b4f762018-04-14 01:40:48 +00009178 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9179 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9180 }
Richard Smith851072e2014-05-19 20:59:20 +00009181 PendingIncompleteDeclChains.clear();
9182
Guy Benyei11169dd2012-12-18 14:30:41 +00009183 // Load pending declaration chains.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009184 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
9185 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009186 PendingDeclChains.clear();
9187
Douglas Gregor6168bd22013-02-18 15:53:43 +00009188 // Make the most recent of the top-level declarations visible.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009189 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9190 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
9191 IdentifierInfo *II = TLD->first;
9192 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
9193 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009194 }
9195 }
9196
Guy Benyei11169dd2012-12-18 14:30:41 +00009197 // Load any pending macro definitions.
9198 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009199 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9200 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9201 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9202 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009203 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009204 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009205 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009206 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009207 resolvePendingMacro(II, Info);
9208 }
9209 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009210 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009211 ++IDIdx) {
9212 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009213 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009214 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009215 }
9216 }
9217 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009218
9219 // Wire up the DeclContexts for Decls that we delayed setting until
9220 // recursive loading is completed.
9221 while (!PendingDeclContextInfos.empty()) {
9222 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9223 PendingDeclContextInfos.pop_front();
Vedant Kumar48b4f762018-04-14 01:40:48 +00009224 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9225 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009226 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9227 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009228
Richard Smithd1c46742014-04-30 02:24:17 +00009229 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009230 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009231 auto Update = PendingUpdateRecords.pop_back_val();
9232 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009233 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009234 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009235 }
Richard Smith8a639892015-01-24 01:07:20 +00009236
9237 // At this point, all update records for loaded decls are in place, so any
9238 // fake class definitions should have become real.
9239 assert(PendingFakeDefinitionData.empty() &&
9240 "faked up a class definition but never saw the real one");
9241
Guy Benyei11169dd2012-12-18 14:30:41 +00009242 // If we deserialized any C++ or Objective-C class definitions, any
9243 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009244 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009245 // happen now, after the redeclaration chains have been fully wired.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009246 for (Decl *D : PendingDefinitions) {
9247 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
9248 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009249 // Make sure that the TagType points at the definition.
9250 const_cast<TagType*>(TagT)->decl = TD;
9251 }
Richard Smith8ce51082015-03-11 01:44:51 +00009252
Vedant Kumar48b4f762018-04-14 01:40:48 +00009253 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009254 for (auto *R = getMostRecentExistingDecl(RD); R;
9255 R = R->getPreviousDecl()) {
9256 assert((R == D) ==
9257 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009258 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009259 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009260 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009261 }
9262
9263 continue;
9264 }
Richard Smith8ce51082015-03-11 01:44:51 +00009265
Vedant Kumar48b4f762018-04-14 01:40:48 +00009266 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009267 // Make sure that the ObjCInterfaceType points at the definition.
9268 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9269 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009270
9271 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9272 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9273
Guy Benyei11169dd2012-12-18 14:30:41 +00009274 continue;
9275 }
Richard Smith8ce51082015-03-11 01:44:51 +00009276
Vedant Kumar48b4f762018-04-14 01:40:48 +00009277 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009278 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9279 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9280
Guy Benyei11169dd2012-12-18 14:30:41 +00009281 continue;
9282 }
Richard Smith8ce51082015-03-11 01:44:51 +00009283
Vedant Kumar48b4f762018-04-14 01:40:48 +00009284 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009285 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9286 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009287 }
9288 PendingDefinitions.clear();
9289
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009290 // Load the bodies of any functions or methods we've encountered. We do
9291 // this now (delayed) so that we can be sure that the declaration chains
9292 // have been fully wired up (hasBody relies on this).
9293 // FIXME: We shouldn't require complete redeclaration chains here.
Vedant Kumar48b4f762018-04-14 01:40:48 +00009294 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9295 PBEnd = PendingBodies.end();
9296 PB != PBEnd; ++PB) {
9297 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009298 // FIXME: Check for =delete/=default?
9299 // FIXME: Complain about ODR violations here?
9300 const FunctionDecl *Defn = nullptr;
9301 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009302 FD->setLazyBody(PB->second);
Richard Trieue6caa262017-12-23 00:41:01 +00009303 } else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009304 auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
Richard Trieue6caa262017-12-23 00:41:01 +00009305 mergeDefinitionVisibility(NonConstDefn, FD);
9306
9307 if (!FD->isLateTemplateParsed() &&
9308 !NonConstDefn->isLateTemplateParsed() &&
9309 FD->getODRHash() != NonConstDefn->getODRHash()) {
9310 PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
9311 }
9312 }
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009313 continue;
9314 }
9315
Vedant Kumar48b4f762018-04-14 01:40:48 +00009316 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009317 if (!getContext().getLangOpts().Modules || !MD->hasBody())
Vedant Kumar48b4f762018-04-14 01:40:48 +00009318 MD->setLazyBody(PB->second);
Daniel Jasper4a6d5b72017-10-11 07:47:54 +00009319 }
9320 PendingBodies.clear();
9321
Richard Smith42413142015-05-15 20:05:43 +00009322 // Do some cleanup.
9323 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9324 getContext().deduplicateMergedDefinitonsFor(ND);
9325 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009326}
9327
9328void ASTReader::diagnoseOdrViolations() {
Richard Trieue6caa262017-12-23 00:41:01 +00009329 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
9330 PendingFunctionOdrMergeFailures.empty())
Richard Smithbb853c72014-08-13 01:23:33 +00009331 return;
9332
Richard Smitha0ce9c42014-07-29 23:23:27 +00009333 // Trigger the import of the full definition of each class that had any
9334 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009335 // These updates may in turn find and diagnose some ODR failures, so take
9336 // ownership of the set first.
9337 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9338 PendingOdrMergeFailures.clear();
9339 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009340 Merge.first->buildLookup();
9341 Merge.first->decls_begin();
9342 Merge.first->bases_begin();
9343 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009344 for (auto &RecordPair : Merge.second) {
9345 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009346 RD->decls_begin();
9347 RD->bases_begin();
9348 RD->vbases_begin();
9349 }
9350 }
9351
Richard Trieue6caa262017-12-23 00:41:01 +00009352 // Trigger the import of functions.
9353 auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
9354 PendingFunctionOdrMergeFailures.clear();
9355 for (auto &Merge : FunctionOdrMergeFailures) {
9356 Merge.first->buildLookup();
9357 Merge.first->decls_begin();
9358 Merge.first->getBody();
9359 for (auto &FD : Merge.second) {
9360 FD->buildLookup();
9361 FD->decls_begin();
9362 FD->getBody();
9363 }
9364 }
9365
Richard Smitha0ce9c42014-07-29 23:23:27 +00009366 // For each declaration from a merged context, check that the canonical
9367 // definition of that context also contains a declaration of the same
9368 // entity.
9369 //
9370 // Caution: this loop does things that might invalidate iterators into
9371 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9372 while (!PendingOdrMergeChecks.empty()) {
9373 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9374
9375 // FIXME: Skip over implicit declarations for now. This matters for things
9376 // like implicitly-declared special member functions. This isn't entirely
9377 // correct; we can end up with multiple unmerged declarations of the same
9378 // implicit entity.
9379 if (D->isImplicit())
9380 continue;
9381
9382 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009383
9384 bool Found = false;
9385 const Decl *DCanon = D->getCanonicalDecl();
9386
Richard Smith01bdb7a2014-08-28 05:44:07 +00009387 for (auto RI : D->redecls()) {
9388 if (RI->getLexicalDeclContext() == CanonDef) {
9389 Found = true;
9390 break;
9391 }
9392 }
9393 if (Found)
9394 continue;
9395
Richard Smith0f4e2c42015-08-06 04:23:48 +00009396 // Quick check failed, time to do the slow thing. Note, we can't just
9397 // look up the name of D in CanonDef here, because the member that is
9398 // in CanonDef might not be found by name lookup (it might have been
9399 // replaced by a more recent declaration in the lookup table), and we
9400 // can't necessarily find it in the redeclaration chain because it might
9401 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009402 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009403 for (auto *CanonMember : CanonDef->decls()) {
9404 if (CanonMember->getCanonicalDecl() == DCanon) {
9405 // This can happen if the declaration is merely mergeable and not
9406 // actually redeclarable (we looked for redeclarations earlier).
9407 //
9408 // FIXME: We should be able to detect this more efficiently, without
9409 // pulling in all of the members of CanonDef.
9410 Found = true;
9411 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009412 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009413 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9414 if (ND->getDeclName() == D->getDeclName())
9415 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009416 }
9417
9418 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009419 // The AST doesn't like TagDecls becoming invalid after they've been
9420 // completed. We only really need to mark FieldDecls as invalid here.
9421 if (!isa<TagDecl>(D))
9422 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009423
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009424 // Ensure we don't accidentally recursively enter deserialization while
9425 // we're producing our diagnostic.
9426 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009427
9428 std::string CanonDefModule =
9429 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9430 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9431 << D << getOwningModuleNameForDiagnostic(D)
9432 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9433
9434 if (Candidates.empty())
9435 Diag(cast<Decl>(CanonDef)->getLocation(),
9436 diag::note_module_odr_violation_no_possible_decls) << D;
9437 else {
Vedant Kumar48b4f762018-04-14 01:40:48 +00009438 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9439 Diag(Candidates[I]->getLocation(),
Richard Smitha0ce9c42014-07-29 23:23:27 +00009440 diag::note_module_odr_violation_possible_decl)
Vedant Kumar48b4f762018-04-14 01:40:48 +00009441 << Candidates[I];
Richard Smitha0ce9c42014-07-29 23:23:27 +00009442 }
9443
9444 DiagnosedOdrMergeFailures.insert(CanonDef);
9445 }
9446 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009447
Richard Trieue6caa262017-12-23 00:41:01 +00009448 if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty())
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009449 return;
9450
9451 // Ensure we don't accidentally recursively enter deserialization while
9452 // we're producing our diagnostics.
9453 Deserializing RecursionGuard(this);
9454
Richard Trieue6caa262017-12-23 00:41:01 +00009455 // Common code for hashing helpers.
9456 ODRHash Hash;
9457 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9458 Hash.clear();
9459 Hash.AddQualType(Ty);
9460 return Hash.CalculateHash();
9461 };
9462
9463 auto ComputeODRHash = [&Hash](const Stmt *S) {
9464 assert(S);
9465 Hash.clear();
9466 Hash.AddStmt(S);
9467 return Hash.CalculateHash();
9468 };
9469
9470 auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
9471 assert(D);
9472 Hash.clear();
9473 Hash.AddSubDecl(D);
9474 return Hash.CalculateHash();
9475 };
9476
Richard Trieu7282d322018-04-25 00:31:15 +00009477 auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
9478 Hash.clear();
9479 Hash.AddTemplateArgument(TA);
9480 return Hash.CalculateHash();
9481 };
9482
Richard Trieu9359e8f2018-05-30 01:12:26 +00009483 auto ComputeTemplateParameterListODRHash =
9484 [&Hash](const TemplateParameterList *TPL) {
9485 assert(TPL);
9486 Hash.clear();
9487 Hash.AddTemplateParameterList(TPL);
9488 return Hash.CalculateHash();
9489 };
9490
Richard Smithcd45dbc2014-04-19 03:48:30 +00009491 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009492 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009493 // If we've already pointed out a specific problem with this class, don't
9494 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009495 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009496 continue;
9497
9498 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009499 CXXRecordDecl *FirstRecord = Merge.first;
9500 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009501 for (auto &RecordPair : Merge.second) {
9502 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009503 // Multiple different declarations got merged together; tell the user
9504 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009505 if (FirstRecord == SecondRecord)
9506 continue;
9507
9508 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009509
9510 auto *FirstDD = FirstRecord->DefinitionData;
9511 auto *SecondDD = RecordPair.second;
9512
9513 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9514
9515 // Diagnostics from DefinitionData are emitted here.
9516 if (FirstDD != SecondDD) {
9517 enum ODRDefinitionDataDifference {
9518 NumBases,
9519 NumVBases,
9520 BaseType,
9521 BaseVirtual,
9522 BaseAccess,
9523 };
9524 auto ODRDiagError = [FirstRecord, &FirstModule,
9525 this](SourceLocation Loc, SourceRange Range,
9526 ODRDefinitionDataDifference DiffType) {
9527 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9528 << FirstRecord << FirstModule.empty() << FirstModule << Range
9529 << DiffType;
9530 };
9531 auto ODRDiagNote = [&SecondModule,
9532 this](SourceLocation Loc, SourceRange Range,
9533 ODRDefinitionDataDifference DiffType) {
9534 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9535 << SecondModule << Range << DiffType;
9536 };
9537
Richard Trieue13eabe2017-09-30 02:19:17 +00009538 unsigned FirstNumBases = FirstDD->NumBases;
9539 unsigned FirstNumVBases = FirstDD->NumVBases;
9540 unsigned SecondNumBases = SecondDD->NumBases;
9541 unsigned SecondNumVBases = SecondDD->NumVBases;
9542
9543 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9544 unsigned NumBases = DD->NumBases;
9545 if (NumBases == 0) return SourceRange();
9546 auto bases = DD->bases();
9547 return SourceRange(bases[0].getLocStart(),
9548 bases[NumBases - 1].getLocEnd());
9549 };
9550
9551 if (FirstNumBases != SecondNumBases) {
9552 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9553 NumBases)
9554 << FirstNumBases;
9555 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9556 NumBases)
9557 << SecondNumBases;
9558 Diagnosed = true;
9559 break;
9560 }
9561
9562 if (FirstNumVBases != SecondNumVBases) {
9563 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9564 NumVBases)
9565 << FirstNumVBases;
9566 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9567 NumVBases)
9568 << SecondNumVBases;
9569 Diagnosed = true;
9570 break;
9571 }
9572
9573 auto FirstBases = FirstDD->bases();
9574 auto SecondBases = SecondDD->bases();
9575 unsigned i = 0;
9576 for (i = 0; i < FirstNumBases; ++i) {
9577 auto FirstBase = FirstBases[i];
9578 auto SecondBase = SecondBases[i];
9579 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9580 ComputeQualTypeODRHash(SecondBase.getType())) {
9581 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9582 BaseType)
9583 << (i + 1) << FirstBase.getType();
9584 ODRDiagNote(SecondRecord->getLocation(),
9585 SecondBase.getSourceRange(), BaseType)
9586 << (i + 1) << SecondBase.getType();
9587 break;
9588 }
9589
9590 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9591 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9592 BaseVirtual)
9593 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9594 ODRDiagNote(SecondRecord->getLocation(),
9595 SecondBase.getSourceRange(), BaseVirtual)
9596 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9597 break;
9598 }
9599
9600 if (FirstBase.getAccessSpecifierAsWritten() !=
9601 SecondBase.getAccessSpecifierAsWritten()) {
9602 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9603 BaseAccess)
9604 << (i + 1) << FirstBase.getType()
9605 << (int)FirstBase.getAccessSpecifierAsWritten();
9606 ODRDiagNote(SecondRecord->getLocation(),
9607 SecondBase.getSourceRange(), BaseAccess)
9608 << (i + 1) << SecondBase.getType()
9609 << (int)SecondBase.getAccessSpecifierAsWritten();
9610 break;
9611 }
9612 }
9613
9614 if (i != FirstNumBases) {
9615 Diagnosed = true;
9616 break;
9617 }
9618 }
9619
Richard Trieue7f7ed22017-02-22 01:11:25 +00009620 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009621
9622 const ClassTemplateDecl *FirstTemplate =
9623 FirstRecord->getDescribedClassTemplate();
9624 const ClassTemplateDecl *SecondTemplate =
9625 SecondRecord->getDescribedClassTemplate();
9626
9627 assert(!FirstTemplate == !SecondTemplate &&
9628 "Both pointers should be null or non-null");
9629
9630 enum ODRTemplateDifference {
9631 ParamEmptyName,
9632 ParamName,
9633 ParamSingleDefaultArgument,
9634 ParamDifferentDefaultArgument,
9635 };
9636
9637 if (FirstTemplate && SecondTemplate) {
9638 DeclHashes FirstTemplateHashes;
9639 DeclHashes SecondTemplateHashes;
Richard Trieu498117b2017-08-23 02:43:59 +00009640
9641 auto PopulateTemplateParameterHashs =
Richard Trieue6caa262017-12-23 00:41:01 +00009642 [&ComputeSubDeclODRHash](DeclHashes &Hashes,
9643 const ClassTemplateDecl *TD) {
Richard Trieu498117b2017-08-23 02:43:59 +00009644 for (auto *D : TD->getTemplateParameters()->asArray()) {
Richard Trieue6caa262017-12-23 00:41:01 +00009645 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieu498117b2017-08-23 02:43:59 +00009646 }
9647 };
9648
9649 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9650 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9651
9652 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9653 "Number of template parameters should be equal.");
9654
9655 auto FirstIt = FirstTemplateHashes.begin();
9656 auto FirstEnd = FirstTemplateHashes.end();
9657 auto SecondIt = SecondTemplateHashes.begin();
9658 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9659 if (FirstIt->second == SecondIt->second)
9660 continue;
9661
9662 auto ODRDiagError = [FirstRecord, &FirstModule,
9663 this](SourceLocation Loc, SourceRange Range,
9664 ODRTemplateDifference DiffType) {
9665 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9666 << FirstRecord << FirstModule.empty() << FirstModule << Range
9667 << DiffType;
9668 };
9669 auto ODRDiagNote = [&SecondModule,
9670 this](SourceLocation Loc, SourceRange Range,
9671 ODRTemplateDifference DiffType) {
9672 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9673 << SecondModule << Range << DiffType;
9674 };
9675
Vedant Kumar48b4f762018-04-14 01:40:48 +00009676 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9677 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
Richard Trieu498117b2017-08-23 02:43:59 +00009678
9679 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9680 "Parameter Decl's should be the same kind.");
9681
9682 DeclarationName FirstName = FirstDecl->getDeclName();
9683 DeclarationName SecondName = SecondDecl->getDeclName();
9684
9685 if (FirstName != SecondName) {
9686 const bool FirstNameEmpty =
9687 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9688 const bool SecondNameEmpty =
9689 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9690 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9691 "Both template parameters cannot be unnamed.");
9692 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9693 FirstNameEmpty ? ParamEmptyName : ParamName)
9694 << FirstName;
9695 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9696 SecondNameEmpty ? ParamEmptyName : ParamName)
9697 << SecondName;
9698 break;
9699 }
9700
9701 switch (FirstDecl->getKind()) {
9702 default:
9703 llvm_unreachable("Invalid template parameter type.");
9704 case Decl::TemplateTypeParm: {
9705 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9706 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9707 const bool HasFirstDefaultArgument =
9708 FirstParam->hasDefaultArgument() &&
9709 !FirstParam->defaultArgumentWasInherited();
9710 const bool HasSecondDefaultArgument =
9711 SecondParam->hasDefaultArgument() &&
9712 !SecondParam->defaultArgumentWasInherited();
9713
9714 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9715 ODRDiagError(FirstDecl->getLocation(),
9716 FirstDecl->getSourceRange(),
9717 ParamSingleDefaultArgument)
9718 << HasFirstDefaultArgument;
9719 ODRDiagNote(SecondDecl->getLocation(),
9720 SecondDecl->getSourceRange(),
9721 ParamSingleDefaultArgument)
9722 << HasSecondDefaultArgument;
9723 break;
9724 }
9725
9726 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9727 "Expecting default arguments.");
9728
9729 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9730 ParamDifferentDefaultArgument);
9731 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9732 ParamDifferentDefaultArgument);
9733
9734 break;
9735 }
9736 case Decl::NonTypeTemplateParm: {
9737 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9738 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9739 const bool HasFirstDefaultArgument =
9740 FirstParam->hasDefaultArgument() &&
9741 !FirstParam->defaultArgumentWasInherited();
9742 const bool HasSecondDefaultArgument =
9743 SecondParam->hasDefaultArgument() &&
9744 !SecondParam->defaultArgumentWasInherited();
9745
9746 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9747 ODRDiagError(FirstDecl->getLocation(),
9748 FirstDecl->getSourceRange(),
9749 ParamSingleDefaultArgument)
9750 << HasFirstDefaultArgument;
9751 ODRDiagNote(SecondDecl->getLocation(),
9752 SecondDecl->getSourceRange(),
9753 ParamSingleDefaultArgument)
9754 << HasSecondDefaultArgument;
9755 break;
9756 }
9757
9758 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9759 "Expecting default arguments.");
9760
9761 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9762 ParamDifferentDefaultArgument);
9763 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9764 ParamDifferentDefaultArgument);
9765
9766 break;
9767 }
9768 case Decl::TemplateTemplateParm: {
9769 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9770 const auto *SecondParam =
9771 cast<TemplateTemplateParmDecl>(SecondDecl);
9772 const bool HasFirstDefaultArgument =
9773 FirstParam->hasDefaultArgument() &&
9774 !FirstParam->defaultArgumentWasInherited();
9775 const bool HasSecondDefaultArgument =
9776 SecondParam->hasDefaultArgument() &&
9777 !SecondParam->defaultArgumentWasInherited();
9778
9779 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9780 ODRDiagError(FirstDecl->getLocation(),
9781 FirstDecl->getSourceRange(),
9782 ParamSingleDefaultArgument)
9783 << HasFirstDefaultArgument;
9784 ODRDiagNote(SecondDecl->getLocation(),
9785 SecondDecl->getSourceRange(),
9786 ParamSingleDefaultArgument)
9787 << HasSecondDefaultArgument;
9788 break;
9789 }
9790
9791 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9792 "Expecting default arguments.");
9793
9794 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9795 ParamDifferentDefaultArgument);
9796 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9797 ParamDifferentDefaultArgument);
9798
9799 break;
9800 }
9801 }
9802
9803 break;
9804 }
9805
9806 if (FirstIt != FirstEnd) {
9807 Diagnosed = true;
9808 break;
9809 }
9810 }
9811
Richard Trieue7f7ed22017-02-22 01:11:25 +00009812 DeclHashes FirstHashes;
9813 DeclHashes SecondHashes;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009814
Richard Trieue6caa262017-12-23 00:41:01 +00009815 auto PopulateHashes = [&ComputeSubDeclODRHash, FirstRecord](
9816 DeclHashes &Hashes, CXXRecordDecl *Record) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009817 for (auto *D : Record->decls()) {
9818 // Due to decl merging, the first CXXRecordDecl is the parent of
9819 // Decls in both records.
9820 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9821 continue;
Richard Trieue6caa262017-12-23 00:41:01 +00009822 Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
Richard Trieue7f7ed22017-02-22 01:11:25 +00009823 }
9824 };
9825 PopulateHashes(FirstHashes, FirstRecord);
9826 PopulateHashes(SecondHashes, SecondRecord);
9827
9828 // Used with err_module_odr_violation_mismatch_decl and
9829 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009830 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009831 enum {
9832 EndOfClass,
9833 PublicSpecifer,
9834 PrivateSpecifer,
9835 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009836 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009837 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009838 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009839 TypeAlias,
9840 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009841 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009842 Friend,
Richard Trieu9359e8f2018-05-30 01:12:26 +00009843 FunctionTemplate,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009844 Other
9845 } FirstDiffType = Other,
9846 SecondDiffType = Other;
9847
9848 auto DifferenceSelector = [](Decl *D) {
9849 assert(D && "valid Decl required");
9850 switch (D->getKind()) {
9851 default:
9852 return Other;
9853 case Decl::AccessSpec:
9854 switch (D->getAccess()) {
9855 case AS_public:
9856 return PublicSpecifer;
9857 case AS_private:
9858 return PrivateSpecifer;
9859 case AS_protected:
9860 return ProtectedSpecifer;
9861 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009862 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009863 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009864 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009865 case Decl::StaticAssert:
9866 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009867 case Decl::Field:
9868 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009869 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009870 case Decl::CXXConstructor:
9871 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009872 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009873 case Decl::TypeAlias:
9874 return TypeAlias;
9875 case Decl::Typedef:
9876 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009877 case Decl::Var:
9878 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009879 case Decl::Friend:
9880 return Friend;
Richard Trieu9359e8f2018-05-30 01:12:26 +00009881 case Decl::FunctionTemplate:
9882 return FunctionTemplate;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009883 }
9884 };
9885
9886 Decl *FirstDecl = nullptr;
9887 Decl *SecondDecl = nullptr;
9888 auto FirstIt = FirstHashes.begin();
9889 auto SecondIt = SecondHashes.begin();
9890
9891 // If there is a diagnoseable difference, FirstDiffType and
9892 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9893 // filled in if not EndOfClass.
9894 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009895 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9896 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009897 ++FirstIt;
9898 ++SecondIt;
9899 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009900 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009901
Richard Trieue7f7ed22017-02-22 01:11:25 +00009902 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9903 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9904
9905 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9906 SecondDiffType =
9907 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9908
9909 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009910 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009911
9912 if (FirstDiffType == Other || SecondDiffType == Other) {
9913 // Reaching this point means an unexpected Decl was encountered
9914 // or no difference was detected. This causes a generic error
9915 // message to be emitted.
9916 Diag(FirstRecord->getLocation(),
9917 diag::err_module_odr_violation_different_definitions)
9918 << FirstRecord << FirstModule.empty() << FirstModule;
9919
Richard Trieuca48d362017-06-21 01:43:13 +00009920 if (FirstDecl) {
9921 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9922 << FirstRecord << FirstDecl->getSourceRange();
9923 }
9924
Richard Trieue7f7ed22017-02-22 01:11:25 +00009925 Diag(SecondRecord->getLocation(),
9926 diag::note_module_odr_violation_different_definitions)
9927 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009928
9929 if (SecondDecl) {
9930 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9931 << SecondDecl->getSourceRange();
9932 }
9933
Richard Trieue7f7ed22017-02-22 01:11:25 +00009934 Diagnosed = true;
9935 break;
9936 }
9937
9938 if (FirstDiffType != SecondDiffType) {
9939 SourceLocation FirstLoc;
9940 SourceRange FirstRange;
9941 if (FirstDiffType == EndOfClass) {
9942 FirstLoc = FirstRecord->getBraceRange().getEnd();
9943 } else {
9944 FirstLoc = FirstIt->first->getLocation();
9945 FirstRange = FirstIt->first->getSourceRange();
9946 }
9947 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9948 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9949 << FirstDiffType;
9950
9951 SourceLocation SecondLoc;
9952 SourceRange SecondRange;
9953 if (SecondDiffType == EndOfClass) {
9954 SecondLoc = SecondRecord->getBraceRange().getEnd();
9955 } else {
9956 SecondLoc = SecondDecl->getLocation();
9957 SecondRange = SecondDecl->getSourceRange();
9958 }
9959 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9960 << SecondModule << SecondRange << SecondDiffType;
9961 Diagnosed = true;
9962 break;
9963 }
9964
Richard Trieu639d7b62017-02-22 22:22:42 +00009965 assert(FirstDiffType == SecondDiffType);
9966
9967 // Used with err_module_odr_violation_mismatch_decl_diff and
9968 // note_module_odr_violation_mismatch_decl_diff
Richard Trieu9359e8f2018-05-30 01:12:26 +00009969 enum ODRDeclDifference {
Richard Trieu639d7b62017-02-22 22:22:42 +00009970 StaticAssertCondition,
9971 StaticAssertMessage,
9972 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009973 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009974 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009975 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009976 FieldDifferentWidthBitField,
9977 FieldSingleMutable,
9978 FieldSingleInitializer,
9979 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009980 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009981 MethodDeleted,
9982 MethodVirtual,
9983 MethodStatic,
9984 MethodVolatile,
9985 MethodConst,
9986 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009987 MethodNumberParameters,
9988 MethodParameterType,
9989 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009990 MethodParameterSingleDefaultArgument,
9991 MethodParameterDifferentDefaultArgument,
Richard Trieu7282d322018-04-25 00:31:15 +00009992 MethodNoTemplateArguments,
9993 MethodDifferentNumberTemplateArguments,
9994 MethodDifferentTemplateArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009995 TypedefName,
9996 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009997 VarName,
9998 VarType,
9999 VarSingleInitializer,
10000 VarDifferentInitializer,
10001 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +000010002 FriendTypeFunction,
10003 FriendType,
10004 FriendFunction,
Richard Trieu9359e8f2018-05-30 01:12:26 +000010005 FunctionTemplateDifferentNumberParameters,
10006 FunctionTemplateParameterDifferentKind,
10007 FunctionTemplateParameterName,
10008 FunctionTemplateParameterSingleDefaultArgument,
10009 FunctionTemplateParameterDifferentDefaultArgument,
10010 FunctionTemplateParameterDifferentType,
10011 FunctionTemplatePackParameter,
Richard Trieu639d7b62017-02-22 22:22:42 +000010012 };
10013
10014 // These lambdas have the common portions of the ODR diagnostics. This
10015 // has the same return as Diag(), so addition parameters can be passed
10016 // in with operator<<
10017 auto ODRDiagError = [FirstRecord, &FirstModule, this](
10018 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10019 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
10020 << FirstRecord << FirstModule.empty() << FirstModule << Range
10021 << DiffType;
10022 };
10023 auto ODRDiagNote = [&SecondModule, this](
10024 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
10025 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
10026 << SecondModule << Range << DiffType;
10027 };
10028
Richard Trieu639d7b62017-02-22 22:22:42 +000010029 switch (FirstDiffType) {
10030 case Other:
10031 case EndOfClass:
10032 case PublicSpecifer:
10033 case PrivateSpecifer:
10034 case ProtectedSpecifer:
10035 llvm_unreachable("Invalid diff type");
10036
10037 case StaticAssert: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010038 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
10039 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
Richard Trieu639d7b62017-02-22 22:22:42 +000010040
10041 Expr *FirstExpr = FirstSA->getAssertExpr();
10042 Expr *SecondExpr = SecondSA->getAssertExpr();
10043 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
10044 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
10045 if (FirstODRHash != SecondODRHash) {
10046 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
10047 StaticAssertCondition);
10048 ODRDiagNote(SecondExpr->getLocStart(),
10049 SecondExpr->getSourceRange(), StaticAssertCondition);
10050 Diagnosed = true;
10051 break;
10052 }
10053
10054 StringLiteral *FirstStr = FirstSA->getMessage();
10055 StringLiteral *SecondStr = SecondSA->getMessage();
10056 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
10057 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
10058 SourceLocation FirstLoc, SecondLoc;
10059 SourceRange FirstRange, SecondRange;
10060 if (FirstStr) {
10061 FirstLoc = FirstStr->getLocStart();
10062 FirstRange = FirstStr->getSourceRange();
10063 } else {
10064 FirstLoc = FirstSA->getLocStart();
10065 FirstRange = FirstSA->getSourceRange();
10066 }
10067 if (SecondStr) {
10068 SecondLoc = SecondStr->getLocStart();
10069 SecondRange = SecondStr->getSourceRange();
10070 } else {
10071 SecondLoc = SecondSA->getLocStart();
10072 SecondRange = SecondSA->getSourceRange();
10073 }
10074 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
10075 << (FirstStr == nullptr);
10076 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
10077 << (SecondStr == nullptr);
10078 Diagnosed = true;
10079 break;
10080 }
10081
10082 if (FirstStr && SecondStr &&
10083 FirstStr->getString() != SecondStr->getString()) {
10084 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
10085 StaticAssertMessage);
10086 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
10087 StaticAssertMessage);
10088 Diagnosed = true;
10089 break;
10090 }
10091 break;
10092 }
Richard Trieud0786092017-02-23 00:23:01 +000010093 case Field: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010094 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
10095 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
Richard Trieud0786092017-02-23 00:23:01 +000010096 IdentifierInfo *FirstII = FirstField->getIdentifier();
10097 IdentifierInfo *SecondII = SecondField->getIdentifier();
10098 if (FirstII->getName() != SecondII->getName()) {
10099 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10100 FieldName)
10101 << FirstII;
10102 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10103 FieldName)
10104 << SecondII;
10105
10106 Diagnosed = true;
10107 break;
10108 }
Richard Trieu8459ddf2017-02-24 02:59:12 +000010109
Richard Smithdbafb6c2017-06-29 23:23:46 +000010110 assert(getContext().hasSameType(FirstField->getType(),
10111 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +000010112
10113 QualType FirstType = FirstField->getType();
10114 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +000010115 if (ComputeQualTypeODRHash(FirstType) !=
10116 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +000010117 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10118 FieldTypeName)
10119 << FirstII << FirstType;
10120 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10121 FieldTypeName)
10122 << SecondII << SecondType;
10123
10124 Diagnosed = true;
10125 break;
10126 }
10127
Richard Trieu93772fc2017-02-24 20:59:28 +000010128 const bool IsFirstBitField = FirstField->isBitField();
10129 const bool IsSecondBitField = SecondField->isBitField();
10130 if (IsFirstBitField != IsSecondBitField) {
10131 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10132 FieldSingleBitField)
10133 << FirstII << IsFirstBitField;
10134 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10135 FieldSingleBitField)
10136 << SecondII << IsSecondBitField;
10137 Diagnosed = true;
10138 break;
10139 }
10140
10141 if (IsFirstBitField && IsSecondBitField) {
10142 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10143 FieldDifferentWidthBitField)
10144 << FirstII << FirstField->getBitWidth()->getSourceRange();
10145 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10146 FieldDifferentWidthBitField)
10147 << SecondII << SecondField->getBitWidth()->getSourceRange();
10148 Diagnosed = true;
10149 break;
10150 }
10151
Richard Trieu8d543e22017-02-24 23:35:37 +000010152 const bool IsFirstMutable = FirstField->isMutable();
10153 const bool IsSecondMutable = SecondField->isMutable();
10154 if (IsFirstMutable != IsSecondMutable) {
10155 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10156 FieldSingleMutable)
10157 << FirstII << IsFirstMutable;
10158 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10159 FieldSingleMutable)
10160 << SecondII << IsSecondMutable;
10161 Diagnosed = true;
10162 break;
10163 }
10164
10165 const Expr *FirstInitializer = FirstField->getInClassInitializer();
10166 const Expr *SecondInitializer = SecondField->getInClassInitializer();
10167 if ((!FirstInitializer && SecondInitializer) ||
10168 (FirstInitializer && !SecondInitializer)) {
10169 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
10170 FieldSingleInitializer)
10171 << FirstII << (FirstInitializer != nullptr);
10172 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
10173 FieldSingleInitializer)
10174 << SecondII << (SecondInitializer != nullptr);
10175 Diagnosed = true;
10176 break;
10177 }
10178
10179 if (FirstInitializer && SecondInitializer) {
10180 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
10181 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
10182 if (FirstInitHash != SecondInitHash) {
10183 ODRDiagError(FirstField->getLocation(),
10184 FirstField->getSourceRange(),
10185 FieldDifferentInitializers)
10186 << FirstII << FirstInitializer->getSourceRange();
10187 ODRDiagNote(SecondField->getLocation(),
10188 SecondField->getSourceRange(),
10189 FieldDifferentInitializers)
10190 << SecondII << SecondInitializer->getSourceRange();
10191 Diagnosed = true;
10192 break;
10193 }
10194 }
10195
Richard Trieud0786092017-02-23 00:23:01 +000010196 break;
10197 }
Richard Trieu48143742017-02-28 21:24:38 +000010198 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010199 enum {
10200 DiagMethod,
10201 DiagConstructor,
10202 DiagDestructor,
10203 } FirstMethodType,
10204 SecondMethodType;
10205 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10206 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10207 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10208 return DiagMethod;
10209 };
Vedant Kumar48b4f762018-04-14 01:40:48 +000010210 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10211 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010212 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10213 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010214 auto FirstName = FirstMethod->getDeclName();
10215 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010216 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010217 ODRDiagError(FirstMethod->getLocation(),
10218 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010219 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010220 ODRDiagNote(SecondMethod->getLocation(),
10221 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010222 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010223
10224 Diagnosed = true;
10225 break;
10226 }
10227
Richard Trieu583e2c12017-03-04 00:08:58 +000010228 const bool FirstDeleted = FirstMethod->isDeleted();
10229 const bool SecondDeleted = SecondMethod->isDeleted();
10230 if (FirstDeleted != SecondDeleted) {
10231 ODRDiagError(FirstMethod->getLocation(),
10232 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010233 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010234
10235 ODRDiagNote(SecondMethod->getLocation(),
10236 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010237 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010238 Diagnosed = true;
10239 break;
10240 }
10241
10242 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10243 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10244 const bool FirstPure = FirstMethod->isPure();
10245 const bool SecondPure = SecondMethod->isPure();
10246 if ((FirstVirtual || SecondVirtual) &&
10247 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10248 ODRDiagError(FirstMethod->getLocation(),
10249 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010250 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010251 ODRDiagNote(SecondMethod->getLocation(),
10252 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010253 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010254 Diagnosed = true;
10255 break;
10256 }
10257
10258 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10259 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10260 // class needs to be checked instead.
10261 const auto FirstStorage = FirstMethod->getStorageClass();
10262 const auto SecondStorage = SecondMethod->getStorageClass();
10263 const bool FirstStatic = FirstStorage == SC_Static;
10264 const bool SecondStatic = SecondStorage == SC_Static;
10265 if (FirstStatic != SecondStatic) {
10266 ODRDiagError(FirstMethod->getLocation(),
10267 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010268 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010269 ODRDiagNote(SecondMethod->getLocation(),
10270 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010271 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010272 Diagnosed = true;
10273 break;
10274 }
10275
10276 const bool FirstVolatile = FirstMethod->isVolatile();
10277 const bool SecondVolatile = SecondMethod->isVolatile();
10278 if (FirstVolatile != SecondVolatile) {
10279 ODRDiagError(FirstMethod->getLocation(),
10280 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010281 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010282 ODRDiagNote(SecondMethod->getLocation(),
10283 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010284 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010285 Diagnosed = true;
10286 break;
10287 }
10288
10289 const bool FirstConst = FirstMethod->isConst();
10290 const bool SecondConst = SecondMethod->isConst();
10291 if (FirstConst != SecondConst) {
10292 ODRDiagError(FirstMethod->getLocation(),
10293 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010294 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010295 ODRDiagNote(SecondMethod->getLocation(),
10296 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010297 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010298 Diagnosed = true;
10299 break;
10300 }
10301
10302 const bool FirstInline = FirstMethod->isInlineSpecified();
10303 const bool SecondInline = SecondMethod->isInlineSpecified();
10304 if (FirstInline != SecondInline) {
10305 ODRDiagError(FirstMethod->getLocation(),
10306 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010307 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010308 ODRDiagNote(SecondMethod->getLocation(),
10309 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010310 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010311 Diagnosed = true;
10312 break;
10313 }
10314
Richard Trieu02552272017-05-02 23:58:52 +000010315 const unsigned FirstNumParameters = FirstMethod->param_size();
10316 const unsigned SecondNumParameters = SecondMethod->param_size();
10317 if (FirstNumParameters != SecondNumParameters) {
10318 ODRDiagError(FirstMethod->getLocation(),
10319 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010320 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010321 ODRDiagNote(SecondMethod->getLocation(),
10322 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010323 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010324 Diagnosed = true;
10325 break;
10326 }
10327
10328 // Need this status boolean to know when break out of the switch.
10329 bool ParameterMismatch = false;
10330 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10331 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10332 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10333
10334 QualType FirstParamType = FirstParam->getType();
10335 QualType SecondParamType = SecondParam->getType();
10336 if (FirstParamType != SecondParamType &&
10337 ComputeQualTypeODRHash(FirstParamType) !=
10338 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010339 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010340 FirstParamType->getAs<DecayedType>()) {
10341 ODRDiagError(FirstMethod->getLocation(),
10342 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010343 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10344 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010345 } else {
10346 ODRDiagError(FirstMethod->getLocation(),
10347 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010348 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10349 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010350 }
10351
Vedant Kumar48b4f762018-04-14 01:40:48 +000010352 if (const DecayedType *ParamDecayedType =
Richard Trieu02552272017-05-02 23:58:52 +000010353 SecondParamType->getAs<DecayedType>()) {
10354 ODRDiagNote(SecondMethod->getLocation(),
10355 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010356 << SecondMethodType << SecondName << (I + 1)
10357 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010358 << ParamDecayedType->getOriginalType();
10359 } else {
10360 ODRDiagNote(SecondMethod->getLocation(),
10361 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010362 << SecondMethodType << SecondName << (I + 1)
10363 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010364 }
10365 ParameterMismatch = true;
10366 break;
10367 }
10368
10369 DeclarationName FirstParamName = FirstParam->getDeclName();
10370 DeclarationName SecondParamName = SecondParam->getDeclName();
10371 if (FirstParamName != SecondParamName) {
10372 ODRDiagError(FirstMethod->getLocation(),
10373 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010374 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010375 ODRDiagNote(SecondMethod->getLocation(),
10376 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010377 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010378 ParameterMismatch = true;
10379 break;
10380 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010381
10382 const Expr *FirstInit = FirstParam->getInit();
10383 const Expr *SecondInit = SecondParam->getInit();
10384 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10385 ODRDiagError(FirstMethod->getLocation(),
10386 FirstMethod->getSourceRange(),
10387 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010388 << FirstMethodType << FirstName << (I + 1)
10389 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010390 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10391 ODRDiagNote(SecondMethod->getLocation(),
10392 SecondMethod->getSourceRange(),
10393 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010394 << SecondMethodType << SecondName << (I + 1)
10395 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010396 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10397 ParameterMismatch = true;
10398 break;
10399 }
10400
10401 if (FirstInit && SecondInit &&
10402 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10403 ODRDiagError(FirstMethod->getLocation(),
10404 FirstMethod->getSourceRange(),
10405 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010406 << FirstMethodType << FirstName << (I + 1)
10407 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010408 ODRDiagNote(SecondMethod->getLocation(),
10409 SecondMethod->getSourceRange(),
10410 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010411 << SecondMethodType << SecondName << (I + 1)
10412 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010413 ParameterMismatch = true;
10414 break;
10415
10416 }
Richard Trieu02552272017-05-02 23:58:52 +000010417 }
10418
10419 if (ParameterMismatch) {
10420 Diagnosed = true;
10421 break;
10422 }
10423
Richard Trieu7282d322018-04-25 00:31:15 +000010424 const auto *FirstTemplateArgs =
10425 FirstMethod->getTemplateSpecializationArgs();
10426 const auto *SecondTemplateArgs =
10427 SecondMethod->getTemplateSpecializationArgs();
10428
10429 if ((FirstTemplateArgs && !SecondTemplateArgs) ||
10430 (!FirstTemplateArgs && SecondTemplateArgs)) {
10431 ODRDiagError(FirstMethod->getLocation(),
10432 FirstMethod->getSourceRange(), MethodNoTemplateArguments)
10433 << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
10434 ODRDiagNote(SecondMethod->getLocation(),
10435 SecondMethod->getSourceRange(), MethodNoTemplateArguments)
10436 << SecondMethodType << SecondName
10437 << (SecondTemplateArgs != nullptr);
10438
10439 Diagnosed = true;
10440 break;
10441 }
10442
10443 if (FirstTemplateArgs && SecondTemplateArgs) {
10444 // Remove pack expansions from argument list.
10445 auto ExpandTemplateArgumentList =
10446 [](const TemplateArgumentList *TAL) {
10447 llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
10448 for (const TemplateArgument &TA : TAL->asArray()) {
10449 if (TA.getKind() != TemplateArgument::Pack) {
10450 ExpandedList.push_back(&TA);
10451 continue;
10452 }
10453 for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
10454 ExpandedList.push_back(&PackTA);
10455 }
10456 }
10457 return ExpandedList;
10458 };
10459 llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
10460 ExpandTemplateArgumentList(FirstTemplateArgs);
10461 llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
10462 ExpandTemplateArgumentList(SecondTemplateArgs);
10463
10464 if (FirstExpandedList.size() != SecondExpandedList.size()) {
10465 ODRDiagError(FirstMethod->getLocation(),
10466 FirstMethod->getSourceRange(),
10467 MethodDifferentNumberTemplateArguments)
10468 << FirstMethodType << FirstName
10469 << (unsigned)FirstExpandedList.size();
10470 ODRDiagNote(SecondMethod->getLocation(),
10471 SecondMethod->getSourceRange(),
10472 MethodDifferentNumberTemplateArguments)
10473 << SecondMethodType << SecondName
10474 << (unsigned)SecondExpandedList.size();
10475
10476 Diagnosed = true;
10477 break;
10478 }
10479
10480 bool TemplateArgumentMismatch = false;
10481 for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
10482 const TemplateArgument &FirstTA = *FirstExpandedList[i],
10483 &SecondTA = *SecondExpandedList[i];
10484 if (ComputeTemplateArgumentODRHash(FirstTA) ==
10485 ComputeTemplateArgumentODRHash(SecondTA)) {
10486 continue;
10487 }
10488
10489 ODRDiagError(FirstMethod->getLocation(),
10490 FirstMethod->getSourceRange(),
10491 MethodDifferentTemplateArgument)
10492 << FirstMethodType << FirstName << FirstTA << i + 1;
10493 ODRDiagNote(SecondMethod->getLocation(),
10494 SecondMethod->getSourceRange(),
10495 MethodDifferentTemplateArgument)
10496 << SecondMethodType << SecondName << SecondTA << i + 1;
10497
10498 TemplateArgumentMismatch = true;
10499 break;
10500 }
10501
10502 if (TemplateArgumentMismatch) {
10503 Diagnosed = true;
10504 break;
10505 }
10506 }
Richard Trieu48143742017-02-28 21:24:38 +000010507 break;
10508 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010509 case TypeAlias:
10510 case TypeDef: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010511 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10512 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
Richard Trieu11d566a2017-06-12 21:58:22 +000010513 auto FirstName = FirstTD->getDeclName();
10514 auto SecondName = SecondTD->getDeclName();
10515 if (FirstName != SecondName) {
10516 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10517 TypedefName)
10518 << (FirstDiffType == TypeAlias) << FirstName;
10519 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10520 TypedefName)
10521 << (FirstDiffType == TypeAlias) << SecondName;
10522 Diagnosed = true;
10523 break;
10524 }
10525
10526 QualType FirstType = FirstTD->getUnderlyingType();
10527 QualType SecondType = SecondTD->getUnderlyingType();
10528 if (ComputeQualTypeODRHash(FirstType) !=
10529 ComputeQualTypeODRHash(SecondType)) {
10530 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10531 TypedefType)
10532 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10533 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10534 TypedefType)
10535 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10536 Diagnosed = true;
10537 break;
10538 }
10539 break;
10540 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010541 case Var: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010542 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10543 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
Richard Trieu6e13ff32017-06-16 02:44:29 +000010544 auto FirstName = FirstVD->getDeclName();
10545 auto SecondName = SecondVD->getDeclName();
10546 if (FirstName != SecondName) {
10547 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10548 VarName)
10549 << FirstName;
10550 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10551 VarName)
10552 << SecondName;
10553 Diagnosed = true;
10554 break;
10555 }
10556
10557 QualType FirstType = FirstVD->getType();
10558 QualType SecondType = SecondVD->getType();
10559 if (ComputeQualTypeODRHash(FirstType) !=
10560 ComputeQualTypeODRHash(SecondType)) {
10561 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10562 VarType)
10563 << FirstName << FirstType;
10564 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10565 VarType)
10566 << SecondName << SecondType;
10567 Diagnosed = true;
10568 break;
10569 }
10570
10571 const Expr *FirstInit = FirstVD->getInit();
10572 const Expr *SecondInit = SecondVD->getInit();
10573 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10574 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10575 VarSingleInitializer)
10576 << FirstName << (FirstInit == nullptr)
10577 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10578 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10579 VarSingleInitializer)
10580 << SecondName << (SecondInit == nullptr)
10581 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10582 Diagnosed = true;
10583 break;
10584 }
10585
10586 if (FirstInit && SecondInit &&
10587 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10588 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10589 VarDifferentInitializer)
10590 << FirstName << FirstInit->getSourceRange();
10591 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10592 VarDifferentInitializer)
10593 << SecondName << SecondInit->getSourceRange();
10594 Diagnosed = true;
10595 break;
10596 }
10597
10598 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10599 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10600 if (FirstIsConstexpr != SecondIsConstexpr) {
10601 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10602 VarConstexpr)
10603 << FirstName << FirstIsConstexpr;
10604 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10605 VarConstexpr)
10606 << SecondName << SecondIsConstexpr;
10607 Diagnosed = true;
10608 break;
10609 }
10610 break;
10611 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010612 case Friend: {
Vedant Kumar48b4f762018-04-14 01:40:48 +000010613 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10614 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
Richard Trieuac6a1b62017-07-08 02:04:42 +000010615
10616 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10617 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10618
10619 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10620 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10621
10622 if (FirstND && SecondND) {
10623 ODRDiagError(FirstFriend->getFriendLoc(),
10624 FirstFriend->getSourceRange(), FriendFunction)
10625 << FirstND;
10626 ODRDiagNote(SecondFriend->getFriendLoc(),
10627 SecondFriend->getSourceRange(), FriendFunction)
10628 << SecondND;
10629
10630 Diagnosed = true;
10631 break;
10632 }
10633
10634 if (FirstTSI && SecondTSI) {
10635 QualType FirstFriendType = FirstTSI->getType();
10636 QualType SecondFriendType = SecondTSI->getType();
10637 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10638 ComputeQualTypeODRHash(SecondFriendType));
10639 ODRDiagError(FirstFriend->getFriendLoc(),
10640 FirstFriend->getSourceRange(), FriendType)
10641 << FirstFriendType;
10642 ODRDiagNote(SecondFriend->getFriendLoc(),
10643 SecondFriend->getSourceRange(), FriendType)
10644 << SecondFriendType;
10645 Diagnosed = true;
10646 break;
10647 }
10648
10649 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10650 FriendTypeFunction)
10651 << (FirstTSI == nullptr);
10652 ODRDiagNote(SecondFriend->getFriendLoc(),
10653 SecondFriend->getSourceRange(), FriendTypeFunction)
10654 << (SecondTSI == nullptr);
10655
10656 Diagnosed = true;
10657 break;
10658 }
Richard Trieu9359e8f2018-05-30 01:12:26 +000010659 case FunctionTemplate: {
10660 FunctionTemplateDecl *FirstTemplate =
10661 cast<FunctionTemplateDecl>(FirstDecl);
10662 FunctionTemplateDecl *SecondTemplate =
10663 cast<FunctionTemplateDecl>(SecondDecl);
10664
10665 TemplateParameterList *FirstTPL =
10666 FirstTemplate->getTemplateParameters();
10667 TemplateParameterList *SecondTPL =
10668 SecondTemplate->getTemplateParameters();
10669
10670 if (FirstTPL->size() != SecondTPL->size()) {
10671 ODRDiagError(FirstTemplate->getLocation(),
10672 FirstTemplate->getSourceRange(),
10673 FunctionTemplateDifferentNumberParameters)
10674 << FirstTemplate << FirstTPL->size();
10675 ODRDiagNote(SecondTemplate->getLocation(),
10676 SecondTemplate->getSourceRange(),
10677 FunctionTemplateDifferentNumberParameters)
10678 << SecondTemplate << SecondTPL->size();
10679
10680 Diagnosed = true;
10681 break;
10682 }
10683
10684 bool ParameterMismatch = false;
10685 for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
10686 NamedDecl *FirstParam = FirstTPL->getParam(i);
10687 NamedDecl *SecondParam = SecondTPL->getParam(i);
10688
10689 if (FirstParam->getKind() != SecondParam->getKind()) {
10690 enum {
10691 TemplateTypeParameter,
10692 NonTypeTemplateParameter,
10693 TemplateTemplateParameter,
10694 };
10695 auto GetParamType = [](NamedDecl *D) {
10696 switch (D->getKind()) {
10697 default:
10698 llvm_unreachable("Unexpected template parameter type");
10699 case Decl::TemplateTypeParm:
10700 return TemplateTypeParameter;
10701 case Decl::NonTypeTemplateParm:
10702 return NonTypeTemplateParameter;
10703 case Decl::TemplateTemplateParm:
10704 return TemplateTemplateParameter;
10705 }
10706 };
10707
10708 ODRDiagError(FirstTemplate->getLocation(),
10709 FirstTemplate->getSourceRange(),
10710 FunctionTemplateParameterDifferentKind)
10711 << FirstTemplate << (i + 1) << GetParamType(FirstParam);
10712 ODRDiagNote(SecondTemplate->getLocation(),
10713 SecondTemplate->getSourceRange(),
10714 FunctionTemplateParameterDifferentKind)
10715 << SecondTemplate << (i + 1) << GetParamType(SecondParam);
10716
10717 ParameterMismatch = true;
10718 break;
10719 }
10720
10721 if (FirstParam->getName() != SecondParam->getName()) {
10722 ODRDiagError(FirstTemplate->getLocation(),
10723 FirstTemplate->getSourceRange(),
10724 FunctionTemplateParameterName)
10725 << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
10726 << FirstParam;
10727 ODRDiagNote(SecondTemplate->getLocation(),
10728 SecondTemplate->getSourceRange(),
10729 FunctionTemplateParameterName)
10730 << SecondTemplate << (i + 1)
10731 << (bool)SecondParam->getIdentifier() << SecondParam;
10732 ParameterMismatch = true;
10733 break;
10734 }
10735
10736 if (isa<TemplateTypeParmDecl>(FirstParam) &&
10737 isa<TemplateTypeParmDecl>(SecondParam)) {
10738 TemplateTypeParmDecl *FirstTTPD =
10739 cast<TemplateTypeParmDecl>(FirstParam);
10740 TemplateTypeParmDecl *SecondTTPD =
10741 cast<TemplateTypeParmDecl>(SecondParam);
10742 bool HasFirstDefaultArgument =
10743 FirstTTPD->hasDefaultArgument() &&
10744 !FirstTTPD->defaultArgumentWasInherited();
10745 bool HasSecondDefaultArgument =
10746 SecondTTPD->hasDefaultArgument() &&
10747 !SecondTTPD->defaultArgumentWasInherited();
10748 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10749 ODRDiagError(FirstTemplate->getLocation(),
10750 FirstTemplate->getSourceRange(),
10751 FunctionTemplateParameterSingleDefaultArgument)
10752 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10753 ODRDiagNote(SecondTemplate->getLocation(),
10754 SecondTemplate->getSourceRange(),
10755 FunctionTemplateParameterSingleDefaultArgument)
10756 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10757 ParameterMismatch = true;
10758 break;
10759 }
10760
10761 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10762 QualType FirstType = FirstTTPD->getDefaultArgument();
10763 QualType SecondType = SecondTTPD->getDefaultArgument();
10764 if (ComputeQualTypeODRHash(FirstType) !=
10765 ComputeQualTypeODRHash(SecondType)) {
10766 ODRDiagError(FirstTemplate->getLocation(),
10767 FirstTemplate->getSourceRange(),
10768 FunctionTemplateParameterDifferentDefaultArgument)
10769 << FirstTemplate << (i + 1) << FirstType;
10770 ODRDiagNote(SecondTemplate->getLocation(),
10771 SecondTemplate->getSourceRange(),
10772 FunctionTemplateParameterDifferentDefaultArgument)
10773 << SecondTemplate << (i + 1) << SecondType;
10774 ParameterMismatch = true;
10775 break;
10776 }
10777 }
10778
10779 if (FirstTTPD->isParameterPack() !=
10780 SecondTTPD->isParameterPack()) {
10781 ODRDiagError(FirstTemplate->getLocation(),
10782 FirstTemplate->getSourceRange(),
10783 FunctionTemplatePackParameter)
10784 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10785 ODRDiagNote(SecondTemplate->getLocation(),
10786 SecondTemplate->getSourceRange(),
10787 FunctionTemplatePackParameter)
10788 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10789 ParameterMismatch = true;
10790 break;
10791 }
10792 }
10793
10794 if (isa<TemplateTemplateParmDecl>(FirstParam) &&
10795 isa<TemplateTemplateParmDecl>(SecondParam)) {
10796 TemplateTemplateParmDecl *FirstTTPD =
10797 cast<TemplateTemplateParmDecl>(FirstParam);
10798 TemplateTemplateParmDecl *SecondTTPD =
10799 cast<TemplateTemplateParmDecl>(SecondParam);
10800
10801 TemplateParameterList *FirstTPL =
10802 FirstTTPD->getTemplateParameters();
10803 TemplateParameterList *SecondTPL =
10804 SecondTTPD->getTemplateParameters();
10805
10806 if (ComputeTemplateParameterListODRHash(FirstTPL) !=
10807 ComputeTemplateParameterListODRHash(SecondTPL)) {
10808 ODRDiagError(FirstTemplate->getLocation(),
10809 FirstTemplate->getSourceRange(),
10810 FunctionTemplateParameterDifferentType)
10811 << FirstTemplate << (i + 1);
10812 ODRDiagNote(SecondTemplate->getLocation(),
10813 SecondTemplate->getSourceRange(),
10814 FunctionTemplateParameterDifferentType)
10815 << SecondTemplate << (i + 1);
10816 ParameterMismatch = true;
10817 break;
10818 }
10819
10820 bool HasFirstDefaultArgument =
10821 FirstTTPD->hasDefaultArgument() &&
10822 !FirstTTPD->defaultArgumentWasInherited();
10823 bool HasSecondDefaultArgument =
10824 SecondTTPD->hasDefaultArgument() &&
10825 !SecondTTPD->defaultArgumentWasInherited();
10826 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10827 ODRDiagError(FirstTemplate->getLocation(),
10828 FirstTemplate->getSourceRange(),
10829 FunctionTemplateParameterSingleDefaultArgument)
10830 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10831 ODRDiagNote(SecondTemplate->getLocation(),
10832 SecondTemplate->getSourceRange(),
10833 FunctionTemplateParameterSingleDefaultArgument)
10834 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10835 ParameterMismatch = true;
10836 break;
10837 }
10838
10839 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10840 TemplateArgument FirstTA =
10841 FirstTTPD->getDefaultArgument().getArgument();
10842 TemplateArgument SecondTA =
10843 SecondTTPD->getDefaultArgument().getArgument();
10844 if (ComputeTemplateArgumentODRHash(FirstTA) !=
10845 ComputeTemplateArgumentODRHash(SecondTA)) {
10846 ODRDiagError(FirstTemplate->getLocation(),
10847 FirstTemplate->getSourceRange(),
10848 FunctionTemplateParameterDifferentDefaultArgument)
10849 << FirstTemplate << (i + 1) << FirstTA;
10850 ODRDiagNote(SecondTemplate->getLocation(),
10851 SecondTemplate->getSourceRange(),
10852 FunctionTemplateParameterDifferentDefaultArgument)
10853 << SecondTemplate << (i + 1) << SecondTA;
10854 ParameterMismatch = true;
10855 break;
10856 }
10857 }
10858
10859 if (FirstTTPD->isParameterPack() !=
10860 SecondTTPD->isParameterPack()) {
10861 ODRDiagError(FirstTemplate->getLocation(),
10862 FirstTemplate->getSourceRange(),
10863 FunctionTemplatePackParameter)
10864 << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
10865 ODRDiagNote(SecondTemplate->getLocation(),
10866 SecondTemplate->getSourceRange(),
10867 FunctionTemplatePackParameter)
10868 << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
10869 ParameterMismatch = true;
10870 break;
10871 }
10872 }
10873
10874 if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
10875 isa<NonTypeTemplateParmDecl>(SecondParam)) {
10876 NonTypeTemplateParmDecl *FirstNTTPD =
10877 cast<NonTypeTemplateParmDecl>(FirstParam);
10878 NonTypeTemplateParmDecl *SecondNTTPD =
10879 cast<NonTypeTemplateParmDecl>(SecondParam);
10880
10881 QualType FirstType = FirstNTTPD->getType();
10882 QualType SecondType = SecondNTTPD->getType();
10883 if (ComputeQualTypeODRHash(FirstType) !=
10884 ComputeQualTypeODRHash(SecondType)) {
10885 ODRDiagError(FirstTemplate->getLocation(),
10886 FirstTemplate->getSourceRange(),
10887 FunctionTemplateParameterDifferentType)
10888 << FirstTemplate << (i + 1);
10889 ODRDiagNote(SecondTemplate->getLocation(),
10890 SecondTemplate->getSourceRange(),
10891 FunctionTemplateParameterDifferentType)
10892 << SecondTemplate << (i + 1);
10893 ParameterMismatch = true;
10894 break;
10895 }
10896
10897 bool HasFirstDefaultArgument =
10898 FirstNTTPD->hasDefaultArgument() &&
10899 !FirstNTTPD->defaultArgumentWasInherited();
10900 bool HasSecondDefaultArgument =
10901 SecondNTTPD->hasDefaultArgument() &&
10902 !SecondNTTPD->defaultArgumentWasInherited();
10903 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
10904 ODRDiagError(FirstTemplate->getLocation(),
10905 FirstTemplate->getSourceRange(),
10906 FunctionTemplateParameterSingleDefaultArgument)
10907 << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
10908 ODRDiagNote(SecondTemplate->getLocation(),
10909 SecondTemplate->getSourceRange(),
10910 FunctionTemplateParameterSingleDefaultArgument)
10911 << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
10912 ParameterMismatch = true;
10913 break;
10914 }
10915
10916 if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
10917 Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
10918 Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
10919 if (ComputeODRHash(FirstDefaultArgument) !=
10920 ComputeODRHash(SecondDefaultArgument)) {
10921 ODRDiagError(FirstTemplate->getLocation(),
10922 FirstTemplate->getSourceRange(),
10923 FunctionTemplateParameterDifferentDefaultArgument)
10924 << FirstTemplate << (i + 1) << FirstDefaultArgument;
10925 ODRDiagNote(SecondTemplate->getLocation(),
10926 SecondTemplate->getSourceRange(),
10927 FunctionTemplateParameterDifferentDefaultArgument)
10928 << SecondTemplate << (i + 1) << SecondDefaultArgument;
10929 ParameterMismatch = true;
10930 break;
10931 }
10932 }
10933
10934 if (FirstNTTPD->isParameterPack() !=
10935 SecondNTTPD->isParameterPack()) {
10936 ODRDiagError(FirstTemplate->getLocation(),
10937 FirstTemplate->getSourceRange(),
10938 FunctionTemplatePackParameter)
10939 << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
10940 ODRDiagNote(SecondTemplate->getLocation(),
10941 SecondTemplate->getSourceRange(),
10942 FunctionTemplatePackParameter)
10943 << SecondTemplate << (i + 1)
10944 << SecondNTTPD->isParameterPack();
10945 ParameterMismatch = true;
10946 break;
10947 }
10948 }
10949 }
10950
10951 if (ParameterMismatch) {
10952 Diagnosed = true;
10953 break;
10954 }
10955
10956 break;
10957 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010958 }
10959
Eugene Zelenkob8c9e2a2017-11-08 01:03:16 +000010960 if (Diagnosed)
Richard Trieue7f7ed22017-02-22 01:11:25 +000010961 continue;
10962
Richard Trieu708859a2017-06-08 00:56:21 +000010963 Diag(FirstDecl->getLocation(),
10964 diag::err_module_odr_violation_mismatch_decl_unknown)
10965 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10966 << FirstDecl->getSourceRange();
10967 Diag(SecondDecl->getLocation(),
10968 diag::note_module_odr_violation_mismatch_decl_unknown)
10969 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010970 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010971 }
10972
10973 if (!Diagnosed) {
10974 // All definitions are updates to the same declaration. This happens if a
10975 // module instantiates the declaration of a class template specialization
10976 // and two or more other modules instantiate its definition.
10977 //
10978 // FIXME: Indicate which modules had instantiations of this definition.
10979 // FIXME: How can this even happen?
10980 Diag(Merge.first->getLocation(),
10981 diag::err_module_odr_violation_different_instantiations)
10982 << Merge.first;
10983 }
10984 }
Richard Trieue6caa262017-12-23 00:41:01 +000010985
10986 // Issue ODR failures diagnostics for functions.
10987 for (auto &Merge : FunctionOdrMergeFailures) {
10988 enum ODRFunctionDifference {
10989 ReturnType,
10990 ParameterName,
10991 ParameterType,
10992 ParameterSingleDefaultArgument,
10993 ParameterDifferentDefaultArgument,
10994 FunctionBody,
10995 };
10996
10997 FunctionDecl *FirstFunction = Merge.first;
10998 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
10999
11000 bool Diagnosed = false;
11001 for (auto &SecondFunction : Merge.second) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011002
Richard Trieue6caa262017-12-23 00:41:01 +000011003 if (FirstFunction == SecondFunction)
11004 continue;
11005
11006 std::string SecondModule =
11007 getOwningModuleNameForDiagnostic(SecondFunction);
11008
11009 auto ODRDiagError = [FirstFunction, &FirstModule,
11010 this](SourceLocation Loc, SourceRange Range,
11011 ODRFunctionDifference DiffType) {
11012 return Diag(Loc, diag::err_module_odr_violation_function)
11013 << FirstFunction << FirstModule.empty() << FirstModule << Range
11014 << DiffType;
11015 };
11016 auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
11017 SourceRange Range,
11018 ODRFunctionDifference DiffType) {
11019 return Diag(Loc, diag::note_module_odr_violation_function)
11020 << SecondModule << Range << DiffType;
11021 };
11022
11023 if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
11024 ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
11025 ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
11026 FirstFunction->getReturnTypeSourceRange(), ReturnType)
11027 << FirstFunction->getReturnType();
11028 ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
11029 SecondFunction->getReturnTypeSourceRange(), ReturnType)
11030 << SecondFunction->getReturnType();
11031 Diagnosed = true;
11032 break;
11033 }
11034
11035 assert(FirstFunction->param_size() == SecondFunction->param_size() &&
11036 "Merged functions with different number of parameters");
11037
11038 auto ParamSize = FirstFunction->param_size();
11039 bool ParameterMismatch = false;
11040 for (unsigned I = 0; I < ParamSize; ++I) {
11041 auto *FirstParam = FirstFunction->getParamDecl(I);
11042 auto *SecondParam = SecondFunction->getParamDecl(I);
11043
11044 assert(getContext().hasSameType(FirstParam->getType(),
11045 SecondParam->getType()) &&
11046 "Merged function has different parameter types.");
11047
11048 if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
11049 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11050 ParameterName)
11051 << I + 1 << FirstParam->getDeclName();
11052 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11053 ParameterName)
11054 << I + 1 << SecondParam->getDeclName();
11055 ParameterMismatch = true;
11056 break;
11057 };
11058
11059 QualType FirstParamType = FirstParam->getType();
11060 QualType SecondParamType = SecondParam->getType();
11061 if (FirstParamType != SecondParamType &&
11062 ComputeQualTypeODRHash(FirstParamType) !=
11063 ComputeQualTypeODRHash(SecondParamType)) {
Vedant Kumar48b4f762018-04-14 01:40:48 +000011064 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011065 FirstParamType->getAs<DecayedType>()) {
11066 ODRDiagError(FirstParam->getLocation(),
11067 FirstParam->getSourceRange(), ParameterType)
11068 << (I + 1) << FirstParamType << true
11069 << ParamDecayedType->getOriginalType();
11070 } else {
11071 ODRDiagError(FirstParam->getLocation(),
11072 FirstParam->getSourceRange(), ParameterType)
11073 << (I + 1) << FirstParamType << false;
11074 }
11075
Vedant Kumar48b4f762018-04-14 01:40:48 +000011076 if (const DecayedType *ParamDecayedType =
Richard Trieue6caa262017-12-23 00:41:01 +000011077 SecondParamType->getAs<DecayedType>()) {
11078 ODRDiagNote(SecondParam->getLocation(),
11079 SecondParam->getSourceRange(), ParameterType)
11080 << (I + 1) << SecondParamType << true
11081 << ParamDecayedType->getOriginalType();
11082 } else {
11083 ODRDiagNote(SecondParam->getLocation(),
11084 SecondParam->getSourceRange(), ParameterType)
11085 << (I + 1) << SecondParamType << false;
11086 }
11087 ParameterMismatch = true;
11088 break;
11089 }
11090
11091 const Expr *FirstInit = FirstParam->getInit();
11092 const Expr *SecondInit = SecondParam->getInit();
11093 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
11094 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11095 ParameterSingleDefaultArgument)
11096 << (I + 1) << (FirstInit == nullptr)
11097 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
11098 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11099 ParameterSingleDefaultArgument)
11100 << (I + 1) << (SecondInit == nullptr)
11101 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
11102 ParameterMismatch = true;
11103 break;
11104 }
11105
11106 if (FirstInit && SecondInit &&
11107 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
11108 ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
11109 ParameterDifferentDefaultArgument)
11110 << (I + 1) << FirstInit->getSourceRange();
11111 ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
11112 ParameterDifferentDefaultArgument)
11113 << (I + 1) << SecondInit->getSourceRange();
11114 ParameterMismatch = true;
11115 break;
11116 }
11117
11118 assert(ComputeSubDeclODRHash(FirstParam) ==
11119 ComputeSubDeclODRHash(SecondParam) &&
11120 "Undiagnosed parameter difference.");
11121 }
11122
11123 if (ParameterMismatch) {
11124 Diagnosed = true;
11125 break;
11126 }
11127
11128 // If no error has been generated before now, assume the problem is in
11129 // the body and generate a message.
11130 ODRDiagError(FirstFunction->getLocation(),
11131 FirstFunction->getSourceRange(), FunctionBody);
11132 ODRDiagNote(SecondFunction->getLocation(),
11133 SecondFunction->getSourceRange(), FunctionBody);
11134 Diagnosed = true;
11135 break;
11136 }
Evgeny Stupachenkobf25d672018-01-05 02:22:52 +000011137 (void)Diagnosed;
Richard Trieue6caa262017-12-23 00:41:01 +000011138 assert(Diagnosed && "Unable to emit ODR diagnostic.");
11139 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011140}
11141
Richard Smithce18a182015-07-14 00:26:00 +000011142void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000011143 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000011144 ReadTimer->startTimer();
11145}
11146
Guy Benyei11169dd2012-12-18 14:30:41 +000011147void ASTReader::FinishedDeserializing() {
11148 assert(NumCurrentElementsDeserializing &&
11149 "FinishedDeserializing not paired with StartedDeserializing");
11150 if (NumCurrentElementsDeserializing == 1) {
11151 // We decrease NumCurrentElementsDeserializing only after pending actions
11152 // are finished, to avoid recursively re-calling finishPendingActions().
11153 finishPendingActions();
11154 }
11155 --NumCurrentElementsDeserializing;
11156
Richard Smitha0ce9c42014-07-29 23:23:27 +000011157 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011158 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000011159 while (!PendingExceptionSpecUpdates.empty()) {
11160 auto Updates = std::move(PendingExceptionSpecUpdates);
11161 PendingExceptionSpecUpdates.clear();
11162 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000011163 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000011164 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000011165 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000011166 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000011167 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000011168 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000011169 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000011170 }
Richard Smith9e2341d2015-03-23 03:25:59 +000011171 }
11172
Richard Smithce18a182015-07-14 00:26:00 +000011173 if (ReadTimer)
11174 ReadTimer->stopTimer();
11175
Richard Smith0f4e2c42015-08-06 04:23:48 +000011176 diagnoseOdrViolations();
11177
Richard Smith04d05b52014-03-23 00:27:18 +000011178 // We are not in recursive loading, so it's safe to pass the "interesting"
11179 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000011180 if (Consumer)
11181 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000011182 }
11183}
11184
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011185void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000011186 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
11187 // Remove any fake results before adding any real ones.
11188 auto It = PendingFakeLookupResults.find(II);
11189 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000011190 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000011191 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000011192 // FIXME: this works around module+PCH performance issue.
11193 // Rather than erase the result from the map, which is O(n), just clear
11194 // the vector of NamedDecls.
11195 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000011196 }
11197 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000011198
11199 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
11200 SemaObj->TUScope->AddDecl(D);
11201 } else if (SemaObj->TUScope) {
11202 // Adding the decl to IdResolver may have failed because it was already in
11203 // (even though it was not added in scope). If it is already in, make sure
11204 // it gets in the scope as well.
11205 if (std::find(SemaObj->IdResolver.begin(Name),
11206 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
11207 SemaObj->TUScope->AddDecl(D);
11208 }
11209}
11210
Richard Smithdbafb6c2017-06-29 23:23:46 +000011211ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000011212 const PCHContainerReader &PCHContainerRdr,
11213 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
11214 StringRef isysroot, bool DisableValidation,
11215 bool AllowASTWithCompilerErrors,
11216 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
11217 bool UseGlobalIndex,
11218 std::unique_ptr<llvm::Timer> ReadTimer)
11219 : Listener(DisableValidation
11220 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
11221 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000011222 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011223 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000011224 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000011225 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
11226 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000011227 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
11228 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000011229 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000011230 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
11231 AllowConfigurationMismatch(AllowConfigurationMismatch),
11232 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000011233 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000011234 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000011235
11236 for (const auto &Ext : Extensions) {
11237 auto BlockName = Ext->getExtensionMetadata().BlockName;
11238 auto Known = ModuleFileExtensions.find(BlockName);
11239 if (Known != ModuleFileExtensions.end()) {
11240 Diags.Report(diag::warn_duplicate_module_file_extension)
11241 << BlockName;
11242 continue;
11243 }
11244
11245 ModuleFileExtensions.insert({BlockName, Ext});
11246 }
Guy Benyei11169dd2012-12-18 14:30:41 +000011247}
11248
11249ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000011250 if (OwnsDeserializationListener)
11251 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000011252}
Richard Smith10379092016-05-06 23:14:07 +000011253
11254IdentifierResolver &ASTReader::getIdResolver() {
11255 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
11256}
David L. Jonesbe1557a2016-12-21 00:17:49 +000011257
11258unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
11259 unsigned AbbrevID) {
11260 Idx = 0;
11261 Record.clear();
11262 return Cursor.readRecord(AbbrevID, Record);
11263}