blob: da8e5ff6b903ca681a8d9b9e199b7d5921aea349 [file] [log] [blame]
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +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"
22#include "clang/AST/DeclCXX.h"
23#include "clang/AST/DeclGroup.h"
24#include "clang/AST/DeclObjC.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/NestedNameSpecifier.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000029#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000030#include "clang/AST/Type.h"
31#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000035#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000036#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000037#include "clang/Basic/FileSystemOptions.h"
38#include "clang/Basic/LangOptions.h"
39#include "clang/Basic/ObjCRuntime.h"
40#include "clang/Basic/OperatorKinds.h"
41#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000042#include "clang/Basic/SourceManager.h"
43#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000044#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000045#include "clang/Basic/TargetInfo.h"
46#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000047#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000048#include "clang/Basic/Version.h"
49#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000050#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000051#include "clang/Lex/HeaderSearch.h"
52#include "clang/Lex/HeaderSearchOptions.h"
53#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000055#include "clang/Lex/PreprocessingRecord.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/Scope.h"
59#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000061#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000062#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ModuleManager.h"
64#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/ADT/APFloat.h"
66#include "llvm/ADT/APInt.h"
67#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000068#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000069#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000070#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000073#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000074#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000075#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000076#include "llvm/Support/ErrorHandling.h"
77#include "llvm/Support/FileSystem.h"
78#include "llvm/Support/MemoryBuffer.h"
79#include "llvm/Support/Path.h"
80#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000081#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000082#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000083#include <cassert>
84#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000085#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086#include <cstring>
87#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000088#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000089#include <limits>
90#include <map>
91#include <memory>
92#include <new>
93#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000094#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000095#include <tuple>
96#include <utility>
97#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +000098
99using namespace clang;
100using namespace clang::serialization;
101using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000102using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000103
Ben Langmuircb69b572014-03-07 06:40:32 +0000104//===----------------------------------------------------------------------===//
105// ChainedASTReaderListener implementation
106//===----------------------------------------------------------------------===//
107
108bool
109ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
110 return First->ReadFullVersionInformation(FullVersion) ||
111 Second->ReadFullVersionInformation(FullVersion);
112}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000113
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000114void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
115 First->ReadModuleName(ModuleName);
116 Second->ReadModuleName(ModuleName);
117}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000118
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000119void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
120 First->ReadModuleMapFile(ModuleMapPath);
121 Second->ReadModuleMapFile(ModuleMapPath);
122}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000123
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000124bool
125ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
126 bool Complain,
127 bool AllowCompatibleDifferences) {
128 return First->ReadLanguageOptions(LangOpts, Complain,
129 AllowCompatibleDifferences) ||
130 Second->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000132}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000133
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000134bool ChainedASTReaderListener::ReadTargetOptions(
135 const TargetOptions &TargetOpts, bool Complain,
136 bool AllowCompatibleDifferences) {
137 return First->ReadTargetOptions(TargetOpts, Complain,
138 AllowCompatibleDifferences) ||
139 Second->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000141}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000142
Ben Langmuircb69b572014-03-07 06:40:32 +0000143bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000144 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000145 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
146 Second->ReadDiagnosticOptions(DiagOpts, Complain);
147}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000148
Ben Langmuircb69b572014-03-07 06:40:32 +0000149bool
150ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
151 bool Complain) {
152 return First->ReadFileSystemOptions(FSOpts, Complain) ||
153 Second->ReadFileSystemOptions(FSOpts, Complain);
154}
155
156bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000157 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
158 bool Complain) {
159 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
160 Complain) ||
161 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000164
Ben Langmuircb69b572014-03-07 06:40:32 +0000165bool ChainedASTReaderListener::ReadPreprocessorOptions(
166 const PreprocessorOptions &PPOpts, bool Complain,
167 std::string &SuggestedPredefines) {
168 return First->ReadPreprocessorOptions(PPOpts, Complain,
169 SuggestedPredefines) ||
170 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
171}
172void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
173 unsigned Value) {
174 First->ReadCounter(M, Value);
175 Second->ReadCounter(M, Value);
176}
177bool ChainedASTReaderListener::needsInputFileVisitation() {
178 return First->needsInputFileVisitation() ||
179 Second->needsInputFileVisitation();
180}
181bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
182 return First->needsSystemInputFileVisitation() ||
183 Second->needsSystemInputFileVisitation();
184}
Richard Smith216a3bd2015-08-13 17:57:10 +0000185void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
186 ModuleKind Kind) {
187 First->visitModuleFile(Filename, Kind);
188 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000189}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000190
Ben Langmuircb69b572014-03-07 06:40:32 +0000191bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000192 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000193 bool isOverridden,
194 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000195 bool Continue = false;
196 if (First->needsInputFileVisitation() &&
197 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000198 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
199 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000200 if (Second->needsInputFileVisitation() &&
201 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000202 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
203 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000204 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000205}
206
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000207void ChainedASTReaderListener::readModuleFileExtension(
208 const ModuleFileExtensionMetadata &Metadata) {
209 First->readModuleFileExtension(Metadata);
210 Second->readModuleFileExtension(Metadata);
211}
212
Guy Benyei11169dd2012-12-18 14:30:41 +0000213//===----------------------------------------------------------------------===//
214// PCH validator implementation
215//===----------------------------------------------------------------------===//
216
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000217ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000218
219/// \brief Compare the given set of language options against an existing set of
220/// language options.
221///
222/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000223/// \param AllowCompatibleDifferences If true, differences between compatible
224/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225///
226/// \returns true if the languagae options mis-match, false otherwise.
227static bool checkLanguageOptions(const LangOptions &LangOpts,
228 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000229 DiagnosticsEngine *Diags,
230 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000231#define LANGOPT(Name, Bits, Default, Description) \
232 if (ExistingLangOpts.Name != LangOpts.Name) { \
233 if (Diags) \
234 Diags->Report(diag::err_pch_langopt_mismatch) \
235 << Description << LangOpts.Name << ExistingLangOpts.Name; \
236 return true; \
237 }
238
239#define VALUE_LANGOPT(Name, Bits, Default, Description) \
240 if (ExistingLangOpts.Name != LangOpts.Name) { \
241 if (Diags) \
242 Diags->Report(diag::err_pch_langopt_value_mismatch) \
243 << Description; \
244 return true; \
245 }
246
247#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
248 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
249 if (Diags) \
250 Diags->Report(diag::err_pch_langopt_value_mismatch) \
251 << Description; \
252 return true; \
253 }
254
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000255#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
256 if (!AllowCompatibleDifferences) \
257 LANGOPT(Name, Bits, Default, Description)
258
259#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
260 if (!AllowCompatibleDifferences) \
261 ENUM_LANGOPT(Name, Bits, Default, Description)
262
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000263#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
264 if (!AllowCompatibleDifferences) \
265 VALUE_LANGOPT(Name, Bits, Default, Description)
266
Guy Benyei11169dd2012-12-18 14:30:41 +0000267#define BENIGN_LANGOPT(Name, Bits, Default, Description)
268#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000269#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000270#include "clang/Basic/LangOptions.def"
271
Ben Langmuircd98cb72015-06-23 18:20:18 +0000272 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
273 if (Diags)
274 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
275 return true;
276 }
277
Guy Benyei11169dd2012-12-18 14:30:41 +0000278 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
279 if (Diags)
280 Diags->Report(diag::err_pch_langopt_value_mismatch)
281 << "target Objective-C runtime";
282 return true;
283 }
284
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000285 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
286 LangOpts.CommentOpts.BlockCommandNames) {
287 if (Diags)
288 Diags->Report(diag::err_pch_langopt_value_mismatch)
289 << "block command names";
290 return true;
291 }
292
Guy Benyei11169dd2012-12-18 14:30:41 +0000293 return false;
294}
295
296/// \brief Compare the given set of target options against an existing set of
297/// target options.
298///
299/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
300///
301/// \returns true if the target options mis-match, false otherwise.
302static bool checkTargetOptions(const TargetOptions &TargetOpts,
303 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000304 DiagnosticsEngine *Diags,
305 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000306#define CHECK_TARGET_OPT(Field, Name) \
307 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
308 if (Diags) \
309 Diags->Report(diag::err_pch_targetopt_mismatch) \
310 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
311 return true; \
312 }
313
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000314 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000315 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000317
318 // We can tolerate different CPUs in many cases, notably when one CPU
319 // supports a strict superset of another. When allowing compatible
320 // differences skip this check.
321 if (!AllowCompatibleDifferences)
322 CHECK_TARGET_OPT(CPU, "target CPU");
323
Guy Benyei11169dd2012-12-18 14:30:41 +0000324#undef CHECK_TARGET_OPT
325
326 // Compare feature sets.
327 SmallVector<StringRef, 4> ExistingFeatures(
328 ExistingTargetOpts.FeaturesAsWritten.begin(),
329 ExistingTargetOpts.FeaturesAsWritten.end());
330 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
331 TargetOpts.FeaturesAsWritten.end());
332 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
333 std::sort(ReadFeatures.begin(), ReadFeatures.end());
334
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000335 // We compute the set difference in both directions explicitly so that we can
336 // diagnose the differences differently.
337 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
338 std::set_difference(
339 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
340 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
341 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
342 ExistingFeatures.begin(), ExistingFeatures.end(),
343 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000344
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000345 // If we are allowing compatible differences and the read feature set is
346 // a strict subset of the existing feature set, there is nothing to diagnose.
347 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
348 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000349
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000350 if (Diags) {
351 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000353 << /* is-existing-feature */ false << Feature;
354 for (StringRef Feature : UnmatchedExistingFeatures)
355 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
356 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000357 }
358
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000359 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000360}
361
362bool
363PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000364 bool Complain,
365 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000366 const LangOptions &ExistingLangOpts = PP.getLangOpts();
367 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000368 Complain ? &Reader.Diags : nullptr,
369 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000370}
371
372bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000373 bool Complain,
374 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000375 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
376 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000377 Complain ? &Reader.Diags : nullptr,
378 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000379}
380
381namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
384 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000385 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
386 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000387
388} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000389
Ben Langmuirb92de022014-04-29 16:25:26 +0000390static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
391 DiagnosticsEngine &Diags,
392 bool Complain) {
393 typedef DiagnosticsEngine::Level Level;
394
395 // Check current mappings for new -Werror mappings, and the stored mappings
396 // for cases that were explicitly mapped to *not* be errors that are now
397 // errors because of options like -Werror.
398 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
399
400 for (DiagnosticsEngine *MappingSource : MappingSources) {
401 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
402 diag::kind DiagID = DiagIDMappingPair.first;
403 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
404 if (CurLevel < DiagnosticsEngine::Error)
405 continue; // not significant
406 Level StoredLevel =
407 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
408 if (StoredLevel < DiagnosticsEngine::Error) {
409 if (Complain)
410 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
411 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
412 return true;
413 }
414 }
415 }
416
417 return false;
418}
419
Alp Tokerac4e8e52014-06-22 21:58:33 +0000420static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
421 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
422 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
423 return true;
424 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000425}
426
427static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
428 DiagnosticsEngine &Diags,
429 bool IsSystem, bool Complain) {
430 // Top-level options
431 if (IsSystem) {
432 if (Diags.getSuppressSystemWarnings())
433 return false;
434 // If -Wsystem-headers was not enabled before, be conservative
435 if (StoredDiags.getSuppressSystemWarnings()) {
436 if (Complain)
437 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
438 return true;
439 }
440 }
441
442 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
443 if (Complain)
444 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
445 return true;
446 }
447
448 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
449 !StoredDiags.getEnableAllWarnings()) {
450 if (Complain)
451 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
452 return true;
453 }
454
455 if (isExtHandlingFromDiagsError(Diags) &&
456 !isExtHandlingFromDiagsError(StoredDiags)) {
457 if (Complain)
458 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
459 return true;
460 }
461
462 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
463}
464
465bool PCHValidator::ReadDiagnosticOptions(
466 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
467 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
468 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
469 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000470 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000471 // This should never fail, because we would have processed these options
472 // before writing them to an ASTFile.
473 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
474
475 ModuleManager &ModuleMgr = Reader.getModuleManager();
476 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
477
478 // If the original import came from a file explicitly generated by the user,
479 // don't check the diagnostic mappings.
480 // FIXME: currently this is approximated by checking whether this is not a
Richard Smithe842a472014-10-22 02:05:46 +0000481 // module import of an implicitly-loaded module file.
Ben Langmuirb92de022014-04-29 16:25:26 +0000482 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
483 // the transitive closure of its imports, since unrelated modules cannot be
484 // imported until after this module finishes validation.
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +0000485 ModuleFile *TopImport = &*ModuleMgr.rbegin();
Ben Langmuirb92de022014-04-29 16:25:26 +0000486 while (!TopImport->ImportedBy.empty())
487 TopImport = TopImport->ImportedBy[0];
Richard Smithe842a472014-10-22 02:05:46 +0000488 if (TopImport->Kind != MK_ImplicitModule)
Ben Langmuirb92de022014-04-29 16:25:26 +0000489 return false;
490
491 StringRef ModuleName = TopImport->ModuleName;
492 assert(!ModuleName.empty() && "diagnostic options read before module name");
493
494 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
495 assert(M && "missing module");
496
497 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
498 // contains the union of their flags.
499 return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
500}
501
Guy Benyei11169dd2012-12-18 14:30:41 +0000502/// \brief Collect the macro definitions provided by the given preprocessor
503/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000504static void
505collectMacroDefinitions(const PreprocessorOptions &PPOpts,
506 MacroDefinitionsMap &Macros,
507 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000508 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
509 StringRef Macro = PPOpts.Macros[I].first;
510 bool IsUndef = PPOpts.Macros[I].second;
511
512 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
513 StringRef MacroName = MacroPair.first;
514 StringRef MacroBody = MacroPair.second;
515
516 // For an #undef'd macro, we only care about the name.
517 if (IsUndef) {
518 if (MacroNames && !Macros.count(MacroName))
519 MacroNames->push_back(MacroName);
520
521 Macros[MacroName] = std::make_pair("", true);
522 continue;
523 }
524
525 // For a #define'd macro, figure out the actual definition.
526 if (MacroName.size() == Macro.size())
527 MacroBody = "1";
528 else {
529 // Note: GCC drops anything following an end-of-line character.
530 StringRef::size_type End = MacroBody.find_first_of("\n\r");
531 MacroBody = MacroBody.substr(0, End);
532 }
533
534 if (MacroNames && !Macros.count(MacroName))
535 MacroNames->push_back(MacroName);
536 Macros[MacroName] = std::make_pair(MacroBody, false);
537 }
538}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000539
Guy Benyei11169dd2012-12-18 14:30:41 +0000540/// \brief Check the preprocessor options deserialized from the control block
541/// against the preprocessor options in an existing preprocessor.
542///
543/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000544/// \param Validate If true, validate preprocessor options. If false, allow
545/// macros defined by \p ExistingPPOpts to override those defined by
546/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000547static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
548 const PreprocessorOptions &ExistingPPOpts,
549 DiagnosticsEngine *Diags,
550 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000551 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000552 const LangOptions &LangOpts,
553 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 // Check macro definitions.
555 MacroDefinitionsMap ASTFileMacros;
556 collectMacroDefinitions(PPOpts, ASTFileMacros);
557 MacroDefinitionsMap ExistingMacros;
558 SmallVector<StringRef, 4> ExistingMacroNames;
559 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
560
561 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
562 // Dig out the macro definition in the existing preprocessor options.
563 StringRef MacroName = ExistingMacroNames[I];
564 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
565
566 // Check whether we know anything about this macro name or not.
567 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
568 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000569 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000570 // FIXME: Check whether this identifier was referenced anywhere in the
571 // AST file. If so, we should reject the AST file. Unfortunately, this
572 // information isn't in the control block. What shall we do about it?
573
574 if (Existing.second) {
575 SuggestedPredefines += "#undef ";
576 SuggestedPredefines += MacroName.str();
577 SuggestedPredefines += '\n';
578 } else {
579 SuggestedPredefines += "#define ";
580 SuggestedPredefines += MacroName.str();
581 SuggestedPredefines += ' ';
582 SuggestedPredefines += Existing.first.str();
583 SuggestedPredefines += '\n';
584 }
585 continue;
586 }
587
588 // If the macro was defined in one but undef'd in the other, we have a
589 // conflict.
590 if (Existing.second != Known->second.second) {
591 if (Diags) {
592 Diags->Report(diag::err_pch_macro_def_undef)
593 << MacroName << Known->second.second;
594 }
595 return true;
596 }
597
598 // If the macro was #undef'd in both, or if the macro bodies are identical,
599 // it's fine.
600 if (Existing.second || Existing.first == Known->second.first)
601 continue;
602
603 // The macro bodies differ; complain.
604 if (Diags) {
605 Diags->Report(diag::err_pch_macro_def_conflict)
606 << MacroName << Known->second.first << Existing.first;
607 }
608 return true;
609 }
610
611 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000612 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 if (Diags) {
614 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
615 }
616 return true;
617 }
618
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000619 // Detailed record is important since it is used for the module cache hash.
620 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000621 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000622 if (Diags) {
623 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
624 }
625 return true;
626 }
627
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 // Compute the #include and #include_macros lines we need.
629 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
630 StringRef File = ExistingPPOpts.Includes[I];
631 if (File == ExistingPPOpts.ImplicitPCHInclude)
632 continue;
633
634 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
635 != PPOpts.Includes.end())
636 continue;
637
638 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000639 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000640 SuggestedPredefines += "\"\n";
641 }
642
643 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
644 StringRef File = ExistingPPOpts.MacroIncludes[I];
645 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
646 File)
647 != PPOpts.MacroIncludes.end())
648 continue;
649
650 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000651 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 SuggestedPredefines += "\"\n##\n";
653 }
654
655 return false;
656}
657
658bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
659 bool Complain,
660 std::string &SuggestedPredefines) {
661 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
662
663 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000664 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000666 SuggestedPredefines,
667 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000668}
669
Yaxun Liu43712e02016-09-07 18:40:20 +0000670bool SimpleASTReaderListener::ReadPreprocessorOptions(
671 const PreprocessorOptions &PPOpts,
672 bool Complain,
673 std::string &SuggestedPredefines) {
674 return checkPreprocessorOptions(PPOpts,
675 PP.getPreprocessorOpts(),
676 nullptr,
677 PP.getFileManager(),
678 SuggestedPredefines,
679 PP.getLangOpts(),
680 false);
681}
682
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000683/// Check the header search options deserialized from the control block
684/// against the header search options in an existing preprocessor.
685///
686/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
687static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
688 StringRef SpecificModuleCachePath,
689 StringRef ExistingModuleCachePath,
690 DiagnosticsEngine *Diags,
691 const LangOptions &LangOpts) {
692 if (LangOpts.Modules) {
693 if (SpecificModuleCachePath != ExistingModuleCachePath) {
694 if (Diags)
695 Diags->Report(diag::err_pch_modulecache_mismatch)
696 << SpecificModuleCachePath << ExistingModuleCachePath;
697 return true;
698 }
699 }
700
701 return false;
702}
703
704bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
705 StringRef SpecificModuleCachePath,
706 bool Complain) {
707 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
708 PP.getHeaderSearchInfo().getModuleCachePath(),
709 Complain ? &Reader.Diags : nullptr,
710 PP.getLangOpts());
711}
712
Guy Benyei11169dd2012-12-18 14:30:41 +0000713void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
714 PP.setCounterValue(Value);
715}
716
717//===----------------------------------------------------------------------===//
718// AST reader implementation
719//===----------------------------------------------------------------------===//
720
Nico Weber824285e2014-05-08 04:26:47 +0000721void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
722 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000724 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000725}
726
Guy Benyei11169dd2012-12-18 14:30:41 +0000727unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
728 return serialization::ComputeHash(Sel);
729}
730
Guy Benyei11169dd2012-12-18 14:30:41 +0000731std::pair<unsigned, unsigned>
732ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000733 using namespace llvm::support;
734 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
735 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000736 return std::make_pair(KeyLen, DataLen);
737}
738
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000739ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000740ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000741 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000742 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000743 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
744 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
745 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 if (N == 0)
747 return SelTable.getNullarySelector(FirstII);
748 else if (N == 1)
749 return SelTable.getUnarySelector(FirstII);
750
751 SmallVector<IdentifierInfo *, 16> Args;
752 Args.push_back(FirstII);
753 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000754 Args.push_back(Reader.getLocalIdentifier(
755 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000756
757 return SelTable.getSelector(N, Args.data());
758}
759
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000760ASTSelectorLookupTrait::data_type
761ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000763 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000764
765 data_type Result;
766
Justin Bogner57ba0b22014-03-28 22:03:24 +0000767 Result.ID = Reader.getGlobalSelectorID(
768 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000769 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
770 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
771 Result.InstanceBits = FullInstanceBits & 0x3;
772 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
773 Result.FactoryBits = FullFactoryBits & 0x3;
774 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
775 unsigned NumInstanceMethods = FullInstanceBits >> 3;
776 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000777
778 // Load instance methods
779 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000780 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
781 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 Result.Instance.push_back(Method);
783 }
784
785 // Load factory methods
786 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000787 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
788 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000789 Result.Factory.push_back(Method);
790 }
791
792 return Result;
793}
794
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000795unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
796 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000797}
798
799std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000800ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000801 using namespace llvm::support;
802 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
803 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000804 return std::make_pair(KeyLen, DataLen);
805}
806
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000807ASTIdentifierLookupTraitBase::internal_key_type
808ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000809 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000810 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000811}
812
Douglas Gregordcf25082013-02-11 18:16:18 +0000813/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000814static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
815 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000816 return II.hadMacroDefinition() ||
817 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000818 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000819 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000820 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
821 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000822}
823
Richard Smith76c2f2c2015-07-17 20:09:43 +0000824static bool readBit(unsigned &Bits) {
825 bool Value = Bits & 0x1;
826 Bits >>= 1;
827 return Value;
828}
829
Richard Smith79bf9202015-08-24 03:33:22 +0000830IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
831 using namespace llvm::support;
832 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
833 return Reader.getGlobalIdentifierID(F, RawID >> 1);
834}
835
Richard Smitheb4b58f62016-02-05 01:40:54 +0000836static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
837 if (!II.isFromAST()) {
838 II.setIsFromAST();
839 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
840 if (isInterestingIdentifier(Reader, II, IsModule))
841 II.setChangedSinceDeserialization();
842 }
843}
844
Guy Benyei11169dd2012-12-18 14:30:41 +0000845IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
846 const unsigned char* d,
847 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000848 using namespace llvm::support;
849 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000850 bool IsInteresting = RawID & 0x01;
851
852 // Wipe out the "is interesting" bit.
853 RawID = RawID >> 1;
854
Richard Smith76c2f2c2015-07-17 20:09:43 +0000855 // Build the IdentifierInfo and link the identifier ID with it.
856 IdentifierInfo *II = KnownII;
857 if (!II) {
858 II = &Reader.getIdentifierTable().getOwn(k);
859 KnownII = II;
860 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000861 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000862 Reader.markIdentifierUpToDate(II);
863
Guy Benyei11169dd2012-12-18 14:30:41 +0000864 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
865 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000866 // For uninteresting identifiers, there's nothing else to do. Just notify
867 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 return II;
870 }
871
Justin Bogner57ba0b22014-03-28 22:03:24 +0000872 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
873 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000874 bool CPlusPlusOperatorKeyword = readBit(Bits);
875 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000876 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000877 bool Poisoned = readBit(Bits);
878 bool ExtensionToken = readBit(Bits);
879 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000880
881 assert(Bits == 0 && "Extra bits in the identifier?");
882 DataLen -= 8;
883
Guy Benyei11169dd2012-12-18 14:30:41 +0000884 // Set or check the various bits in the IdentifierInfo structure.
885 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000886 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000887 II->revertTokenIDToIdentifier();
888 if (!F.isModule())
889 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
890 else if (HasRevertedBuiltin && II->getBuiltinID()) {
891 II->revertBuiltin();
892 assert((II->hasRevertedBuiltin() ||
893 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
894 "Incorrect ObjC keyword or builtin ID");
895 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000896 assert(II->isExtensionToken() == ExtensionToken &&
897 "Incorrect extension token flag");
898 (void)ExtensionToken;
899 if (Poisoned)
900 II->setIsPoisoned(true);
901 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
902 "Incorrect C++ operator keyword flag");
903 (void)CPlusPlusOperatorKeyword;
904
905 // If this identifier is a macro, deserialize the macro
906 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000907 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000908 uint32_t MacroDirectivesOffset =
909 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000910 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000911
Richard Smithd7329392015-04-21 21:46:32 +0000912 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000913 }
914
915 Reader.SetIdentifierInfo(ID, II);
916
917 // Read all of the declarations visible at global scope with this
918 // name.
919 if (DataLen > 0) {
920 SmallVector<uint32_t, 4> DeclIDs;
921 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000922 DeclIDs.push_back(Reader.getGlobalDeclID(
923 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000924 Reader.SetGloballyVisibleDecls(II, DeclIDs);
925 }
926
927 return II;
928}
929
Richard Smitha06c7e62015-08-26 23:55:49 +0000930DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
931 : Kind(Name.getNameKind()) {
932 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000934 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 break;
936 case DeclarationName::ObjCZeroArgSelector:
937 case DeclarationName::ObjCOneArgSelector:
938 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000939 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000940 break;
941 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000942 Data = Name.getCXXOverloadedOperator();
943 break;
944 case DeclarationName::CXXLiteralOperatorName:
945 Data = (uint64_t)Name.getCXXLiteralIdentifier();
946 break;
947 case DeclarationName::CXXConstructorName:
948 case DeclarationName::CXXDestructorName:
949 case DeclarationName::CXXConversionFunctionName:
950 case DeclarationName::CXXUsingDirective:
951 Data = 0;
952 break;
953 }
954}
955
956unsigned DeclarationNameKey::getHash() const {
957 llvm::FoldingSetNodeID ID;
958 ID.AddInteger(Kind);
959
960 switch (Kind) {
961 case DeclarationName::Identifier:
962 case DeclarationName::CXXLiteralOperatorName:
963 ID.AddString(((IdentifierInfo*)Data)->getName());
964 break;
965 case DeclarationName::ObjCZeroArgSelector:
966 case DeclarationName::ObjCOneArgSelector:
967 case DeclarationName::ObjCMultiArgSelector:
968 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
969 break;
970 case DeclarationName::CXXOperatorName:
971 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 break;
973 case DeclarationName::CXXConstructorName:
974 case DeclarationName::CXXDestructorName:
975 case DeclarationName::CXXConversionFunctionName:
976 case DeclarationName::CXXUsingDirective:
977 break;
978 }
979
980 return ID.ComputeHash();
981}
982
Richard Smithd88a7f12015-09-01 20:35:42 +0000983ModuleFile *
984ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
985 using namespace llvm::support;
986 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
987 return Reader.getLocalModuleFile(F, ModuleFileID);
988}
989
Guy Benyei11169dd2012-12-18 14:30:41 +0000990std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000991ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000992 using namespace llvm::support;
993 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
994 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 return std::make_pair(KeyLen, DataLen);
996}
997
Richard Smitha06c7e62015-08-26 23:55:49 +0000998ASTDeclContextNameLookupTrait::internal_key_type
999ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001000 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001001
Richard Smitha06c7e62015-08-26 23:55:49 +00001002 auto Kind = (DeclarationName::NameKind)*d++;
1003 uint64_t Data;
1004 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +00001006 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001007 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001008 break;
1009 case DeclarationName::ObjCZeroArgSelector:
1010 case DeclarationName::ObjCOneArgSelector:
1011 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001012 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001013 (uint64_t)Reader.getLocalSelector(
1014 F, endian::readNext<uint32_t, little, unaligned>(
1015 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001018 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001019 break;
1020 case DeclarationName::CXXLiteralOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001021 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001022 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 break;
1024 case DeclarationName::CXXConstructorName:
1025 case DeclarationName::CXXDestructorName:
1026 case DeclarationName::CXXConversionFunctionName:
1027 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001028 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 break;
1030 }
1031
Richard Smitha06c7e62015-08-26 23:55:49 +00001032 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001033}
1034
Richard Smithd88a7f12015-09-01 20:35:42 +00001035void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1036 const unsigned char *d,
1037 unsigned DataLen,
1038 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001039 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001040 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1041 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1042 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1043 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001044}
1045
Richard Smith0f4e2c42015-08-06 04:23:48 +00001046bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1047 BitstreamCursor &Cursor,
1048 uint64_t Offset,
1049 DeclContext *DC) {
1050 assert(Offset != 0);
1051
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001053 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001054
Richard Smith0f4e2c42015-08-06 04:23:48 +00001055 RecordData Record;
1056 StringRef Blob;
1057 unsigned Code = Cursor.ReadCode();
1058 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1059 if (RecCode != DECL_CONTEXT_LEXICAL) {
1060 Error("Expected lexical block");
1061 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001062 }
1063
Richard Smith82f8fcd2015-08-06 22:07:25 +00001064 assert(!isa<TranslationUnitDecl>(DC) &&
1065 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001066 // If we are handling a C++ class template instantiation, we can see multiple
1067 // lexical updates for the same record. It's important that we select only one
1068 // of them, so that field numbering works properly. Just pick the first one we
1069 // see.
1070 auto &Lex = LexicalDecls[DC];
1071 if (!Lex.first) {
1072 Lex = std::make_pair(
1073 &M, llvm::makeArrayRef(
1074 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1075 Blob.data()),
1076 Blob.size() / 4));
1077 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001078 DC->setHasExternalLexicalStorage(true);
1079 return false;
1080}
Guy Benyei11169dd2012-12-18 14:30:41 +00001081
Richard Smith0f4e2c42015-08-06 04:23:48 +00001082bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1083 BitstreamCursor &Cursor,
1084 uint64_t Offset,
1085 DeclID ID) {
1086 assert(Offset != 0);
1087
1088 SavedStreamPosition SavedPosition(Cursor);
1089 Cursor.JumpToBit(Offset);
1090
1091 RecordData Record;
1092 StringRef Blob;
1093 unsigned Code = Cursor.ReadCode();
1094 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1095 if (RecCode != DECL_CONTEXT_VISIBLE) {
1096 Error("Expected visible lookup table block");
1097 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001098 }
1099
Richard Smith0f4e2c42015-08-06 04:23:48 +00001100 // We can't safely determine the primary context yet, so delay attaching the
1101 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001102 auto *Data = (const unsigned char*)Blob.data();
1103 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 return false;
1105}
1106
1107void ASTReader::Error(StringRef Msg) {
1108 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001109 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1110 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001111 Diag(diag::note_module_cache_path)
1112 << PP.getHeaderSearchInfo().getModuleCachePath();
1113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001114}
1115
1116void ASTReader::Error(unsigned DiagID,
1117 StringRef Arg1, StringRef Arg2) {
1118 if (Diags.isDiagnosticInFlight())
1119 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1120 else
1121 Diag(DiagID) << Arg1 << Arg2;
1122}
1123
1124//===----------------------------------------------------------------------===//
1125// Source Manager Deserialization
1126//===----------------------------------------------------------------------===//
1127
1128/// \brief Read the line table in the source manager block.
1129/// \returns true if there was an error.
1130bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001131 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 unsigned Idx = 0;
1133 LineTableInfo &LineTable = SourceMgr.getLineTable();
1134
1135 // Parse the file names
1136 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001137 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001138 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001139 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1141 }
Richard Smith63078492015-09-01 07:41:55 +00001142 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001143
1144 // Parse the line entries
1145 std::vector<LineEntry> Entries;
1146 while (Idx < Record.size()) {
1147 int FID = Record[Idx++];
1148 assert(FID >= 0 && "Serialized line entries for non-local file.");
1149 // Remap FileID from 1-based old view.
1150 FID += F.SLocEntryBaseID - 1;
1151
1152 // Extract the line entries
1153 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001154 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001155 Entries.clear();
1156 Entries.reserve(NumEntries);
1157 for (unsigned I = 0; I != NumEntries; ++I) {
1158 unsigned FileOffset = Record[Idx++];
1159 unsigned LineNo = Record[Idx++];
1160 int FilenameID = FileIDs[Record[Idx++]];
1161 SrcMgr::CharacteristicKind FileKind
1162 = (SrcMgr::CharacteristicKind)Record[Idx++];
1163 unsigned IncludeOffset = Record[Idx++];
1164 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1165 FileKind, IncludeOffset));
1166 }
1167 LineTable.AddEntry(FileID::get(FID), Entries);
1168 }
1169
1170 return false;
1171}
1172
1173/// \brief Read a source manager block
1174bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1175 using namespace SrcMgr;
1176
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001177 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001178
1179 // Set the source-location entry cursor to the current position in
1180 // the stream. This cursor will be used to read the contents of the
1181 // source manager block initially, and then lazily read
1182 // source-location entries as needed.
1183 SLocEntryCursor = F.Stream;
1184
1185 // The stream itself is going to skip over the source manager block.
1186 if (F.Stream.SkipBlock()) {
1187 Error("malformed block record in AST file");
1188 return true;
1189 }
1190
1191 // Enter the source manager block.
1192 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1193 Error("malformed source manager block record in AST file");
1194 return true;
1195 }
1196
1197 RecordData Record;
1198 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001199 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001200
Chris Lattnere7b154b2013-01-19 21:39:22 +00001201 switch (E.Kind) {
1202 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1203 case llvm::BitstreamEntry::Error:
1204 Error("malformed block record in AST file");
1205 return true;
1206 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001208 case llvm::BitstreamEntry::Record:
1209 // The interesting case.
1210 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001212
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001215 StringRef Blob;
1216 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 default: // Default behavior: ignore.
1218 break;
1219
1220 case SM_SLOC_FILE_ENTRY:
1221 case SM_SLOC_BUFFER_ENTRY:
1222 case SM_SLOC_EXPANSION_ENTRY:
1223 // Once we hit one of the source location entries, we're done.
1224 return false;
1225 }
1226 }
1227}
1228
1229/// \brief If a header file is not found at the path that we expect it to be
1230/// and the PCH file was moved from its original location, try to resolve the
1231/// file by assuming that header+PCH were moved together and the header is in
1232/// the same place relative to the PCH.
1233static std::string
1234resolveFileRelativeToOriginalDir(const std::string &Filename,
1235 const std::string &OriginalDir,
1236 const std::string &CurrDir) {
1237 assert(OriginalDir != CurrDir &&
1238 "No point trying to resolve the file if the PCH dir didn't change");
1239 using namespace llvm::sys;
1240 SmallString<128> filePath(Filename);
1241 fs::make_absolute(filePath);
1242 assert(path::is_absolute(OriginalDir));
1243 SmallString<128> currPCHPath(CurrDir);
1244
1245 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1246 fileDirE = path::end(path::parent_path(filePath));
1247 path::const_iterator origDirI = path::begin(OriginalDir),
1248 origDirE = path::end(OriginalDir);
1249 // Skip the common path components from filePath and OriginalDir.
1250 while (fileDirI != fileDirE && origDirI != origDirE &&
1251 *fileDirI == *origDirI) {
1252 ++fileDirI;
1253 ++origDirI;
1254 }
1255 for (; origDirI != origDirE; ++origDirI)
1256 path::append(currPCHPath, "..");
1257 path::append(currPCHPath, fileDirI, fileDirE);
1258 path::append(currPCHPath, path::filename(Filename));
1259 return currPCHPath.str();
1260}
1261
1262bool ASTReader::ReadSLocEntry(int ID) {
1263 if (ID == 0)
1264 return false;
1265
1266 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1267 Error("source location entry ID out-of-range for AST file");
1268 return true;
1269 }
1270
Richard Smithaada85c2016-02-06 02:06:43 +00001271 // Local helper to read the (possibly-compressed) buffer data following the
1272 // entry record.
1273 auto ReadBuffer = [this](
1274 BitstreamCursor &SLocEntryCursor,
1275 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1276 RecordData Record;
1277 StringRef Blob;
1278 unsigned Code = SLocEntryCursor.ReadCode();
1279 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1280
1281 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001282 if (!llvm::zlib::isAvailable()) {
1283 Error("zlib is not available");
1284 return nullptr;
1285 }
Richard Smithaada85c2016-02-06 02:06:43 +00001286 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001287 if (llvm::Error E =
1288 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1289 Error("could not decompress embedded file contents: " +
1290 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001291 return nullptr;
1292 }
1293 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1294 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1295 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1296 } else {
1297 Error("AST record has invalid code");
1298 return nullptr;
1299 }
1300 };
1301
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1303 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001304 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 unsigned BaseOffset = F->SLocEntryBaseOffset;
1306
1307 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001308 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1309 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001310 Error("incorrectly-formatted source location entry in AST file");
1311 return true;
1312 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001313
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001315 StringRef Blob;
1316 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 default:
1318 Error("incorrectly-formatted source location entry in AST file");
1319 return true;
1320
1321 case SM_SLOC_FILE_ENTRY: {
1322 // We will detect whether a file changed and return 'Failure' for it, but
1323 // we will also try to fail gracefully by setting up the SLocEntry.
1324 unsigned InputID = Record[4];
1325 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001326 const FileEntry *File = IF.getFile();
1327 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001328
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001329 // Note that we only check if a File was returned. If it was out-of-date
1330 // we have complained but we will continue creating a FileID to recover
1331 // gracefully.
1332 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001333 return true;
1334
1335 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1336 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1337 // This is the module's main file.
1338 IncludeLoc = getImportLocation(F);
1339 }
1340 SrcMgr::CharacteristicKind
1341 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1342 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1343 ID, BaseOffset + Record[0]);
1344 SrcMgr::FileInfo &FileInfo =
1345 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1346 FileInfo.NumCreatedFIDs = Record[5];
1347 if (Record[3])
1348 FileInfo.setHasLineDirectives();
1349
1350 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1351 unsigned NumFileDecls = Record[7];
1352 if (NumFileDecls) {
1353 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1354 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1355 NumFileDecls));
1356 }
Richard Smithaada85c2016-02-06 02:06:43 +00001357
Guy Benyei11169dd2012-12-18 14:30:41 +00001358 const SrcMgr::ContentCache *ContentCache
1359 = SourceMgr.getOrCreateContentCache(File,
1360 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1361 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001362 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1363 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001364 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1365 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001367 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001368 }
1369
1370 break;
1371 }
1372
1373 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001374 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 unsigned Offset = Record[0];
1376 SrcMgr::CharacteristicKind
1377 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1378 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001379 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 IncludeLoc = getImportLocation(F);
1381 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001382
Richard Smithaada85c2016-02-06 02:06:43 +00001383 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1384 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001386 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001387 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 break;
1389 }
1390
1391 case SM_SLOC_EXPANSION_ENTRY: {
1392 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1393 SourceMgr.createExpansionLoc(SpellingLoc,
1394 ReadSourceLocation(*F, Record[2]),
1395 ReadSourceLocation(*F, Record[3]),
1396 Record[4],
1397 ID,
1398 BaseOffset + Record[0]);
1399 break;
1400 }
1401 }
1402
1403 return false;
1404}
1405
1406std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1407 if (ID == 0)
1408 return std::make_pair(SourceLocation(), "");
1409
1410 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1411 Error("source location entry ID out-of-range for AST file");
1412 return std::make_pair(SourceLocation(), "");
1413 }
1414
1415 // Find which module file this entry lands in.
1416 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001417 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 return std::make_pair(SourceLocation(), "");
1419
1420 // FIXME: Can we map this down to a particular submodule? That would be
1421 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001422 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001423}
1424
1425/// \brief Find the location where the module F is imported.
1426SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1427 if (F->ImportLoc.isValid())
1428 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001429
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 // Otherwise we have a PCH. It's considered to be "imported" at the first
1431 // location of its includer.
1432 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001433 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001434 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001435 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001436 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 return F->ImportedBy[0]->FirstLoc;
1438}
1439
1440/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1441/// specified cursor. Read the abbreviations that are at the top of the block
1442/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001443bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001444 if (Cursor.EnterSubBlock(BlockID))
1445 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001446
1447 while (true) {
1448 uint64_t Offset = Cursor.GetCurrentBitNo();
1449 unsigned Code = Cursor.ReadCode();
1450
1451 // We expect all abbrevs to be at the start of the block.
1452 if (Code != llvm::bitc::DEFINE_ABBREV) {
1453 Cursor.JumpToBit(Offset);
1454 return false;
1455 }
1456 Cursor.ReadAbbrevRecord();
1457 }
1458}
1459
Richard Smithe40f2ba2013-08-07 21:41:30 +00001460Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001461 unsigned &Idx) {
1462 Token Tok;
1463 Tok.startToken();
1464 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1465 Tok.setLength(Record[Idx++]);
1466 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1467 Tok.setIdentifierInfo(II);
1468 Tok.setKind((tok::TokenKind)Record[Idx++]);
1469 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1470 return Tok;
1471}
1472
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001473MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001474 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001475
1476 // Keep track of where we are in the stream, then jump back there
1477 // after reading this macro.
1478 SavedStreamPosition SavedPosition(Stream);
1479
1480 Stream.JumpToBit(Offset);
1481 RecordData Record;
1482 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001483 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001484
Guy Benyei11169dd2012-12-18 14:30:41 +00001485 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001486 // Advance to the next record, but if we get to the end of the block, don't
1487 // pop it (removing all the abbreviations from the cursor) since we want to
1488 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001489 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001490 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001491
Chris Lattnerefa77172013-01-20 00:00:22 +00001492 switch (Entry.Kind) {
1493 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1494 case llvm::BitstreamEntry::Error:
1495 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001496 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001497 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001498 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001499 case llvm::BitstreamEntry::Record:
1500 // The interesting case.
1501 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001502 }
1503
1504 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 Record.clear();
1506 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001507 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001509 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001510 case PP_MACRO_DIRECTIVE_HISTORY:
1511 return Macro;
1512
Guy Benyei11169dd2012-12-18 14:30:41 +00001513 case PP_MACRO_OBJECT_LIKE:
1514 case PP_MACRO_FUNCTION_LIKE: {
1515 // If we already have a macro, that means that we've hit the end
1516 // of the definition of the macro we were looking for. We're
1517 // done.
1518 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001519 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001520
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001521 unsigned NextIndex = 1; // Skip identifier ID.
1522 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001524 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001525 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001527 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001528
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1530 // Decode function-like macro info.
1531 bool isC99VarArgs = Record[NextIndex++];
1532 bool isGNUVarArgs = Record[NextIndex++];
1533 bool hasCommaPasting = Record[NextIndex++];
1534 MacroArgs.clear();
1535 unsigned NumArgs = Record[NextIndex++];
1536 for (unsigned i = 0; i != NumArgs; ++i)
1537 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1538
1539 // Install function-like macro info.
1540 MI->setIsFunctionLike();
1541 if (isC99VarArgs) MI->setIsC99Varargs();
1542 if (isGNUVarArgs) MI->setIsGNUVarargs();
1543 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001544 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 }
1546
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 // Remember that we saw this macro last so that we add the tokens that
1548 // form its body to it.
1549 Macro = MI;
1550
1551 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1552 Record[NextIndex]) {
1553 // We have a macro definition. Register the association
1554 PreprocessedEntityID
1555 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1556 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001557 PreprocessingRecord::PPEntityID PPID =
1558 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1559 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1560 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001561 if (PPDef)
1562 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 }
1564
1565 ++NumMacrosRead;
1566 break;
1567 }
1568
1569 case PP_TOKEN: {
1570 // If we see a TOKEN before a PP_MACRO_*, then the file is
1571 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001572 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001573
John McCallf413f5e2013-05-03 00:10:13 +00001574 unsigned Idx = 0;
1575 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001576 Macro->AddTokenToBody(Tok);
1577 break;
1578 }
1579 }
1580 }
1581}
1582
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001583PreprocessedEntityID
Guy Benyei11169dd2012-12-18 14:30:41 +00001584ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001585 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001587 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001588 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001589
Guy Benyei11169dd2012-12-18 14:30:41 +00001590 return LocalID + I->second;
1591}
1592
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001593unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1594 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001595}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001596
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001597HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001598HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001599 internal_key_type ikey = {FE->getSize(),
1600 M.HasTimestamps ? FE->getModificationTime() : 0,
1601 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001602 return ikey;
1603}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001604
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001605bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001606 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 return false;
1608
Mehdi Amini004b9c72016-10-10 22:52:47 +00001609 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001610 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001611
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001613 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001614 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1615 if (!Key.Imported)
1616 return FileMgr.getFile(Key.Filename);
1617
1618 std::string Resolved = Key.Filename;
1619 Reader.ResolveImportedPath(M, Resolved);
1620 return FileMgr.getFile(Resolved);
1621 };
1622
1623 const FileEntry *FEA = GetFile(a);
1624 const FileEntry *FEB = GetFile(b);
1625 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001626}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001627
Guy Benyei11169dd2012-12-18 14:30:41 +00001628std::pair<unsigned, unsigned>
1629HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001630 using namespace llvm::support;
1631 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001633 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001634}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001635
1636HeaderFileInfoTrait::internal_key_type
1637HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001638 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001639 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001640 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1641 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001643 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001644 return ikey;
1645}
1646
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001647HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001648HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 unsigned DataLen) {
1650 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001651 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 HeaderFileInfo HFI;
1653 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001654 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1655 HFI.isImport |= (Flags >> 4) & 0x01;
1656 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1657 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001659 // FIXME: Find a better way to handle this. Maybe just store a
1660 // "has been included" flag?
1661 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1662 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001663 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1664 M, endian::readNext<uint32_t, little, unaligned>(d));
1665 if (unsigned FrameworkOffset =
1666 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001667 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001668 // since 0 is used as an indicator for "no framework name".
1669 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1670 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1671 }
Richard Smith386bb072015-08-18 23:42:23 +00001672
1673 assert((End - d) % 4 == 0 &&
1674 "Wrong data length in HeaderFileInfo deserialization");
1675 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001676 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001677 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1678 LocalSMID >>= 2;
1679
1680 // This header is part of a module. Associate it with the module to enable
1681 // implicit module import.
1682 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1683 Module *Mod = Reader.getSubmodule(GlobalSMID);
1684 FileManager &FileMgr = Reader.getFileManager();
1685 ModuleMap &ModMap =
1686 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1687
1688 std::string Filename = key.Filename;
1689 if (key.Imported)
1690 Reader.ResolveImportedPath(M, Filename);
1691 // FIXME: This is not always the right filename-as-written, but we're not
1692 // going to use this information to rebuild the module, so it doesn't make
1693 // a lot of difference.
1694 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001695 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1696 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001697 }
1698
Guy Benyei11169dd2012-12-18 14:30:41 +00001699 // This HeaderFileInfo was externally loaded.
1700 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001701 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 return HFI;
1703}
1704
Richard Smithd7329392015-04-21 21:46:32 +00001705void ASTReader::addPendingMacro(IdentifierInfo *II,
1706 ModuleFile *M,
1707 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001708 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1709 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001710}
1711
1712void ASTReader::ReadDefinedMacros() {
1713 // Note that we are loading defined macros.
1714 Deserializing Macros(this);
1715
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001716 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1717 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001718
1719 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001720 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 continue;
1722
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001723 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001724 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001725
1726 RecordData Record;
1727 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001728 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001729
Chris Lattnere7b154b2013-01-19 21:39:22 +00001730 switch (E.Kind) {
1731 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1732 case llvm::BitstreamEntry::Error:
1733 Error("malformed block record in AST file");
1734 return;
1735 case llvm::BitstreamEntry::EndBlock:
1736 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001737
Chris Lattnere7b154b2013-01-19 21:39:22 +00001738 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001739 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001740 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001741 default: // Default behavior: ignore.
1742 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001743
Chris Lattnere7b154b2013-01-19 21:39:22 +00001744 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001745 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001746 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001747 if (II->isOutOfDate())
1748 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001749 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001750 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001751
Chris Lattnere7b154b2013-01-19 21:39:22 +00001752 case PP_TOKEN:
1753 // Ignore tokens.
1754 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001756 break;
1757 }
1758 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001759 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 }
1761}
1762
1763namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001764
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 /// \brief Visitor class used to look up identifirs in an AST file.
1766 class IdentifierLookupVisitor {
1767 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001768 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001769 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001770 unsigned &NumIdentifierLookups;
1771 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001773
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001775 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1776 unsigned &NumIdentifierLookups,
1777 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001778 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1779 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001780 NumIdentifierLookups(NumIdentifierLookups),
1781 NumIdentifierLookupHits(NumIdentifierLookupHits),
1782 Found()
1783 {
1784 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001785
1786 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001787 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001788 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001790
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 ASTIdentifierLookupTable *IdTable
1792 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1793 if (!IdTable)
1794 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001795
1796 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001797 Found);
1798 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001799 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001800 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 if (Pos == IdTable->end())
1802 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001803
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 // Dereferencing the iterator has the effect of building the
1805 // IdentifierInfo node and populating it with the various
1806 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001807 ++NumIdentifierLookupHits;
1808 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 return true;
1810 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001811
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 // \brief Retrieve the identifier info found within the module
1813 // files.
1814 IdentifierInfo *getIdentifierInfo() const { return Found; }
1815 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001816
1817} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001818
1819void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1820 // Note that we are loading an identifier.
1821 Deserializing AnIdentifier(this);
1822
1823 unsigned PriorGeneration = 0;
1824 if (getContext().getLangOpts().Modules)
1825 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001826
1827 // If there is a global index, look there first to determine which modules
1828 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001829 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001830 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001831 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001832 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1833 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001834 }
1835 }
1836
Douglas Gregor7211ac12013-01-25 23:32:03 +00001837 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001838 NumIdentifierLookups,
1839 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001840 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 markIdentifierUpToDate(&II);
1842}
1843
1844void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1845 if (!II)
1846 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001847
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 II->setOutOfDate(false);
1849
1850 // Update the generation for this identifier.
1851 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001852 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001853}
1854
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001855void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1856 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001857 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858
1859 BitstreamCursor &Cursor = M.MacroCursor;
1860 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001861 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001862
Richard Smith713369b2015-04-23 20:40:50 +00001863 struct ModuleMacroRecord {
1864 SubmoduleID SubModID;
1865 MacroInfo *MI;
1866 SmallVector<SubmoduleID, 8> Overrides;
1867 };
1868 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001869
Richard Smithd7329392015-04-21 21:46:32 +00001870 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1871 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1872 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001873 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001874 while (true) {
1875 llvm::BitstreamEntry Entry =
1876 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1877 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1878 Error("malformed block record in AST file");
1879 return;
1880 }
1881
1882 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001883 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001884 case PP_MACRO_DIRECTIVE_HISTORY:
1885 break;
1886
1887 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001888 ModuleMacros.push_back(ModuleMacroRecord());
1889 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001890 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1891 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001892 for (int I = 2, N = Record.size(); I != N; ++I)
1893 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001894 continue;
1895 }
1896
1897 default:
1898 Error("malformed block record in AST file");
1899 return;
1900 }
1901
1902 // We found the macro directive history; that's the last record
1903 // for this macro.
1904 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001905 }
1906
Richard Smithd7329392015-04-21 21:46:32 +00001907 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001908 {
1909 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001910 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001911 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001912 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001913 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001914 Module *Mod = getSubmodule(ModID);
1915 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001916 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001917 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001918 }
1919
1920 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001921 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001922 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001923 }
1924 }
1925
1926 // Don't read the directive history for a module; we don't have anywhere
1927 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001928 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001929 return;
1930
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001931 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001932 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001933 unsigned Idx = 0, N = Record.size();
1934 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001935 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001936 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001937 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1938 switch (K) {
1939 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001940 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001941 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001942 break;
1943 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001944 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001945 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001946 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001947 }
1948 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001949 bool isPublic = Record[Idx++];
1950 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1951 break;
1952 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001953
1954 if (!Latest)
1955 Latest = MD;
1956 if (Earliest)
1957 Earliest->setPrevious(MD);
1958 Earliest = MD;
1959 }
1960
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001961 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001962 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001963}
1964
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001965ASTReader::InputFileInfo
1966ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001967 // Go find this input file.
1968 BitstreamCursor &Cursor = F.InputFilesCursor;
1969 SavedStreamPosition SavedPosition(Cursor);
1970 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1971
1972 unsigned Code = Cursor.ReadCode();
1973 RecordData Record;
1974 StringRef Blob;
1975
1976 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1977 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1978 "invalid record type for input file");
1979 (void)Result;
1980
1981 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001982 InputFileInfo R;
1983 R.StoredSize = static_cast<off_t>(Record[1]);
1984 R.StoredTime = static_cast<time_t>(Record[2]);
1985 R.Overridden = static_cast<bool>(Record[3]);
1986 R.Transient = static_cast<bool>(Record[4]);
1987 R.Filename = Blob;
1988 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001989 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001990}
1991
Manman Renc8c94152016-10-21 23:35:03 +00001992static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001993InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001994 // If this ID is bogus, just return an empty input file.
1995 if (ID == 0 || ID > F.InputFilesLoaded.size())
1996 return InputFile();
1997
1998 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001999 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002000 return F.InputFilesLoaded[ID-1];
2001
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002002 if (F.InputFilesLoaded[ID-1].isNotFound())
2003 return InputFile();
2004
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002006 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002007 SavedStreamPosition SavedPosition(Cursor);
2008 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002009
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002010 InputFileInfo FI = readInputFileInfo(F, ID);
2011 off_t StoredSize = FI.StoredSize;
2012 time_t StoredTime = FI.StoredTime;
2013 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002014 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002015 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002016
Richard Smitha8cfffa2015-11-26 02:04:16 +00002017 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002018
2019 // If we didn't find the file, resolve it relative to the
2020 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002021 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002022 F.OriginalDir != CurrentDir) {
2023 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2024 F.OriginalDir,
2025 CurrentDir);
2026 if (!Resolved.empty())
2027 File = FileMgr.getFile(Resolved);
2028 }
2029
2030 // For an overridden file, create a virtual file with the stored
2031 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002032 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002033 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002034
Craig Toppera13603a2014-05-22 05:54:18 +00002035 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002036 if (Complain) {
2037 std::string ErrorStr = "could not find file '";
2038 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002039 ErrorStr += "' referenced by AST file '";
2040 ErrorStr += F.FileName;
2041 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002042 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002043 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002044 // Record that we didn't find the file.
2045 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2046 return InputFile();
2047 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002048
Ben Langmuir198c1682014-03-07 07:27:49 +00002049 // Check if there was a request to override the contents of the file
2050 // that was part of the precompiled header. Overridding such a file
2051 // can lead to problems when lexing using the source locations from the
2052 // PCH.
2053 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002054 // FIXME: Reject if the overrides are different.
2055 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002056 if (Complain)
2057 Error(diag::err_fe_pch_file_overridden, Filename);
2058 // After emitting the diagnostic, recover by disabling the override so
2059 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002060 //
2061 // FIXME: This recovery is just as broken as the original state; there may
2062 // be another precompiled module that's using the overridden contents, or
2063 // we might be half way through parsing it. Instead, we should treat the
2064 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002065 SM.disableFileContentsOverride(File);
2066 // The FileEntry is a virtual file entry with the size of the contents
2067 // that would override the original contents. Set it to the original's
2068 // size/time.
2069 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2070 StoredSize, StoredTime);
2071 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002072
Ben Langmuir198c1682014-03-07 07:27:49 +00002073 bool IsOutOfDate = false;
2074
2075 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002076 if (!Overridden && //
2077 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002078 (StoredTime && StoredTime != File->getModificationTime() &&
2079 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002080 )) {
2081 if (Complain) {
2082 // Build a list of the PCH imports that got us here (in reverse).
2083 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2084 while (ImportStack.back()->ImportedBy.size() > 0)
2085 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002086
Ben Langmuir198c1682014-03-07 07:27:49 +00002087 // The top-level PCH is stale.
2088 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002089 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2090 if (DiagnosticKind == 0)
2091 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2092 else if (DiagnosticKind == 1)
2093 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2094 else
2095 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002096
Ben Langmuir198c1682014-03-07 07:27:49 +00002097 // Print the import stack.
2098 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2099 Diag(diag::note_pch_required_by)
2100 << Filename << ImportStack[0]->FileName;
2101 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002102 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002103 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002104 }
2105
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 if (!Diags.isDiagnosticInFlight())
2107 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002108 }
2109
Ben Langmuir198c1682014-03-07 07:27:49 +00002110 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002112 // FIXME: If the file is overridden and we've already opened it,
2113 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002114
Richard Smitha8cfffa2015-11-26 02:04:16 +00002115 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002116
2117 // Note that we've loaded this input file.
2118 F.InputFilesLoaded[ID-1] = IF;
2119 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002120}
2121
Richard Smith7ed1bc92014-12-05 22:42:13 +00002122/// \brief If we are loading a relocatable PCH or module file, and the filename
2123/// is not an absolute path, add the system or module root to the beginning of
2124/// the file name.
2125void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2126 // Resolve relative to the base directory, if we have one.
2127 if (!M.BaseDirectory.empty())
2128 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002129}
2130
Richard Smith7ed1bc92014-12-05 22:42:13 +00002131void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002132 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2133 return;
2134
Richard Smith7ed1bc92014-12-05 22:42:13 +00002135 SmallString<128> Buffer;
2136 llvm::sys::path::append(Buffer, Prefix, Filename);
2137 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002138}
2139
Richard Smith0f99d6a2015-08-09 08:48:41 +00002140static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2141 switch (ARR) {
2142 case ASTReader::Failure: return true;
2143 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2144 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2145 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2146 case ASTReader::ConfigurationMismatch:
2147 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2148 case ASTReader::HadErrors: return true;
2149 case ASTReader::Success: return false;
2150 }
2151
2152 llvm_unreachable("unknown ASTReadResult");
2153}
2154
Richard Smith0516b182015-09-08 19:40:14 +00002155ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2156 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2157 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002158 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002159 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2160 return Failure;
2161
2162 // Read all of the records in the options block.
2163 RecordData Record;
2164 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002165 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002166 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002167
Richard Smith0516b182015-09-08 19:40:14 +00002168 switch (Entry.Kind) {
2169 case llvm::BitstreamEntry::Error:
2170 case llvm::BitstreamEntry::SubBlock:
2171 return Failure;
2172
2173 case llvm::BitstreamEntry::EndBlock:
2174 return Result;
2175
2176 case llvm::BitstreamEntry::Record:
2177 // The interesting case.
2178 break;
2179 }
2180
2181 // Read and process a record.
2182 Record.clear();
2183 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2184 case LANGUAGE_OPTIONS: {
2185 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2186 if (ParseLanguageOptions(Record, Complain, Listener,
2187 AllowCompatibleConfigurationMismatch))
2188 Result = ConfigurationMismatch;
2189 break;
2190 }
2191
2192 case TARGET_OPTIONS: {
2193 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2194 if (ParseTargetOptions(Record, Complain, Listener,
2195 AllowCompatibleConfigurationMismatch))
2196 Result = ConfigurationMismatch;
2197 break;
2198 }
2199
2200 case DIAGNOSTIC_OPTIONS: {
2201 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002202 if (ValidateDiagnosticOptions &&
2203 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002204 ParseDiagnosticOptions(Record, Complain, Listener))
2205 return OutOfDate;
2206 break;
2207 }
2208
2209 case FILE_SYSTEM_OPTIONS: {
2210 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2211 if (!AllowCompatibleConfigurationMismatch &&
2212 ParseFileSystemOptions(Record, Complain, Listener))
2213 Result = ConfigurationMismatch;
2214 break;
2215 }
2216
2217 case HEADER_SEARCH_OPTIONS: {
2218 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2219 if (!AllowCompatibleConfigurationMismatch &&
2220 ParseHeaderSearchOptions(Record, Complain, Listener))
2221 Result = ConfigurationMismatch;
2222 break;
2223 }
2224
2225 case PREPROCESSOR_OPTIONS:
2226 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2227 if (!AllowCompatibleConfigurationMismatch &&
2228 ParsePreprocessorOptions(Record, Complain, Listener,
2229 SuggestedPredefines))
2230 Result = ConfigurationMismatch;
2231 break;
2232 }
2233 }
2234}
2235
Guy Benyei11169dd2012-12-18 14:30:41 +00002236ASTReader::ASTReadResult
2237ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002238 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002239 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002241 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002242 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002243
2244 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2245 Error("malformed block record in AST file");
2246 return Failure;
2247 }
2248
2249 // Read all of the records and blocks in the control block.
2250 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002251 unsigned NumInputs = 0;
2252 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002253 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002254 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002255
Chris Lattnere7b154b2013-01-19 21:39:22 +00002256 switch (Entry.Kind) {
2257 case llvm::BitstreamEntry::Error:
2258 Error("malformed block record in AST file");
2259 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002260 case llvm::BitstreamEntry::EndBlock: {
2261 // Validate input files.
2262 const HeaderSearchOptions &HSOpts =
2263 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002264
Richard Smitha1825302014-10-23 22:18:29 +00002265 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002266 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2267 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002268 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2269 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002271
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002272 // If we are reading a module, we will create a verification timestamp,
2273 // so we verify all input files. Otherwise, verify only user input
2274 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002275
2276 unsigned N = NumUserInputs;
2277 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002278 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002279 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002280 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002281 N = NumInputs;
2282
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002283 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002284 InputFile IF = getInputFile(F, I+1, Complain);
2285 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002286 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002287 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002289
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002290 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002291 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002292
Ben Langmuircb69b572014-03-07 06:40:32 +00002293 if (Listener && Listener->needsInputFileVisitation()) {
2294 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2295 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002296 for (unsigned I = 0; I < N; ++I) {
2297 bool IsSystem = I >= NumUserInputs;
2298 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002299 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002300 F.Kind == MK_ExplicitModule ||
2301 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002302 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002303 }
2304
Richard Smith8a308ec2015-11-05 00:54:55 +00002305 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002306 }
2307
Chris Lattnere7b154b2013-01-19 21:39:22 +00002308 case llvm::BitstreamEntry::SubBlock:
2309 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002310 case INPUT_FILES_BLOCK_ID:
2311 F.InputFilesCursor = Stream;
2312 if (Stream.SkipBlock() || // Skip with the main cursor
2313 // Read the abbreviations
2314 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2315 Error("malformed block record in AST file");
2316 return Failure;
2317 }
2318 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002319
2320 case OPTIONS_BLOCK_ID:
2321 // If we're reading the first module for this group, check its options
2322 // are compatible with ours. For modules it imports, no further checking
2323 // is required, because we checked them when we built it.
2324 if (Listener && !ImportedBy) {
2325 // Should we allow the configuration of the module file to differ from
2326 // the configuration of the current translation unit in a compatible
2327 // way?
2328 //
2329 // FIXME: Allow this for files explicitly specified with -include-pch.
2330 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002331 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002332 const HeaderSearchOptions &HSOpts =
2333 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002334
Richard Smith8a308ec2015-11-05 00:54:55 +00002335 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2336 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002337 *Listener, SuggestedPredefines,
2338 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002339 if (Result == Failure) {
2340 Error("malformed block record in AST file");
2341 return Result;
2342 }
2343
Richard Smith8a308ec2015-11-05 00:54:55 +00002344 if (DisableValidation ||
2345 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2346 Result = Success;
2347
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002348 // If we can't load the module, exit early since we likely
2349 // will rebuild the module anyway. The stream may be in the
2350 // middle of a block.
2351 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002352 return Result;
2353 } else if (Stream.SkipBlock()) {
2354 Error("malformed block record in AST file");
2355 return Failure;
2356 }
2357 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002358
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002360 if (Stream.SkipBlock()) {
2361 Error("malformed block record in AST file");
2362 return Failure;
2363 }
2364 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002365 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002366
Chris Lattnere7b154b2013-01-19 21:39:22 +00002367 case llvm::BitstreamEntry::Record:
2368 // The interesting case.
2369 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002370 }
2371
2372 // Read and process a record.
2373 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002374 StringRef Blob;
2375 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 case METADATA: {
2377 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2378 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002379 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2380 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002381 return VersionMismatch;
2382 }
2383
Richard Smithe75ee0f2015-08-17 07:13:32 +00002384 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002385 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2386 Diag(diag::err_pch_with_compiler_errors);
2387 return HadErrors;
2388 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002389 if (hasErrors) {
2390 Diags.ErrorOccurred = true;
2391 Diags.UncompilableErrorOccurred = true;
2392 Diags.UnrecoverableErrorOccurred = true;
2393 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002394
2395 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002396 // Relative paths in a relocatable PCH are relative to our sysroot.
2397 if (F.RelocatablePCH)
2398 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002399
Richard Smithe75ee0f2015-08-17 07:13:32 +00002400 F.HasTimestamps = Record[5];
2401
Guy Benyei11169dd2012-12-18 14:30:41 +00002402 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002403 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2405 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002406 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 return VersionMismatch;
2408 }
2409 break;
2410 }
2411
Ben Langmuir487ea142014-10-23 18:05:36 +00002412 case SIGNATURE:
2413 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2414 F.Signature = Record[0];
2415 break;
2416
Guy Benyei11169dd2012-12-18 14:30:41 +00002417 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002418 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002419 unsigned Idx = 0, N = Record.size();
2420 while (Idx < N) {
2421 // Read information about the AST file.
2422 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2423 // The import location will be the local one for now; we will adjust
2424 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002425 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002427 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002428 off_t StoredSize = (off_t)Record[Idx++];
2429 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002430 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002431 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002432
Richard Smith0f99d6a2015-08-09 08:48:41 +00002433 // If our client can't cope with us being out of date, we can't cope with
2434 // our dependency being missing.
2435 unsigned Capabilities = ClientLoadCapabilities;
2436 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2437 Capabilities &= ~ARR_Missing;
2438
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002440 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2441 Loaded, StoredSize, StoredModTime,
2442 StoredSignature, Capabilities);
2443
2444 // If we diagnosed a problem, produce a backtrace.
2445 if (isDiagnosedResult(Result, Capabilities))
2446 Diag(diag::note_module_file_imported_by)
2447 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2448
2449 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 case Failure: return Failure;
2451 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002452 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 case OutOfDate: return OutOfDate;
2454 case VersionMismatch: return VersionMismatch;
2455 case ConfigurationMismatch: return ConfigurationMismatch;
2456 case HadErrors: return HadErrors;
2457 case Success: break;
2458 }
2459 }
2460 break;
2461 }
2462
Guy Benyei11169dd2012-12-18 14:30:41 +00002463 case ORIGINAL_FILE:
2464 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002465 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002467 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002468 break;
2469
2470 case ORIGINAL_FILE_ID:
2471 F.OriginalSourceFileID = FileID::get(Record[0]);
2472 break;
2473
2474 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002475 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 break;
2477
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002478 case MODULE_NAME:
2479 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002480 if (Listener)
2481 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002482 break;
2483
Richard Smith223d3f22014-12-06 03:21:08 +00002484 case MODULE_DIRECTORY: {
2485 assert(!F.ModuleName.empty() &&
2486 "MODULE_DIRECTORY found before MODULE_NAME");
2487 // If we've already loaded a module map file covering this module, we may
2488 // have a better path for it (relative to the current build).
2489 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2490 if (M && M->Directory) {
2491 // If we're implicitly loading a module, the base directory can't
2492 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002493 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002494 const DirectoryEntry *BuildDir =
2495 PP.getFileManager().getDirectory(Blob);
2496 if (!BuildDir || BuildDir != M->Directory) {
2497 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2498 Diag(diag::err_imported_module_relocated)
2499 << F.ModuleName << Blob << M->Directory->getName();
2500 return OutOfDate;
2501 }
2502 }
2503 F.BaseDirectory = M->Directory->getName();
2504 } else {
2505 F.BaseDirectory = Blob;
2506 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002507 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002508 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002509
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002510 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002511 if (ASTReadResult Result =
2512 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2513 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002514 break;
2515
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002516 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002517 NumInputs = Record[0];
2518 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002519 F.InputFileOffsets =
2520 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002521 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002522 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 break;
2524 }
2525 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002526}
2527
Ben Langmuir2c9af442014-04-10 17:57:43 +00002528ASTReader::ASTReadResult
2529ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002530 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002531
2532 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2533 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002534 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 }
2536
2537 // Read all of the records and blocks for the AST file.
2538 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002539 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002540 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002541
Chris Lattnere7b154b2013-01-19 21:39:22 +00002542 switch (Entry.Kind) {
2543 case llvm::BitstreamEntry::Error:
2544 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002545 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002546 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002547 // Outside of C++, we do not store a lookup map for the translation unit.
2548 // Instead, mark it as needing a lookup map to be built if this module
2549 // contains any declarations lexically within it (which it always does!).
2550 // This usually has no cost, since we very rarely need the lookup map for
2551 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002552 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002553 if (DC->hasExternalLexicalStorage() &&
2554 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002556
Ben Langmuir2c9af442014-04-10 17:57:43 +00002557 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002559 case llvm::BitstreamEntry::SubBlock:
2560 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 case DECLTYPES_BLOCK_ID:
2562 // We lazily load the decls block, but we want to set up the
2563 // DeclsCursor cursor to point into it. Clone our current bitcode
2564 // cursor to it, enter the block and read the abbrevs in that block.
2565 // With the main cursor, we just skip over it.
2566 F.DeclsCursor = Stream;
2567 if (Stream.SkipBlock() || // Skip with the main cursor.
2568 // Read the abbrevs.
2569 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2570 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002571 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002572 }
2573 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002574
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 case PREPROCESSOR_BLOCK_ID:
2576 F.MacroCursor = Stream;
2577 if (!PP.getExternalSource())
2578 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002579
Guy Benyei11169dd2012-12-18 14:30:41 +00002580 if (Stream.SkipBlock() ||
2581 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2582 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002583 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 }
2585 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2586 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002587
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 case PREPROCESSOR_DETAIL_BLOCK_ID:
2589 F.PreprocessorDetailCursor = Stream;
2590 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002591 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002593 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002594 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002595 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002597 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002598
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 if (!PP.getPreprocessingRecord())
2600 PP.createPreprocessingRecord();
2601 if (!PP.getPreprocessingRecord()->getExternalSource())
2602 PP.getPreprocessingRecord()->SetExternalSource(*this);
2603 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002604
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 case SOURCE_MANAGER_BLOCK_ID:
2606 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002607 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002609
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002611 if (ASTReadResult Result =
2612 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002613 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002615
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002617 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 if (Stream.SkipBlock() ||
2619 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2620 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002621 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 }
2623 CommentsCursors.push_back(std::make_pair(C, &F));
2624 break;
2625 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002626
Guy Benyei11169dd2012-12-18 14:30:41 +00002627 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002628 if (Stream.SkipBlock()) {
2629 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002630 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002631 }
2632 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 }
2634 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002635
Chris Lattnere7b154b2013-01-19 21:39:22 +00002636 case llvm::BitstreamEntry::Record:
2637 // The interesting case.
2638 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 }
2640
2641 // Read and process a record.
2642 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002643 StringRef Blob;
2644 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 default: // Default behavior: ignore.
2646 break;
2647
2648 case TYPE_OFFSET: {
2649 if (F.LocalNumTypes != 0) {
2650 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002651 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002653 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002654 F.LocalNumTypes = Record[0];
2655 unsigned LocalBaseTypeIndex = Record[1];
2656 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002657
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 if (F.LocalNumTypes > 0) {
2659 // Introduce the global -> local mapping for types within this module.
2660 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002661
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 // Introduce the local -> global mapping for types within this module.
2663 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002664 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002666
2667 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 }
2669 break;
2670 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002671
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 case DECL_OFFSET: {
2673 if (F.LocalNumDecls != 0) {
2674 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002675 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002677 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002678 F.LocalNumDecls = Record[0];
2679 unsigned LocalBaseDeclID = Record[1];
2680 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002681
Guy Benyei11169dd2012-12-18 14:30:41 +00002682 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002683 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002684 // module.
2685 GlobalDeclMap.insert(
2686 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002687
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 // Introduce the local -> global mapping for declarations within this
2689 // module.
2690 F.DeclRemap.insertOrReplace(
2691 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002692
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 // Introduce the global -> local mapping for declarations within this
2694 // module.
2695 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002696
Ben Langmuir52ca6782014-10-20 16:27:32 +00002697 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2698 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 break;
2700 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002701
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 case TU_UPDATE_LEXICAL: {
2703 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002704 LexicalContents Contents(
2705 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2706 Blob.data()),
2707 static_cast<unsigned int>(Blob.size() / 4));
2708 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002709 TU->setHasExternalLexicalStorage(true);
2710 break;
2711 }
2712
2713 case UPDATE_VISIBLE: {
2714 unsigned Idx = 0;
2715 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002716 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002717 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002718 // If we've already loaded the decl, perform the updates when we finish
2719 // loading this block.
2720 if (Decl *D = GetExistingDecl(ID))
2721 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002722 break;
2723 }
2724
2725 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002726 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002728 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2729 (const unsigned char *)F.IdentifierTableData + Record[0],
2730 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2731 (const unsigned char *)F.IdentifierTableData,
2732 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002733
Guy Benyei11169dd2012-12-18 14:30:41 +00002734 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2735 }
2736 break;
2737
2738 case IDENTIFIER_OFFSET: {
2739 if (F.LocalNumIdentifiers != 0) {
2740 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002741 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002743 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 F.LocalNumIdentifiers = Record[0];
2745 unsigned LocalBaseIdentifierID = Record[1];
2746 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002747
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 if (F.LocalNumIdentifiers > 0) {
2749 // Introduce the global -> local mapping for identifiers within this
2750 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002751 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002752 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002753
Guy Benyei11169dd2012-12-18 14:30:41 +00002754 // Introduce the local -> global mapping for identifiers within this
2755 // module.
2756 F.IdentifierRemap.insertOrReplace(
2757 std::make_pair(LocalBaseIdentifierID,
2758 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002759
Ben Langmuir52ca6782014-10-20 16:27:32 +00002760 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2761 + F.LocalNumIdentifiers);
2762 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 break;
2764 }
2765
Richard Smith33e0f7e2015-07-22 02:08:40 +00002766 case INTERESTING_IDENTIFIERS:
2767 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2768 break;
2769
Ben Langmuir332aafe2014-01-31 01:06:56 +00002770 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002771 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2772 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002773 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002774 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 break;
2776
David Blaikie9ffe5a32017-01-30 05:00:26 +00002777 case MODULAR_CODEGEN_DECLS:
2778 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2779 // them (ie: if we're not codegenerating this module).
2780 if (F.Kind == MK_MainFile)
2781 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2782 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2783 break;
2784
Guy Benyei11169dd2012-12-18 14:30:41 +00002785 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002786 if (SpecialTypes.empty()) {
2787 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2788 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2789 break;
2790 }
2791
2792 if (SpecialTypes.size() != Record.size()) {
2793 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002794 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002795 }
2796
2797 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2798 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2799 if (!SpecialTypes[I])
2800 SpecialTypes[I] = ID;
2801 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2802 // merge step?
2803 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 break;
2805
2806 case STATISTICS:
2807 TotalNumStatements += Record[0];
2808 TotalNumMacros += Record[1];
2809 TotalLexicalDeclContexts += Record[2];
2810 TotalVisibleDeclContexts += Record[3];
2811 break;
2812
2813 case UNUSED_FILESCOPED_DECLS:
2814 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2815 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2816 break;
2817
2818 case DELEGATING_CTORS:
2819 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2820 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2821 break;
2822
2823 case WEAK_UNDECLARED_IDENTIFIERS:
2824 if (Record.size() % 4 != 0) {
2825 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002826 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002827 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002828
2829 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 // files. This isn't the way to do it :)
2831 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002832
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 // Translate the weak, undeclared identifiers into global IDs.
2834 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2835 WeakUndeclaredIdentifiers.push_back(
2836 getGlobalIdentifierID(F, Record[I++]));
2837 WeakUndeclaredIdentifiers.push_back(
2838 getGlobalIdentifierID(F, Record[I++]));
2839 WeakUndeclaredIdentifiers.push_back(
2840 ReadSourceLocation(F, Record, I).getRawEncoding());
2841 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2842 }
2843 break;
2844
Guy Benyei11169dd2012-12-18 14:30:41 +00002845 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002846 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002847 F.LocalNumSelectors = Record[0];
2848 unsigned LocalBaseSelectorID = Record[1];
2849 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002850
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002852 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 // module.
2854 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002855
2856 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 // module.
2858 F.SelectorRemap.insertOrReplace(
2859 std::make_pair(LocalBaseSelectorID,
2860 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002861
2862 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002863 }
2864 break;
2865 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002866
Guy Benyei11169dd2012-12-18 14:30:41 +00002867 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002868 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 if (Record[0])
2870 F.SelectorLookupTable
2871 = ASTSelectorLookupTable::Create(
2872 F.SelectorLookupTableData + Record[0],
2873 F.SelectorLookupTableData,
2874 ASTSelectorLookupTrait(*this, F));
2875 TotalNumMethodPoolEntries += Record[1];
2876 break;
2877
2878 case REFERENCED_SELECTOR_POOL:
2879 if (!Record.empty()) {
2880 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002881 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 Record[Idx++]));
2883 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2884 getRawEncoding());
2885 }
2886 }
2887 break;
2888
2889 case PP_COUNTER_VALUE:
2890 if (!Record.empty() && Listener)
2891 Listener->ReadCounter(F, Record[0]);
2892 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002893
Guy Benyei11169dd2012-12-18 14:30:41 +00002894 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002895 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 F.NumFileSortedDecls = Record[0];
2897 break;
2898
2899 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002900 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 F.LocalNumSLocEntries = Record[0];
2902 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002903 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002904 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002905 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002906 if (!F.SLocEntryBaseID) {
2907 Error("ran out of source locations");
2908 break;
2909 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 // Make our entry in the range map. BaseID is negative and growing, so
2911 // we invert it. Because we invert it, though, we need the other end of
2912 // the range.
2913 unsigned RangeStart =
2914 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2915 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2916 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2917
2918 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2919 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2920 GlobalSLocOffsetMap.insert(
2921 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2922 - SLocSpaceSize,&F));
2923
2924 // Initialize the remapping table.
2925 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002926 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002928 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002930
Guy Benyei11169dd2012-12-18 14:30:41 +00002931 TotalNumSLocEntries += F.LocalNumSLocEntries;
2932 break;
2933 }
2934
2935 case MODULE_OFFSET_MAP: {
2936 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002937 const unsigned char *Data = (const unsigned char*)Blob.data();
2938 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002939
2940 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2941 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2942 F.SLocRemap.insert(std::make_pair(0U, 0));
2943 F.SLocRemap.insert(std::make_pair(2U, 1));
2944 }
2945
Guy Benyei11169dd2012-12-18 14:30:41 +00002946 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002947 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2948 RemapBuilder;
2949 RemapBuilder SLocRemap(F.SLocRemap);
2950 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2951 RemapBuilder MacroRemap(F.MacroRemap);
2952 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2953 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2954 RemapBuilder SelectorRemap(F.SelectorRemap);
2955 RemapBuilder DeclRemap(F.DeclRemap);
2956 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002957
Richard Smithd8879c82015-08-24 21:59:32 +00002958 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002959 using namespace llvm::support;
2960 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 StringRef Name = StringRef((const char*)Data, Len);
2962 Data += Len;
2963 ModuleFile *OM = ModuleMgr.lookup(Name);
2964 if (!OM) {
2965 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002966 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002967 }
2968
Justin Bogner57ba0b22014-03-28 22:03:24 +00002969 uint32_t SLocOffset =
2970 endian::readNext<uint32_t, little, unaligned>(Data);
2971 uint32_t IdentifierIDOffset =
2972 endian::readNext<uint32_t, little, unaligned>(Data);
2973 uint32_t MacroIDOffset =
2974 endian::readNext<uint32_t, little, unaligned>(Data);
2975 uint32_t PreprocessedEntityIDOffset =
2976 endian::readNext<uint32_t, little, unaligned>(Data);
2977 uint32_t SubmoduleIDOffset =
2978 endian::readNext<uint32_t, little, unaligned>(Data);
2979 uint32_t SelectorIDOffset =
2980 endian::readNext<uint32_t, little, unaligned>(Data);
2981 uint32_t DeclIDOffset =
2982 endian::readNext<uint32_t, little, unaligned>(Data);
2983 uint32_t TypeIndexOffset =
2984 endian::readNext<uint32_t, little, unaligned>(Data);
2985
Ben Langmuir785180e2014-10-20 16:27:30 +00002986 uint32_t None = std::numeric_limits<uint32_t>::max();
2987
2988 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2989 RemapBuilder &Remap) {
2990 if (Offset != None)
2991 Remap.insert(std::make_pair(Offset,
2992 static_cast<int>(BaseOffset - Offset)));
2993 };
2994 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2995 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2996 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
2997 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
2998 PreprocessedEntityRemap);
2999 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3000 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3001 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3002 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003003
3004 // Global -> local mappings.
3005 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3006 }
3007 break;
3008 }
3009
3010 case SOURCE_MANAGER_LINE_TABLE:
3011 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003012 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003013 break;
3014
3015 case SOURCE_LOCATION_PRELOADS: {
3016 // Need to transform from the local view (1-based IDs) to the global view,
3017 // which is based off F.SLocEntryBaseID.
3018 if (!F.PreloadSLocEntries.empty()) {
3019 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003020 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003021 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003022
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 F.PreloadSLocEntries.swap(Record);
3024 break;
3025 }
3026
3027 case EXT_VECTOR_DECLS:
3028 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3029 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3030 break;
3031
3032 case VTABLE_USES:
3033 if (Record.size() % 3 != 0) {
3034 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003035 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003036 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003037
Guy Benyei11169dd2012-12-18 14:30:41 +00003038 // Later tables overwrite earlier ones.
3039 // FIXME: Modules will have some trouble with this. This is clearly not
3040 // the right way to do this.
3041 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003042
Guy Benyei11169dd2012-12-18 14:30:41 +00003043 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3044 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3045 VTableUses.push_back(
3046 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3047 VTableUses.push_back(Record[Idx++]);
3048 }
3049 break;
3050
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 case PENDING_IMPLICIT_INSTANTIATIONS:
3052 if (PendingInstantiations.size() % 2 != 0) {
3053 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003054 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003055 }
3056
3057 if (Record.size() % 2 != 0) {
3058 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003059 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 }
3061
3062 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3063 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3064 PendingInstantiations.push_back(
3065 ReadSourceLocation(F, Record, I).getRawEncoding());
3066 }
3067 break;
3068
3069 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003070 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003071 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003072 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003073 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3075 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3076 break;
3077
3078 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003079 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3080 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3081 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003082
3083 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003084
Guy Benyei11169dd2012-12-18 14:30:41 +00003085 unsigned StartingID;
3086 if (!PP.getPreprocessingRecord())
3087 PP.createPreprocessingRecord();
3088 if (!PP.getPreprocessingRecord()->getExternalSource())
3089 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003090 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003091 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003092 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003093 F.BasePreprocessedEntityID = StartingID;
3094
3095 if (F.NumPreprocessedEntities > 0) {
3096 // Introduce the global -> local mapping for preprocessed entities in
3097 // this module.
3098 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003099
Guy Benyei11169dd2012-12-18 14:30:41 +00003100 // Introduce the local -> global mapping for preprocessed entities in
3101 // this module.
3102 F.PreprocessedEntityRemap.insertOrReplace(
3103 std::make_pair(LocalBasePreprocessedEntityID,
3104 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3105 }
3106
3107 break;
3108 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 case DECL_UPDATE_OFFSETS: {
3111 if (Record.size() % 2 != 0) {
3112 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003113 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003115 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3116 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3117 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3118
3119 // If we've already loaded the decl, perform the updates when we finish
3120 // loading this block.
3121 if (Decl *D = GetExistingDecl(ID))
3122 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3123 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 break;
3125 }
3126
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 case OBJC_CATEGORIES_MAP: {
3128 if (F.LocalNumObjCCategoriesInMap != 0) {
3129 Error("duplicate OBJC_CATEGORIES_MAP record 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.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003134 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 break;
3136 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003137
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 case OBJC_CATEGORIES:
3139 F.ObjCCategories.swap(Record);
3140 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003141
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 case DIAG_PRAGMA_MAPPINGS:
3143 if (F.PragmaDiagMappings.empty())
3144 F.PragmaDiagMappings.swap(Record);
3145 else
3146 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3147 Record.begin(), Record.end());
3148 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003149
Guy Benyei11169dd2012-12-18 14:30:41 +00003150 case CUDA_SPECIAL_DECL_REFS:
3151 // Later tables overwrite earlier ones.
3152 // FIXME: Modules will have trouble with this.
3153 CUDASpecialDeclRefs.clear();
3154 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3155 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3156 break;
3157
3158 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003159 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003160 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 if (Record[0]) {
3162 F.HeaderFileInfoTable
3163 = HeaderFileInfoLookupTable::Create(
3164 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3165 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003166 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003168 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003169
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 PP.getHeaderSearchInfo().SetExternalSource(this);
3171 if (!PP.getHeaderSearchInfo().getExternalLookup())
3172 PP.getHeaderSearchInfo().SetExternalLookup(this);
3173 }
3174 break;
3175 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003176
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 case FP_PRAGMA_OPTIONS:
3178 // Later tables overwrite earlier ones.
3179 FPPragmaOptions.swap(Record);
3180 break;
3181
3182 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003183 for (unsigned I = 0, E = Record.size(); I != E; ) {
3184 auto Name = ReadString(Record, I);
3185 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003186 Opt.Supported = Record[I++] != 0;
3187 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003188 Opt.Avail = Record[I++];
3189 Opt.Core = Record[I++];
3190 }
3191 break;
3192
3193 case OPENCL_EXTENSION_TYPES:
3194 for (unsigned I = 0, E = Record.size(); I != E;) {
3195 auto TypeID = static_cast<::TypeID>(Record[I++]);
3196 auto *Type = GetType(TypeID).getTypePtr();
3197 auto NumExt = static_cast<unsigned>(Record[I++]);
3198 for (unsigned II = 0; II != NumExt; ++II) {
3199 auto Ext = ReadString(Record, I);
3200 OpenCLTypeExtMap[Type].insert(Ext);
3201 }
3202 }
3203 break;
3204
3205 case OPENCL_EXTENSION_DECLS:
3206 for (unsigned I = 0, E = Record.size(); I != E;) {
3207 auto DeclID = static_cast<::DeclID>(Record[I++]);
3208 auto *Decl = GetDecl(DeclID);
3209 auto NumExt = static_cast<unsigned>(Record[I++]);
3210 for (unsigned II = 0; II != NumExt; ++II) {
3211 auto Ext = ReadString(Record, I);
3212 OpenCLDeclExtMap[Decl].insert(Ext);
3213 }
3214 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003215 break;
3216
3217 case TENTATIVE_DEFINITIONS:
3218 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3219 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3220 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003221
Guy Benyei11169dd2012-12-18 14:30:41 +00003222 case KNOWN_NAMESPACES:
3223 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3224 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3225 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003226
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003227 case UNDEFINED_BUT_USED:
3228 if (UndefinedButUsed.size() % 2 != 0) {
3229 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003230 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003231 }
3232
3233 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003234 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003235 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003236 }
3237 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003238 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3239 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003240 ReadSourceLocation(F, Record, I).getRawEncoding());
3241 }
3242 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003243 case DELETE_EXPRS_TO_ANALYZE:
3244 for (unsigned I = 0, N = Record.size(); I != N;) {
3245 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3246 const uint64_t Count = Record[I++];
3247 DelayedDeleteExprs.push_back(Count);
3248 for (uint64_t C = 0; C < Count; ++C) {
3249 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3250 bool IsArrayForm = Record[I++] == 1;
3251 DelayedDeleteExprs.push_back(IsArrayForm);
3252 }
3253 }
3254 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003255
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003257 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 // If we aren't loading a module (which has its own exports), make
3259 // all of the imported modules visible.
3260 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003261 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3262 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3263 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003264 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003265 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003266 if (DeserializationListener)
3267 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3268 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003269 }
3270 }
3271 break;
3272 }
3273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 case MACRO_OFFSET: {
3275 if (F.LocalNumMacros != 0) {
3276 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003277 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003278 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003279 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 F.LocalNumMacros = Record[0];
3281 unsigned LocalBaseMacroID = Record[1];
3282 F.BaseMacroID = getTotalNumMacros();
3283
3284 if (F.LocalNumMacros > 0) {
3285 // Introduce the global -> local mapping for macros within this module.
3286 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3287
3288 // Introduce the local -> global mapping for macros within this module.
3289 F.MacroRemap.insertOrReplace(
3290 std::make_pair(LocalBaseMacroID,
3291 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003292
3293 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 }
3295 break;
3296 }
3297
Richard Smithe40f2ba2013-08-07 21:41:30 +00003298 case LATE_PARSED_TEMPLATE: {
3299 LateParsedTemplates.append(Record.begin(), Record.end());
3300 break;
3301 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003302
3303 case OPTIMIZE_PRAGMA_OPTIONS:
3304 if (Record.size() != 1) {
3305 Error("invalid pragma optimize record");
3306 return Failure;
3307 }
3308 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3309 break;
Nico Weber72889432014-09-06 01:25:55 +00003310
Nico Weber779355f2016-03-02 23:22:00 +00003311 case MSSTRUCT_PRAGMA_OPTIONS:
3312 if (Record.size() != 1) {
3313 Error("invalid pragma ms_struct record");
3314 return Failure;
3315 }
3316 PragmaMSStructState = Record[0];
3317 break;
3318
Nico Weber42932312016-03-03 00:17:35 +00003319 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3320 if (Record.size() != 2) {
3321 Error("invalid pragma ms_struct record");
3322 return Failure;
3323 }
3324 PragmaMSPointersToMembersState = Record[0];
3325 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3326 break;
3327
Nico Weber72889432014-09-06 01:25:55 +00003328 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3329 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3330 UnusedLocalTypedefNameCandidates.push_back(
3331 getGlobalDeclID(F, Record[I]));
3332 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003333
3334 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3335 if (Record.size() != 1) {
3336 Error("invalid cuda pragma options record");
3337 return Failure;
3338 }
3339 ForceCUDAHostDeviceDepth = Record[0];
3340 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003341 }
3342 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003343}
3344
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003345ASTReader::ASTReadResult
3346ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3347 const ModuleFile *ImportedBy,
3348 unsigned ClientLoadCapabilities) {
3349 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003350 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003351
Manman Ren11f2a472016-08-18 17:42:15 +00003352 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003353 // For an explicitly-loaded module, we don't care whether the original
3354 // module map file exists or matches.
3355 return Success;
3356 }
3357
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003358 // Try to resolve ModuleName in the current header search context and
3359 // verify that it is found in the same module map file as we saved. If the
3360 // top-level AST file is a main file, skip this check because there is no
3361 // usable header search context.
3362 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003363 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003364 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003365 // An implicitly-loaded module file should have its module listed in some
3366 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003367 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003368 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3369 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3370 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003371 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003372 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3373 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3374 // This module was defined by an imported (explicit) module.
3375 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3376 << ASTFE->getName();
3377 else
3378 // This module was built with a different module map.
3379 Diag(diag::err_imported_module_not_found)
3380 << F.ModuleName << F.FileName << ImportedBy->FileName
3381 << F.ModuleMapPath;
3382 }
3383 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003384 }
3385
Richard Smithe842a472014-10-22 02:05:46 +00003386 assert(M->Name == F.ModuleName && "found module with different name");
3387
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003388 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003389 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003390 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3391 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003392 assert(ImportedBy && "top-level import should be verified");
3393 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3394 Diag(diag::err_imported_module_modmap_changed)
3395 << F.ModuleName << ImportedBy->FileName
3396 << ModMap->getName() << F.ModuleMapPath;
3397 return OutOfDate;
3398 }
3399
3400 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3401 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3402 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003403 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003404 const FileEntry *F =
3405 FileMgr.getFile(Filename, false, false);
3406 if (F == nullptr) {
3407 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3408 Error("could not find file '" + Filename +"' referenced by AST file");
3409 return OutOfDate;
3410 }
3411 AdditionalStoredMaps.insert(F);
3412 }
3413
3414 // Check any additional module map files (e.g. module.private.modulemap)
3415 // that are not in the pcm.
3416 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3417 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3418 // Remove files that match
3419 // Note: SmallPtrSet::erase is really remove
3420 if (!AdditionalStoredMaps.erase(ModMap)) {
3421 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3422 Diag(diag::err_module_different_modmap)
3423 << F.ModuleName << /*new*/0 << ModMap->getName();
3424 return OutOfDate;
3425 }
3426 }
3427 }
3428
3429 // Check any additional module map files that are in the pcm, but not
3430 // found in header search. Cases that match are already removed.
3431 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3432 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3433 Diag(diag::err_module_different_modmap)
3434 << F.ModuleName << /*not new*/1 << ModMap->getName();
3435 return OutOfDate;
3436 }
3437 }
3438
3439 if (Listener)
3440 Listener->ReadModuleMapFile(F.ModuleMapPath);
3441 return Success;
3442}
3443
3444
Douglas Gregorc1489562013-02-12 23:36:21 +00003445/// \brief Move the given method to the back of the global list of methods.
3446static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3447 // Find the entry for this selector in the method pool.
3448 Sema::GlobalMethodPool::iterator Known
3449 = S.MethodPool.find(Method->getSelector());
3450 if (Known == S.MethodPool.end())
3451 return;
3452
3453 // Retrieve the appropriate method list.
3454 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3455 : Known->second.second;
3456 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003457 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003458 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003459 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003460 Found = true;
3461 } else {
3462 // Keep searching.
3463 continue;
3464 }
3465 }
3466
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003467 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003468 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003469 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003470 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003471 }
3472}
3473
Richard Smithde711422015-04-23 21:20:19 +00003474void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003475 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003476 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003477 bool wasHidden = D->Hidden;
3478 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003479
Richard Smith49f906a2014-03-01 00:08:04 +00003480 if (wasHidden && SemaObj) {
3481 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3482 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003483 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 }
3485 }
3486}
3487
Richard Smith49f906a2014-03-01 00:08:04 +00003488void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003489 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003490 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003491 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003492 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003493 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003495 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003496
3497 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003498 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 // there is nothing more to do.
3500 continue;
3501 }
Richard Smith49f906a2014-03-01 00:08:04 +00003502
Guy Benyei11169dd2012-12-18 14:30:41 +00003503 if (!Mod->isAvailable()) {
3504 // Modules that aren't available cannot be made visible.
3505 continue;
3506 }
3507
3508 // Update the module's name visibility.
3509 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003510
Guy Benyei11169dd2012-12-18 14:30:41 +00003511 // If we've already deserialized any names from this module,
3512 // mark them as visible.
3513 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3514 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003515 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003517 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003518 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3519 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003521
Guy Benyei11169dd2012-12-18 14:30:41 +00003522 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003523 SmallVector<Module *, 16> Exports;
3524 Mod->getExportedModules(Exports);
3525 for (SmallVectorImpl<Module *>::iterator
3526 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3527 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003528 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003529 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003530 }
3531 }
3532}
3533
Richard Smith6561f922016-09-12 21:06:40 +00003534/// We've merged the definition \p MergedDef into the existing definition
3535/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3536/// visible.
3537void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3538 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003539 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3540 // in modules other than its owning module. We should instead give the
3541 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003542 if (Def->isHidden()) {
3543 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003544 if (!MergedDef->isHidden())
3545 Def->Hidden = false;
3546 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3547 getContext().mergeDefinitionIntoModule(
3548 Def, MergedDef->getImportedOwningModule(),
3549 /*NotifyListeners*/ false);
3550 PendingMergedDefinitionsToDeduplicate.insert(Def);
3551 } else {
3552 auto SubmoduleID = MergedDef->getOwningModuleID();
3553 assert(SubmoduleID && "hidden definition in no module");
3554 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3555 }
Richard Smith6561f922016-09-12 21:06:40 +00003556 }
3557}
3558
Douglas Gregore060e572013-01-25 01:03:03 +00003559bool ASTReader::loadGlobalIndex() {
3560 if (GlobalIndex)
3561 return false;
3562
3563 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3564 !Context.getLangOpts().Modules)
3565 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003566
Douglas Gregore060e572013-01-25 01:03:03 +00003567 // Try to load the global index.
3568 TriedLoadingGlobalIndex = true;
3569 StringRef ModuleCachePath
3570 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3571 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003572 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003573 if (!Result.first)
3574 return true;
3575
3576 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003577 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003578 return false;
3579}
3580
3581bool ASTReader::isGlobalIndexUnavailable() const {
3582 return Context.getLangOpts().Modules && UseGlobalIndex &&
3583 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3584}
3585
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003586static void updateModuleTimestamp(ModuleFile &MF) {
3587 // Overwrite the timestamp file contents so that file's mtime changes.
3588 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003589 std::error_code EC;
3590 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3591 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003592 return;
3593 OS << "Timestamp file\n";
3594}
3595
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003596/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3597/// cursor into the start of the given block ID, returning false on success and
3598/// true on failure.
3599static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003600 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003601 llvm::BitstreamEntry Entry = Cursor.advance();
3602 switch (Entry.Kind) {
3603 case llvm::BitstreamEntry::Error:
3604 case llvm::BitstreamEntry::EndBlock:
3605 return true;
3606
3607 case llvm::BitstreamEntry::Record:
3608 // Ignore top-level records.
3609 Cursor.skipRecord(Entry.ID);
3610 break;
3611
3612 case llvm::BitstreamEntry::SubBlock:
3613 if (Entry.ID == BlockID) {
3614 if (Cursor.EnterSubBlock(BlockID))
3615 return true;
3616 // Found it!
3617 return false;
3618 }
3619
3620 if (Cursor.SkipBlock())
3621 return true;
3622 }
3623 }
3624}
3625
Benjamin Kramer0772c422016-02-13 13:42:54 +00003626ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003627 ModuleKind Type,
3628 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003629 unsigned ClientLoadCapabilities,
3630 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003631 llvm::SaveAndRestore<SourceLocation>
3632 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3633
Richard Smithd1c46742014-04-30 02:24:17 +00003634 // Defer any pending actions until we get to the end of reading the AST file.
3635 Deserializing AnASTFile(this);
3636
Guy Benyei11169dd2012-12-18 14:30:41 +00003637 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003638 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003639
3640 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003641 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003642 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003643 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003644 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 ClientLoadCapabilities)) {
3646 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003647 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 case OutOfDate:
3649 case VersionMismatch:
3650 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003651 case HadErrors: {
3652 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3653 for (const ImportedModule &IM : Loaded)
3654 LoadedSet.insert(IM.Mod);
3655
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003656 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003657 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003658 ? &PP.getHeaderSearchInfo().getModuleMap()
3659 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003660
3661 // If we find that any modules are unusable, the global index is going
3662 // to be out-of-date. Just remove it.
3663 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003664 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003665 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003666 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 case Success:
3668 break;
3669 }
3670
3671 // Here comes stuff that we only do once the entire chain is loaded.
3672
3673 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003674 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3675 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003676 M != MEnd; ++M) {
3677 ModuleFile &F = *M->Mod;
3678
3679 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003680 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3681 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003682
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003683 // Read the extension blocks.
3684 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3685 if (ASTReadResult Result = ReadExtensionBlock(F))
3686 return Result;
3687 }
3688
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003689 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003690 // bits of all files we've seen.
3691 F.GlobalBitOffset = TotalModulesSizeInBits;
3692 TotalModulesSizeInBits += F.SizeInBits;
3693 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003694
Guy Benyei11169dd2012-12-18 14:30:41 +00003695 // Preload SLocEntries.
3696 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3697 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3698 // Load it through the SourceManager and don't call ReadSLocEntry()
3699 // directly because the entry may have already been loaded in which case
3700 // calling ReadSLocEntry() directly would trigger an assertion in
3701 // SourceManager.
3702 SourceMgr.getLoadedSLocEntryByID(Index);
3703 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003704
3705 // Preload all the pending interesting identifiers by marking them out of
3706 // date.
3707 for (auto Offset : F.PreloadIdentifierOffsets) {
3708 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3709 F.IdentifierTableData + Offset);
3710
3711 ASTIdentifierLookupTrait Trait(*this, F);
3712 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3713 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003714 auto &II = PP.getIdentifierTable().getOwn(Key);
3715 II.setOutOfDate(true);
3716
3717 // Mark this identifier as being from an AST file so that we can track
3718 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003719 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003720
3721 // Associate the ID with the identifier so that the writer can reuse it.
3722 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3723 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003724 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003725 }
3726
Douglas Gregor603cd862013-03-22 18:50:14 +00003727 // Setup the import locations and notify the module manager that we've
3728 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003729 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3730 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 M != MEnd; ++M) {
3732 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003733
3734 ModuleMgr.moduleFileAccepted(&F);
3735
3736 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003737 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003738 // FIXME: We assume that locations from PCH / preamble do not need
3739 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003740 if (!M->ImportedBy)
3741 F.ImportLoc = M->ImportLoc;
3742 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003743 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 }
3745
Richard Smith33e0f7e2015-07-22 02:08:40 +00003746 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003747 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3748 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003749 // Mark all of the identifiers in the identifier table as being out of date,
3750 // so that various accessors know to check the loaded modules when the
3751 // identifier is used.
3752 //
3753 // For C++ modules, we don't need information on many identifiers (just
3754 // those that provide macros or are poisoned), so we mark all of
3755 // the interesting ones via PreloadIdentifierOffsets.
3756 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3757 IdEnd = PP.getIdentifierTable().end();
3758 Id != IdEnd; ++Id)
3759 Id->second->setOutOfDate(true);
3760 }
Manman Rena0f31a02016-04-29 19:04:05 +00003761 // Mark selectors as out of date.
3762 for (auto Sel : SelectorGeneration)
3763 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003764
Guy Benyei11169dd2012-12-18 14:30:41 +00003765 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003766 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3767 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3769 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003770
3771 switch (Unresolved.Kind) {
3772 case UnresolvedModuleRef::Conflict:
3773 if (ResolvedMod) {
3774 Module::Conflict Conflict;
3775 Conflict.Other = ResolvedMod;
3776 Conflict.Message = Unresolved.String.str();
3777 Unresolved.Mod->Conflicts.push_back(Conflict);
3778 }
3779 continue;
3780
3781 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003782 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003783 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003785
Douglas Gregorfb912652013-03-20 21:10:35 +00003786 case UnresolvedModuleRef::Export:
3787 if (ResolvedMod || Unresolved.IsWildcard)
3788 Unresolved.Mod->Exports.push_back(
3789 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3790 continue;
3791 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003792 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003793 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003794
Graydon Hoaree7196af2016-12-09 21:45:49 +00003795 if (Imported)
3796 Imported->append(ImportedModules.begin(),
3797 ImportedModules.end());
3798
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003799 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3800 // Might be unnecessary as use declarations are only used to build the
3801 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003802
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 InitializeContext();
3804
Richard Smith3d8e97e2013-10-18 06:54:39 +00003805 if (SemaObj)
3806 UpdateSema();
3807
Guy Benyei11169dd2012-12-18 14:30:41 +00003808 if (DeserializationListener)
3809 DeserializationListener->ReaderInitialized(this);
3810
3811 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003812 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003813 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 = FileID::get(PrimaryModule.SLocEntryBaseID
3815 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3816
3817 // If this AST file is a precompiled preamble, then set the
3818 // preamble file ID of the source manager to the file source file
3819 // from which the preamble was built.
3820 if (Type == MK_Preamble) {
3821 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3822 } else if (Type == MK_MainFile) {
3823 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3824 }
3825 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003826
Guy Benyei11169dd2012-12-18 14:30:41 +00003827 // For any Objective-C class definitions we have already loaded, make sure
3828 // that we load any additional categories.
3829 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003830 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003831 ObjCClassesLoaded[I],
3832 PreviousGeneration);
3833 }
Douglas Gregore060e572013-01-25 01:03:03 +00003834
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003835 if (PP.getHeaderSearchInfo()
3836 .getHeaderSearchOpts()
3837 .ModulesValidateOncePerBuildSession) {
3838 // Now we are certain that the module and all modules it depends on are
3839 // up to date. Create or update timestamp files for modules that are
3840 // located in the module cache (not for PCH files that could be anywhere
3841 // in the filesystem).
3842 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3843 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003844 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003845 updateModuleTimestamp(*M.Mod);
3846 }
3847 }
3848 }
3849
Guy Benyei11169dd2012-12-18 14:30:41 +00003850 return Success;
3851}
3852
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003853static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003854
Ben Langmuir70a1b812015-03-24 04:43:52 +00003855/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3856static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003857 return Stream.canSkipToPos(4) &&
3858 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003859 Stream.Read(8) == 'P' &&
3860 Stream.Read(8) == 'C' &&
3861 Stream.Read(8) == 'H';
3862}
3863
Richard Smith0f99d6a2015-08-09 08:48:41 +00003864static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3865 switch (Kind) {
3866 case MK_PCH:
3867 return 0; // PCH
3868 case MK_ImplicitModule:
3869 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003870 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003871 return 1; // module
3872 case MK_MainFile:
3873 case MK_Preamble:
3874 return 2; // main source file
3875 }
3876 llvm_unreachable("unknown module kind");
3877}
3878
Guy Benyei11169dd2012-12-18 14:30:41 +00003879ASTReader::ASTReadResult
3880ASTReader::ReadASTCore(StringRef FileName,
3881 ModuleKind Type,
3882 SourceLocation ImportLoc,
3883 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003884 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003885 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003886 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003887 unsigned ClientLoadCapabilities) {
3888 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003889 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003890 ModuleManager::AddModuleResult AddResult
3891 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003892 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003893 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003894 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003895
Douglas Gregor7029ce12013-03-19 00:28:20 +00003896 switch (AddResult) {
3897 case ModuleManager::AlreadyLoaded:
3898 return Success;
3899
3900 case ModuleManager::NewlyLoaded:
3901 // Load module file below.
3902 break;
3903
3904 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003905 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003906 // it.
3907 if (ClientLoadCapabilities & ARR_Missing)
3908 return Missing;
3909
3910 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003911 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003912 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003913 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003914 return Failure;
3915
3916 case ModuleManager::OutOfDate:
3917 // We couldn't load the module file because it is out-of-date. If the
3918 // client can handle out-of-date, return it.
3919 if (ClientLoadCapabilities & ARR_OutOfDate)
3920 return OutOfDate;
3921
3922 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003923 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003924 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003925 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003926 return Failure;
3927 }
3928
Douglas Gregor7029ce12013-03-19 00:28:20 +00003929 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003930
3931 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3932 // module?
3933 if (FileName != "-") {
3934 CurrentDir = llvm::sys::path::parent_path(FileName);
3935 if (CurrentDir.empty()) CurrentDir = ".";
3936 }
3937
3938 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003939 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003940 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003941 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003942
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003944 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003945 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3946 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 return Failure;
3948 }
3949
3950 // This is used for compatibility with older PCH formats.
3951 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003952 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003953 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003954
Chris Lattnerefa77172013-01-20 00:00:22 +00003955 switch (Entry.Kind) {
3956 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003957 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003958 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003959 Error("invalid record at top-level of AST file");
3960 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003961
Chris Lattnerefa77172013-01-20 00:00:22 +00003962 case llvm::BitstreamEntry::SubBlock:
3963 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003964 }
3965
Chris Lattnerefa77172013-01-20 00:00:22 +00003966 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 case CONTROL_BLOCK_ID:
3968 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003969 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003971 // Check that we didn't try to load a non-module AST file as a module.
3972 //
3973 // FIXME: Should we also perform the converse check? Loading a module as
3974 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003975 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3976 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003977 F.ModuleName.empty()) {
3978 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3979 if (Result != OutOfDate ||
3980 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3981 Diag(diag::err_module_file_not_module) << FileName;
3982 return Result;
3983 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003984 break;
3985
3986 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003987 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003988 case OutOfDate: return OutOfDate;
3989 case VersionMismatch: return VersionMismatch;
3990 case ConfigurationMismatch: return ConfigurationMismatch;
3991 case HadErrors: return HadErrors;
3992 }
3993 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003994
Guy Benyei11169dd2012-12-18 14:30:41 +00003995 case AST_BLOCK_ID:
3996 if (!HaveReadControlBlock) {
3997 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00003998 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00003999 return VersionMismatch;
4000 }
4001
4002 // Record that we've loaded this module.
4003 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4004 return Success;
4005
4006 default:
4007 if (Stream.SkipBlock()) {
4008 Error("malformed block record in AST file");
4009 return Failure;
4010 }
4011 break;
4012 }
4013 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004014
4015 return Success;
4016}
4017
4018/// Parse a record and blob containing module file extension metadata.
4019static bool parseModuleFileExtensionMetadata(
4020 const SmallVectorImpl<uint64_t> &Record,
4021 StringRef Blob,
4022 ModuleFileExtensionMetadata &Metadata) {
4023 if (Record.size() < 4) return true;
4024
4025 Metadata.MajorVersion = Record[0];
4026 Metadata.MinorVersion = Record[1];
4027
4028 unsigned BlockNameLen = Record[2];
4029 unsigned UserInfoLen = Record[3];
4030
4031 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4032
4033 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4034 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4035 Blob.data() + BlockNameLen + UserInfoLen);
4036 return false;
4037}
4038
4039ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4040 BitstreamCursor &Stream = F.Stream;
4041
4042 RecordData Record;
4043 while (true) {
4044 llvm::BitstreamEntry Entry = Stream.advance();
4045 switch (Entry.Kind) {
4046 case llvm::BitstreamEntry::SubBlock:
4047 if (Stream.SkipBlock())
4048 return Failure;
4049
4050 continue;
4051
4052 case llvm::BitstreamEntry::EndBlock:
4053 return Success;
4054
4055 case llvm::BitstreamEntry::Error:
4056 return HadErrors;
4057
4058 case llvm::BitstreamEntry::Record:
4059 break;
4060 }
4061
4062 Record.clear();
4063 StringRef Blob;
4064 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4065 switch (RecCode) {
4066 case EXTENSION_METADATA: {
4067 ModuleFileExtensionMetadata Metadata;
4068 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4069 return Failure;
4070
4071 // Find a module file extension with this block name.
4072 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4073 if (Known == ModuleFileExtensions.end()) break;
4074
4075 // Form a reader.
4076 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4077 F, Stream)) {
4078 F.ExtensionReaders.push_back(std::move(Reader));
4079 }
4080
4081 break;
4082 }
4083 }
4084 }
4085
4086 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004087}
4088
Richard Smitha7e2cc62015-05-01 01:53:09 +00004089void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004090 // If there's a listener, notify them that we "read" the translation unit.
4091 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004092 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 Context.getTranslationUnitDecl());
4094
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 // FIXME: Find a better way to deal with collisions between these
4096 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004097
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 // Load the special types.
4099 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4100 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4101 if (!Context.CFConstantStringTypeDecl)
4102 Context.setCFConstantStringType(GetType(String));
4103 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004104
Guy Benyei11169dd2012-12-18 14:30:41 +00004105 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4106 QualType FileType = GetType(File);
4107 if (FileType.isNull()) {
4108 Error("FILE type is NULL");
4109 return;
4110 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004111
Guy Benyei11169dd2012-12-18 14:30:41 +00004112 if (!Context.FILEDecl) {
4113 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4114 Context.setFILEDecl(Typedef->getDecl());
4115 else {
4116 const TagType *Tag = FileType->getAs<TagType>();
4117 if (!Tag) {
4118 Error("Invalid FILE type in AST file");
4119 return;
4120 }
4121 Context.setFILEDecl(Tag->getDecl());
4122 }
4123 }
4124 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004125
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4127 QualType Jmp_bufType = GetType(Jmp_buf);
4128 if (Jmp_bufType.isNull()) {
4129 Error("jmp_buf type is NULL");
4130 return;
4131 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004132
Guy Benyei11169dd2012-12-18 14:30:41 +00004133 if (!Context.jmp_bufDecl) {
4134 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4135 Context.setjmp_bufDecl(Typedef->getDecl());
4136 else {
4137 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4138 if (!Tag) {
4139 Error("Invalid jmp_buf type in AST file");
4140 return;
4141 }
4142 Context.setjmp_bufDecl(Tag->getDecl());
4143 }
4144 }
4145 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4148 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4149 if (Sigjmp_bufType.isNull()) {
4150 Error("sigjmp_buf type is NULL");
4151 return;
4152 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004153
Guy Benyei11169dd2012-12-18 14:30:41 +00004154 if (!Context.sigjmp_bufDecl) {
4155 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4156 Context.setsigjmp_bufDecl(Typedef->getDecl());
4157 else {
4158 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4159 assert(Tag && "Invalid sigjmp_buf type in AST file");
4160 Context.setsigjmp_bufDecl(Tag->getDecl());
4161 }
4162 }
4163 }
4164
4165 if (unsigned ObjCIdRedef
4166 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4167 if (Context.ObjCIdRedefinitionType.isNull())
4168 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4169 }
4170
4171 if (unsigned ObjCClassRedef
4172 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4173 if (Context.ObjCClassRedefinitionType.isNull())
4174 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4175 }
4176
4177 if (unsigned ObjCSelRedef
4178 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4179 if (Context.ObjCSelRedefinitionType.isNull())
4180 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4181 }
4182
4183 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4184 QualType Ucontext_tType = GetType(Ucontext_t);
4185 if (Ucontext_tType.isNull()) {
4186 Error("ucontext_t type is NULL");
4187 return;
4188 }
4189
4190 if (!Context.ucontext_tDecl) {
4191 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4192 Context.setucontext_tDecl(Typedef->getDecl());
4193 else {
4194 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4195 assert(Tag && "Invalid ucontext_t type in AST file");
4196 Context.setucontext_tDecl(Tag->getDecl());
4197 }
4198 }
4199 }
4200 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004201
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4203
4204 // If there were any CUDA special declarations, deserialize them.
4205 if (!CUDASpecialDeclRefs.empty()) {
4206 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4207 Context.setcudaConfigureCallDecl(
4208 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4209 }
Richard Smith56be7542014-03-21 00:33:59 +00004210
Guy Benyei11169dd2012-12-18 14:30:41 +00004211 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004212 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004213 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004214 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004215 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004216 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004217 if (Import.ImportLoc.isValid())
4218 PP.makeModuleVisible(Imported, Import.ImportLoc);
4219 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004220 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004221 }
4222 ImportedModules.clear();
4223}
4224
4225void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004226 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004227}
4228
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004229/// \brief Reads and return the signature record from \p PCH's control block, or
4230/// else returns 0.
4231static ASTFileSignature readASTFileSignature(StringRef PCH) {
4232 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004233 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004234 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004235
4236 // Scan for the CONTROL_BLOCK_ID block.
4237 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4238 return 0;
4239
4240 // Scan for SIGNATURE inside the control block.
4241 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004242 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004243 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004244 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004245 return 0;
4246
4247 Record.clear();
4248 StringRef Blob;
4249 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4250 return Record[0];
4251 }
4252}
4253
Guy Benyei11169dd2012-12-18 14:30:41 +00004254/// \brief Retrieve the name of the original source file name
4255/// directly from the AST file, without actually loading the AST
4256/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004257std::string ASTReader::getOriginalSourceFile(
4258 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004259 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004260 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004261 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004262 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004263 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4264 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 return std::string();
4266 }
4267
4268 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004269 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004270
4271 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004272 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4274 return std::string();
4275 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004276
Chris Lattnere7b154b2013-01-19 21:39:22 +00004277 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004278 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004279 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4280 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004281 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004282
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004283 // Scan for ORIGINAL_FILE inside the control block.
4284 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004285 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004286 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004287 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4288 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004289
Chris Lattnere7b154b2013-01-19 21:39:22 +00004290 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4291 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4292 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004293 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004294
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004296 StringRef Blob;
4297 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4298 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004299 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004300}
4301
4302namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004303
Guy Benyei11169dd2012-12-18 14:30:41 +00004304 class SimplePCHValidator : public ASTReaderListener {
4305 const LangOptions &ExistingLangOpts;
4306 const TargetOptions &ExistingTargetOpts;
4307 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004308 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004309 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004310
Guy Benyei11169dd2012-12-18 14:30:41 +00004311 public:
4312 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4313 const TargetOptions &ExistingTargetOpts,
4314 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004315 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 FileManager &FileMgr)
4317 : ExistingLangOpts(ExistingLangOpts),
4318 ExistingTargetOpts(ExistingTargetOpts),
4319 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004320 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004321 FileMgr(FileMgr)
4322 {
4323 }
4324
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004325 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4326 bool AllowCompatibleDifferences) override {
4327 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4328 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004329 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004330
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004331 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4332 bool AllowCompatibleDifferences) override {
4333 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4334 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004335 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004336
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004337 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4338 StringRef SpecificModuleCachePath,
4339 bool Complain) override {
4340 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4341 ExistingModuleCachePath,
4342 nullptr, ExistingLangOpts);
4343 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004344
Craig Topper3e89dfe2014-03-13 02:13:41 +00004345 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4346 bool Complain,
4347 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004348 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004349 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004350 }
4351 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004352
4353} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004354
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004355bool ASTReader::readASTFileControlBlock(
4356 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004357 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004358 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004359 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004361 // FIXME: This allows use of the VFS; we do not allow use of the
4362 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004363 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 if (!Buffer) {
4365 return true;
4366 }
4367
4368 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004369 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004370
4371 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004372 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004374
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004375 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004376 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004377 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004378
4379 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004380 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004381 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004382 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004383
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004385 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004386 bool DoneWithControlBlock = false;
4387 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004388 llvm::BitstreamEntry Entry = Stream.advance();
4389
4390 switch (Entry.Kind) {
4391 case llvm::BitstreamEntry::SubBlock: {
4392 switch (Entry.ID) {
4393 case OPTIONS_BLOCK_ID: {
4394 std::string IgnoredSuggestedPredefines;
4395 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4396 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004397 Listener, IgnoredSuggestedPredefines,
4398 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004399 return true;
4400 break;
4401 }
4402
4403 case INPUT_FILES_BLOCK_ID:
4404 InputFilesCursor = Stream;
4405 if (Stream.SkipBlock() ||
4406 (NeedsInputFiles &&
4407 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4408 return true;
4409 break;
4410
4411 default:
4412 if (Stream.SkipBlock())
4413 return true;
4414 break;
4415 }
4416
4417 continue;
4418 }
4419
4420 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004421 DoneWithControlBlock = true;
4422 break;
Richard Smith0516b182015-09-08 19:40:14 +00004423
4424 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004425 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004426
4427 case llvm::BitstreamEntry::Record:
4428 break;
4429 }
4430
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004431 if (DoneWithControlBlock) break;
4432
Guy Benyei11169dd2012-12-18 14:30:41 +00004433 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004434 StringRef Blob;
4435 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004436 switch ((ControlRecordTypes)RecCode) {
4437 case METADATA: {
4438 if (Record[0] != VERSION_MAJOR)
4439 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004440
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004441 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004442 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004443
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004444 break;
4445 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004446 case MODULE_NAME:
4447 Listener.ReadModuleName(Blob);
4448 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004449 case MODULE_DIRECTORY:
4450 ModuleDir = Blob;
4451 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004452 case MODULE_MAP_FILE: {
4453 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004454 auto Path = ReadString(Record, Idx);
4455 ResolveImportedPath(Path, ModuleDir);
4456 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004457 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004458 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004459 case INPUT_FILE_OFFSETS: {
4460 if (!NeedsInputFiles)
4461 break;
4462
4463 unsigned NumInputFiles = Record[0];
4464 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004465 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004466 for (unsigned I = 0; I != NumInputFiles; ++I) {
4467 // Go find this input file.
4468 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004469
4470 if (isSystemFile && !NeedsSystemInputFiles)
4471 break; // the rest are system input files
4472
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004473 BitstreamCursor &Cursor = InputFilesCursor;
4474 SavedStreamPosition SavedPosition(Cursor);
4475 Cursor.JumpToBit(InputFileOffs[I]);
4476
4477 unsigned Code = Cursor.ReadCode();
4478 RecordData Record;
4479 StringRef Blob;
4480 bool shouldContinue = false;
4481 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4482 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004483 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004484 std::string Filename = Blob;
4485 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004486 shouldContinue = Listener.visitInputFile(
4487 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004488 break;
4489 }
4490 if (!shouldContinue)
4491 break;
4492 }
4493 break;
4494 }
4495
Richard Smithd4b230b2014-10-27 23:01:16 +00004496 case IMPORTS: {
4497 if (!NeedsImports)
4498 break;
4499
4500 unsigned Idx = 0, N = Record.size();
4501 while (Idx < N) {
4502 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004503 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004504 std::string Filename = ReadString(Record, Idx);
4505 ResolveImportedPath(Filename, ModuleDir);
4506 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004507 }
4508 break;
4509 }
4510
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004511 default:
4512 // No other validation to perform.
4513 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004514 }
4515 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004516
4517 // Look for module file extension blocks, if requested.
4518 if (FindModuleFileExtensions) {
4519 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4520 bool DoneWithExtensionBlock = false;
4521 while (!DoneWithExtensionBlock) {
4522 llvm::BitstreamEntry Entry = Stream.advance();
4523
4524 switch (Entry.Kind) {
4525 case llvm::BitstreamEntry::SubBlock:
4526 if (Stream.SkipBlock())
4527 return true;
4528
4529 continue;
4530
4531 case llvm::BitstreamEntry::EndBlock:
4532 DoneWithExtensionBlock = true;
4533 continue;
4534
4535 case llvm::BitstreamEntry::Error:
4536 return true;
4537
4538 case llvm::BitstreamEntry::Record:
4539 break;
4540 }
4541
4542 Record.clear();
4543 StringRef Blob;
4544 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4545 switch (RecCode) {
4546 case EXTENSION_METADATA: {
4547 ModuleFileExtensionMetadata Metadata;
4548 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4549 return true;
4550
4551 Listener.readModuleFileExtension(Metadata);
4552 break;
4553 }
4554 }
4555 }
4556 }
4557 }
4558
4559 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004560}
4561
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004562bool ASTReader::isAcceptableASTFile(
4563 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004564 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004565 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4566 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004567 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4568 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004569 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004570 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004571 validator,
4572 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004573}
4574
Ben Langmuir2c9af442014-04-10 17:57:43 +00004575ASTReader::ASTReadResult
4576ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004577 // Enter the submodule block.
4578 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4579 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004580 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 }
4582
4583 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4584 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004585 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 RecordData Record;
4587 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004588 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004589
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004590 switch (Entry.Kind) {
4591 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4592 case llvm::BitstreamEntry::Error:
4593 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004594 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004595 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004596 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004597 case llvm::BitstreamEntry::Record:
4598 // The interesting case.
4599 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004600 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004601
Guy Benyei11169dd2012-12-18 14:30:41 +00004602 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004603 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004604 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004605 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4606
4607 if ((Kind == SUBMODULE_METADATA) != First) {
4608 Error("submodule metadata record should be at beginning of block");
4609 return Failure;
4610 }
4611 First = false;
4612
4613 // Submodule information is only valid if we have a current module.
4614 // FIXME: Should we error on these cases?
4615 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4616 Kind != SUBMODULE_DEFINITION)
4617 continue;
4618
4619 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004620 default: // Default behavior: ignore.
4621 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004622
Richard Smith03478d92014-10-23 22:12:14 +00004623 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004624 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004625 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004626 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 }
Richard Smith03478d92014-10-23 22:12:14 +00004628
Chris Lattner0e6c9402013-01-20 02:38:54 +00004629 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004630 unsigned Idx = 0;
4631 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4632 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4633 bool IsFramework = Record[Idx++];
4634 bool IsExplicit = Record[Idx++];
4635 bool IsSystem = Record[Idx++];
4636 bool IsExternC = Record[Idx++];
4637 bool InferSubmodules = Record[Idx++];
4638 bool InferExplicitSubmodules = Record[Idx++];
4639 bool InferExportWildcard = Record[Idx++];
4640 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004641 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004642
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004643 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004644 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004645 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004646
Guy Benyei11169dd2012-12-18 14:30:41 +00004647 // Retrieve this (sub)module from the module map, creating it if
4648 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004649 CurrentModule =
4650 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4651 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004652
4653 // FIXME: set the definition loc for CurrentModule, or call
4654 // ModMap.setInferredModuleAllowedBy()
4655
Guy Benyei11169dd2012-12-18 14:30:41 +00004656 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4657 if (GlobalIndex >= SubmodulesLoaded.size() ||
4658 SubmodulesLoaded[GlobalIndex]) {
4659 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004660 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004661 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004662
Douglas Gregor7029ce12013-03-19 00:28:20 +00004663 if (!ParentModule) {
4664 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4665 if (CurFile != F.File) {
4666 if (!Diags.isDiagnosticInFlight()) {
4667 Diag(diag::err_module_file_conflict)
4668 << CurrentModule->getTopLevelModuleName()
4669 << CurFile->getName()
4670 << F.File->getName();
4671 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004672 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004673 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004674 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004675
4676 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004677 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004678
Adrian Prantl15bcf702015-06-30 17:39:43 +00004679 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004680 CurrentModule->IsFromModuleFile = true;
4681 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004682 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 CurrentModule->InferSubmodules = InferSubmodules;
4684 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4685 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004686 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004687 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004688 if (DeserializationListener)
4689 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004690
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004692
Richard Smith8a3e39a2016-03-28 21:31:09 +00004693 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004694 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004695 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004696 CurrentModule->UnresolvedConflicts.clear();
4697 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004698
4699 // The module is available unless it's missing a requirement; relevant
4700 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4701 // Missing headers that were present when the module was built do not
4702 // make it unavailable -- if we got this far, this must be an explicitly
4703 // imported module file.
4704 CurrentModule->Requirements.clear();
4705 CurrentModule->MissingHeaders.clear();
4706 CurrentModule->IsMissingRequirement =
4707 ParentModule && ParentModule->IsMissingRequirement;
4708 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004709 break;
4710 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004711
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004713 std::string Filename = Blob;
4714 ResolveImportedPath(F, Filename);
4715 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004716 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004717 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4718 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004719 // This can be a spurious difference caused by changing the VFS to
4720 // point to a different copy of the file, and it is too late to
4721 // to rebuild safely.
4722 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4723 // after input file validation only real problems would remain and we
4724 // could just error. For now, assume it's okay.
4725 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004726 }
4727 }
4728 break;
4729 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004730
Richard Smith202210b2014-10-24 20:23:01 +00004731 case SUBMODULE_HEADER:
4732 case SUBMODULE_EXCLUDED_HEADER:
4733 case SUBMODULE_PRIVATE_HEADER:
4734 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004735 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4736 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004737 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004738
Richard Smith202210b2014-10-24 20:23:01 +00004739 case SUBMODULE_TEXTUAL_HEADER:
4740 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4741 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4742 // them here.
4743 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004744
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004746 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 break;
4748 }
4749
4750 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004751 std::string Dirname = Blob;
4752 ResolveImportedPath(F, Dirname);
4753 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004754 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004755 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4756 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004757 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4758 Error("mismatched umbrella directories in submodule");
4759 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004760 }
4761 }
4762 break;
4763 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004764
Guy Benyei11169dd2012-12-18 14:30:41 +00004765 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004766 F.BaseSubmoduleID = getTotalNumSubmodules();
4767 F.LocalNumSubmodules = Record[0];
4768 unsigned LocalBaseSubmoduleID = Record[1];
4769 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004770 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004771 // module.
4772 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004773
4774 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004775 // module.
4776 F.SubmoduleRemap.insertOrReplace(
4777 std::make_pair(LocalBaseSubmoduleID,
4778 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004779
Ben Langmuir52ca6782014-10-20 16:27:32 +00004780 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4781 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004782 break;
4783 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004784
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004786 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004787 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 Unresolved.File = &F;
4789 Unresolved.Mod = CurrentModule;
4790 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004791 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004793 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004794 }
4795 break;
4796 }
4797
4798 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004799 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004800 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 Unresolved.File = &F;
4802 Unresolved.Mod = CurrentModule;
4803 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004804 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004805 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004806 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004807 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004808
4809 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 // the parsed, unresolved exports around.
4811 CurrentModule->UnresolvedExports.clear();
4812 break;
4813 }
4814 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004815 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 Context.getTargetInfo());
4817 break;
4818 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004819
4820 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004821 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004822 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004823 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004824
4825 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004826 CurrentModule->ConfigMacros.push_back(Blob.str());
4827 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004828
4829 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004830 UnresolvedModuleRef Unresolved;
4831 Unresolved.File = &F;
4832 Unresolved.Mod = CurrentModule;
4833 Unresolved.ID = Record[0];
4834 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4835 Unresolved.IsWildcard = false;
4836 Unresolved.String = Blob;
4837 UnresolvedModuleRefs.push_back(Unresolved);
4838 break;
4839 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004840
4841 case SUBMODULE_INITIALIZERS:
4842 SmallVector<uint32_t, 16> Inits;
4843 for (auto &ID : Record)
4844 Inits.push_back(getGlobalDeclID(F, ID));
4845 Context.addLazyModuleInitializers(CurrentModule, Inits);
4846 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 }
4848 }
4849}
4850
4851/// \brief Parse the record that corresponds to a LangOptions data
4852/// structure.
4853///
4854/// This routine parses the language options from the AST file and then gives
4855/// them to the AST listener if one is set.
4856///
4857/// \returns true if the listener deems the file unacceptable, false otherwise.
4858bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4859 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004860 ASTReaderListener &Listener,
4861 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 LangOptions LangOpts;
4863 unsigned Idx = 0;
4864#define LANGOPT(Name, Bits, Default, Description) \
4865 LangOpts.Name = Record[Idx++];
4866#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4867 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4868#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004869#define SANITIZER(NAME, ID) \
4870 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004871#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004872
Ben Langmuircd98cb72015-06-23 18:20:18 +00004873 for (unsigned N = Record[Idx++]; N; --N)
4874 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4875
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4877 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4878 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004879
Ben Langmuird4a667a2015-06-23 18:20:23 +00004880 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004881
4882 // Comment options.
4883 for (unsigned N = Record[Idx++]; N; --N) {
4884 LangOpts.CommentOpts.BlockCommandNames.push_back(
4885 ReadString(Record, Idx));
4886 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004887 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004888
Samuel Antaoee8fb302016-01-06 13:42:12 +00004889 // OpenMP offloading options.
4890 for (unsigned N = Record[Idx++]; N; --N) {
4891 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4892 }
4893
4894 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4895
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004896 return Listener.ReadLanguageOptions(LangOpts, Complain,
4897 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004898}
4899
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004900bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4901 ASTReaderListener &Listener,
4902 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 unsigned Idx = 0;
4904 TargetOptions TargetOpts;
4905 TargetOpts.Triple = ReadString(Record, Idx);
4906 TargetOpts.CPU = ReadString(Record, Idx);
4907 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 for (unsigned N = Record[Idx++]; N; --N) {
4909 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4910 }
4911 for (unsigned N = Record[Idx++]; N; --N) {
4912 TargetOpts.Features.push_back(ReadString(Record, Idx));
4913 }
4914
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004915 return Listener.ReadTargetOptions(TargetOpts, Complain,
4916 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004917}
4918
4919bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4920 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004921 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004922 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004923#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004924#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004925 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004926#include "clang/Basic/DiagnosticOptions.def"
4927
Richard Smith3be1cb22014-08-07 00:24:21 +00004928 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004929 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004930 for (unsigned N = Record[Idx++]; N; --N)
4931 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004932
4933 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4934}
4935
4936bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4937 ASTReaderListener &Listener) {
4938 FileSystemOptions FSOpts;
4939 unsigned Idx = 0;
4940 FSOpts.WorkingDir = ReadString(Record, Idx);
4941 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4942}
4943
4944bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4945 bool Complain,
4946 ASTReaderListener &Listener) {
4947 HeaderSearchOptions HSOpts;
4948 unsigned Idx = 0;
4949 HSOpts.Sysroot = ReadString(Record, Idx);
4950
4951 // Include entries.
4952 for (unsigned N = Record[Idx++]; N; --N) {
4953 std::string Path = ReadString(Record, Idx);
4954 frontend::IncludeDirGroup Group
4955 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004956 bool IsFramework = Record[Idx++];
4957 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004958 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4959 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004960 }
4961
4962 // System header prefixes.
4963 for (unsigned N = Record[Idx++]; N; --N) {
4964 std::string Prefix = ReadString(Record, Idx);
4965 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004966 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 }
4968
4969 HSOpts.ResourceDir = ReadString(Record, Idx);
4970 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004971 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 HSOpts.DisableModuleHash = Record[Idx++];
4973 HSOpts.UseBuiltinIncludes = Record[Idx++];
4974 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4975 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4976 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004977 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004978
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004979 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4980 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004981}
4982
4983bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4984 bool Complain,
4985 ASTReaderListener &Listener,
4986 std::string &SuggestedPredefines) {
4987 PreprocessorOptions PPOpts;
4988 unsigned Idx = 0;
4989
4990 // Macro definitions/undefs
4991 for (unsigned N = Record[Idx++]; N; --N) {
4992 std::string Macro = ReadString(Record, Idx);
4993 bool IsUndef = Record[Idx++];
4994 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4995 }
4996
4997 // Includes
4998 for (unsigned N = Record[Idx++]; N; --N) {
4999 PPOpts.Includes.push_back(ReadString(Record, Idx));
5000 }
5001
5002 // Macro Includes
5003 for (unsigned N = Record[Idx++]; N; --N) {
5004 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5005 }
5006
5007 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005008 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005009 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5010 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5011 PPOpts.ObjCXXARCStandardLibrary =
5012 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5013 SuggestedPredefines.clear();
5014 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5015 SuggestedPredefines);
5016}
5017
5018std::pair<ModuleFile *, unsigned>
5019ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5020 GlobalPreprocessedEntityMapType::iterator
5021 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005022 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005023 "Corrupted global preprocessed entity map");
5024 ModuleFile *M = I->second;
5025 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5026 return std::make_pair(M, LocalIndex);
5027}
5028
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005029llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005030ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5031 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5032 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5033 Mod.NumPreprocessedEntities);
5034
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005035 return llvm::make_range(PreprocessingRecord::iterator(),
5036 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005037}
5038
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005039llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005040ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005041 return llvm::make_range(
5042 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5043 ModuleDeclIterator(this, &Mod,
5044 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005045}
5046
5047PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5048 PreprocessedEntityID PPID = Index+1;
5049 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5050 ModuleFile &M = *PPInfo.first;
5051 unsigned LocalIndex = PPInfo.second;
5052 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5053
Guy Benyei11169dd2012-12-18 14:30:41 +00005054 if (!PP.getPreprocessingRecord()) {
5055 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005056 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005058
5059 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005060 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5061
5062 llvm::BitstreamEntry Entry =
5063 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5064 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005065 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005066
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005068 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5069 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005071 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005072 RecordData Record;
5073 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005074 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5075 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005076 switch (RecType) {
5077 case PPD_MACRO_EXPANSION: {
5078 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005079 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005080 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005081 if (isBuiltin)
5082 Name = getLocalIdentifier(M, Record[1]);
5083 else {
Richard Smith66a81862015-05-04 02:25:31 +00005084 PreprocessedEntityID GlobalID =
5085 getGlobalPreprocessedEntityID(M, Record[1]);
5086 Def = cast<MacroDefinitionRecord>(
5087 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005088 }
5089
5090 MacroExpansion *ME;
5091 if (isBuiltin)
5092 ME = new (PPRec) MacroExpansion(Name, Range);
5093 else
5094 ME = new (PPRec) MacroExpansion(Def, Range);
5095
5096 return ME;
5097 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005098
Guy Benyei11169dd2012-12-18 14:30:41 +00005099 case PPD_MACRO_DEFINITION: {
5100 // Decode the identifier info and then check again; if the macro is
5101 // still defined and associated with the identifier,
5102 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005103 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005104
5105 if (DeserializationListener)
5106 DeserializationListener->MacroDefinitionRead(PPID, MD);
5107
5108 return MD;
5109 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005110
Guy Benyei11169dd2012-12-18 14:30:41 +00005111 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005112 const char *FullFileNameStart = Blob.data() + Record[0];
5113 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005114 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005115 if (!FullFileName.empty())
5116 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005117
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 // FIXME: Stable encoding
5119 InclusionDirective::InclusionKind Kind
5120 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5121 InclusionDirective *ID
5122 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005123 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005124 Record[1], Record[3],
5125 File,
5126 Range);
5127 return ID;
5128 }
5129 }
5130
5131 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5132}
5133
5134/// \brief \arg SLocMapI points at a chunk of a module that contains no
5135/// preprocessed entities or the entities it contains are not the ones we are
5136/// looking for. Find the next module that contains entities and return the ID
5137/// of the first entry.
5138PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5139 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5140 ++SLocMapI;
5141 for (GlobalSLocOffsetMapType::const_iterator
5142 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5143 ModuleFile &M = *SLocMapI->second;
5144 if (M.NumPreprocessedEntities)
5145 return M.BasePreprocessedEntityID;
5146 }
5147
5148 return getTotalNumPreprocessedEntities();
5149}
5150
5151namespace {
5152
Guy Benyei11169dd2012-12-18 14:30:41 +00005153struct PPEntityComp {
5154 const ASTReader &Reader;
5155 ModuleFile &M;
5156
5157 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5158
5159 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5160 SourceLocation LHS = getLoc(L);
5161 SourceLocation RHS = getLoc(R);
5162 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5163 }
5164
5165 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5166 SourceLocation LHS = getLoc(L);
5167 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5168 }
5169
5170 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5171 SourceLocation RHS = getLoc(R);
5172 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5173 }
5174
5175 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005176 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005177 }
5178};
5179
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005180} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005181
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005182PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5183 bool EndsAfter) const {
5184 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005185 return getTotalNumPreprocessedEntities();
5186
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005187 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5188 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005189 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5190 "Corrupted global sloc offset map");
5191
5192 if (SLocMapI->second->NumPreprocessedEntities == 0)
5193 return findNextPreprocessedEntity(SLocMapI);
5194
5195 ModuleFile &M = *SLocMapI->second;
5196 typedef const PPEntityOffset *pp_iterator;
5197 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5198 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5199
5200 size_t Count = M.NumPreprocessedEntities;
5201 size_t Half;
5202 pp_iterator First = pp_begin;
5203 pp_iterator PPI;
5204
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005205 if (EndsAfter) {
5206 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005207 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005208 } else {
5209 // Do a binary search manually instead of using std::lower_bound because
5210 // The end locations of entities may be unordered (when a macro expansion
5211 // is inside another macro argument), but for this case it is not important
5212 // whether we get the first macro expansion or its containing macro.
5213 while (Count > 0) {
5214 Half = Count / 2;
5215 PPI = First;
5216 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005217 if (SourceMgr.isBeforeInTranslationUnit(
5218 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005219 First = PPI;
5220 ++First;
5221 Count = Count - Half - 1;
5222 } else
5223 Count = Half;
5224 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005225 }
5226
5227 if (PPI == pp_end)
5228 return findNextPreprocessedEntity(SLocMapI);
5229
5230 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5231}
5232
Guy Benyei11169dd2012-12-18 14:30:41 +00005233/// \brief Returns a pair of [Begin, End) indices of preallocated
5234/// preprocessed entities that \arg Range encompasses.
5235std::pair<unsigned, unsigned>
5236 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5237 if (Range.isInvalid())
5238 return std::make_pair(0,0);
5239 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5240
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005241 PreprocessedEntityID BeginID =
5242 findPreprocessedEntity(Range.getBegin(), false);
5243 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005244 return std::make_pair(BeginID, EndID);
5245}
5246
5247/// \brief Optionally returns true or false if the preallocated preprocessed
5248/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005249Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005250 FileID FID) {
5251 if (FID.isInvalid())
5252 return false;
5253
5254 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5255 ModuleFile &M = *PPInfo.first;
5256 unsigned LocalIndex = PPInfo.second;
5257 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005258
Richard Smithcb34bd32016-03-27 07:28:06 +00005259 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005260 if (Loc.isInvalid())
5261 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005262
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5264 return true;
5265 else
5266 return false;
5267}
5268
5269namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005270
Guy Benyei11169dd2012-12-18 14:30:41 +00005271 /// \brief Visitor used to search for information about a header file.
5272 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005273 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005274
David Blaikie05785d12013-02-20 22:23:23 +00005275 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005276
Guy Benyei11169dd2012-12-18 14:30:41 +00005277 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005278 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5279 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005280
5281 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005282 HeaderFileInfoLookupTable *Table
5283 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5284 if (!Table)
5285 return false;
5286
5287 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005288 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005289 if (Pos == Table->end())
5290 return false;
5291
Richard Smithbdf2d932015-07-30 03:37:16 +00005292 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005293 return true;
5294 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005295
David Blaikie05785d12013-02-20 22:23:23 +00005296 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005297 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005298
5299} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005300
5301HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005302 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005303 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005304 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005305 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005306
Guy Benyei11169dd2012-12-18 14:30:41 +00005307 return HeaderFileInfo();
5308}
5309
5310void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005311 using DiagState = DiagnosticsEngine::DiagState;
5312 SmallVector<DiagState *, 32> DiagStates;
5313
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005314 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005315 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005316 auto &Record = F.PragmaDiagMappings;
5317 if (Record.empty())
5318 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005319
Richard Smithd230de22017-01-26 01:01:01 +00005320 DiagStates.clear();
5321
5322 auto ReadDiagState =
5323 [&](const DiagState &BasedOn, SourceLocation Loc,
5324 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5325 unsigned BackrefID = Record[Idx++];
5326 if (BackrefID != 0)
5327 return DiagStates[BackrefID - 1];
5328
Guy Benyei11169dd2012-12-18 14:30:41 +00005329 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005330 Diag.DiagStates.push_back(BasedOn);
5331 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005333 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5334 unsigned DiagID = Record[Idx++];
5335 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005336 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005337 if (Mapping.isPragma() || IncludeNonPragmaStates)
5338 NewState->setMapping(DiagID, Mapping);
5339 }
5340 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5341 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5342 ++Idx;
5343 return NewState;
5344 };
5345
5346 auto *FirstState = ReadDiagState(
5347 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5348 SourceLocation(), F.isModule());
5349 SourceLocation CurStateLoc =
5350 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5351 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5352
5353 if (!F.isModule()) {
5354 Diag.DiagStatesByLoc.CurDiagState = CurState;
5355 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5356
5357 // Preserve the property that the imaginary root file describes the
5358 // current state.
5359 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5360 if (T.empty())
5361 T.push_back({CurState, 0});
5362 else
5363 T[0].State = CurState;
5364 }
5365
5366 while (Idx < Record.size()) {
5367 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5368 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5369 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5370 unsigned Transitions = Record[Idx++];
5371
5372 // Note that we don't need to set up Parent/ParentOffset here, because
5373 // we won't be changing the diagnostic state within imported FileIDs
5374 // (other than perhaps appending to the main source file, which has no
5375 // parent).
5376 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5377 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5378 for (unsigned I = 0; I != Transitions; ++I) {
5379 unsigned Offset = Record[Idx++];
5380 auto *State =
5381 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5382 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005383 }
5384 }
Richard Smithd230de22017-01-26 01:01:01 +00005385
5386 // Don't try to read these mappings again.
5387 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005388 }
5389}
5390
5391/// \brief Get the correct cursor and offset for loading a type.
5392ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5393 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5394 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5395 ModuleFile *M = I->second;
5396 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5397}
5398
5399/// \brief Read and return the type with the given index..
5400///
5401/// The index is the type ID, shifted and minus the number of predefs. This
5402/// routine actually reads the record corresponding to the type at the given
5403/// location. It is a helper routine for GetType, which deals with reading type
5404/// IDs.
5405QualType ASTReader::readTypeRecord(unsigned Index) {
5406 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005407 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005408
5409 // Keep track of where we are in the stream, then jump back there
5410 // after reading this type.
5411 SavedStreamPosition SavedPosition(DeclsCursor);
5412
5413 ReadingKindTracker ReadingKind(Read_Type, *this);
5414
5415 // Note that we are loading a type record.
5416 Deserializing AType(this);
5417
5418 unsigned Idx = 0;
5419 DeclsCursor.JumpToBit(Loc.Offset);
5420 RecordData Record;
5421 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005422 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005423 case TYPE_EXT_QUAL: {
5424 if (Record.size() != 2) {
5425 Error("Incorrect encoding of extended qualifier type");
5426 return QualType();
5427 }
5428 QualType Base = readType(*Loc.F, Record, Idx);
5429 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5430 return Context.getQualifiedType(Base, Quals);
5431 }
5432
5433 case TYPE_COMPLEX: {
5434 if (Record.size() != 1) {
5435 Error("Incorrect encoding of complex type");
5436 return QualType();
5437 }
5438 QualType ElemType = readType(*Loc.F, Record, Idx);
5439 return Context.getComplexType(ElemType);
5440 }
5441
5442 case TYPE_POINTER: {
5443 if (Record.size() != 1) {
5444 Error("Incorrect encoding of pointer type");
5445 return QualType();
5446 }
5447 QualType PointeeType = readType(*Loc.F, Record, Idx);
5448 return Context.getPointerType(PointeeType);
5449 }
5450
Reid Kleckner8a365022013-06-24 17:51:48 +00005451 case TYPE_DECAYED: {
5452 if (Record.size() != 1) {
5453 Error("Incorrect encoding of decayed type");
5454 return QualType();
5455 }
5456 QualType OriginalType = readType(*Loc.F, Record, Idx);
5457 QualType DT = Context.getAdjustedParameterType(OriginalType);
5458 if (!isa<DecayedType>(DT))
5459 Error("Decayed type does not decay");
5460 return DT;
5461 }
5462
Reid Kleckner0503a872013-12-05 01:23:43 +00005463 case TYPE_ADJUSTED: {
5464 if (Record.size() != 2) {
5465 Error("Incorrect encoding of adjusted type");
5466 return QualType();
5467 }
5468 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5469 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5470 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5471 }
5472
Guy Benyei11169dd2012-12-18 14:30:41 +00005473 case TYPE_BLOCK_POINTER: {
5474 if (Record.size() != 1) {
5475 Error("Incorrect encoding of block pointer type");
5476 return QualType();
5477 }
5478 QualType PointeeType = readType(*Loc.F, Record, Idx);
5479 return Context.getBlockPointerType(PointeeType);
5480 }
5481
5482 case TYPE_LVALUE_REFERENCE: {
5483 if (Record.size() != 2) {
5484 Error("Incorrect encoding of lvalue reference type");
5485 return QualType();
5486 }
5487 QualType PointeeType = readType(*Loc.F, Record, Idx);
5488 return Context.getLValueReferenceType(PointeeType, Record[1]);
5489 }
5490
5491 case TYPE_RVALUE_REFERENCE: {
5492 if (Record.size() != 1) {
5493 Error("Incorrect encoding of rvalue reference type");
5494 return QualType();
5495 }
5496 QualType PointeeType = readType(*Loc.F, Record, Idx);
5497 return Context.getRValueReferenceType(PointeeType);
5498 }
5499
5500 case TYPE_MEMBER_POINTER: {
5501 if (Record.size() != 2) {
5502 Error("Incorrect encoding of member pointer type");
5503 return QualType();
5504 }
5505 QualType PointeeType = readType(*Loc.F, Record, Idx);
5506 QualType ClassType = readType(*Loc.F, Record, Idx);
5507 if (PointeeType.isNull() || ClassType.isNull())
5508 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005509
Guy Benyei11169dd2012-12-18 14:30:41 +00005510 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5511 }
5512
5513 case TYPE_CONSTANT_ARRAY: {
5514 QualType ElementType = readType(*Loc.F, Record, Idx);
5515 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5516 unsigned IndexTypeQuals = Record[2];
5517 unsigned Idx = 3;
5518 llvm::APInt Size = ReadAPInt(Record, Idx);
5519 return Context.getConstantArrayType(ElementType, Size,
5520 ASM, IndexTypeQuals);
5521 }
5522
5523 case TYPE_INCOMPLETE_ARRAY: {
5524 QualType ElementType = readType(*Loc.F, Record, Idx);
5525 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5526 unsigned IndexTypeQuals = Record[2];
5527 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5528 }
5529
5530 case TYPE_VARIABLE_ARRAY: {
5531 QualType ElementType = readType(*Loc.F, Record, Idx);
5532 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5533 unsigned IndexTypeQuals = Record[2];
5534 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5535 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5536 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5537 ASM, IndexTypeQuals,
5538 SourceRange(LBLoc, RBLoc));
5539 }
5540
5541 case TYPE_VECTOR: {
5542 if (Record.size() != 3) {
5543 Error("incorrect encoding of vector type in AST file");
5544 return QualType();
5545 }
5546
5547 QualType ElementType = readType(*Loc.F, Record, Idx);
5548 unsigned NumElements = Record[1];
5549 unsigned VecKind = Record[2];
5550 return Context.getVectorType(ElementType, NumElements,
5551 (VectorType::VectorKind)VecKind);
5552 }
5553
5554 case TYPE_EXT_VECTOR: {
5555 if (Record.size() != 3) {
5556 Error("incorrect encoding of extended vector type in AST file");
5557 return QualType();
5558 }
5559
5560 QualType ElementType = readType(*Loc.F, Record, Idx);
5561 unsigned NumElements = Record[1];
5562 return Context.getExtVectorType(ElementType, NumElements);
5563 }
5564
5565 case TYPE_FUNCTION_NO_PROTO: {
5566 if (Record.size() != 6) {
5567 Error("incorrect encoding of no-proto function type");
5568 return QualType();
5569 }
5570 QualType ResultType = readType(*Loc.F, Record, Idx);
5571 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5572 (CallingConv)Record[4], Record[5]);
5573 return Context.getFunctionNoProtoType(ResultType, Info);
5574 }
5575
5576 case TYPE_FUNCTION_PROTO: {
5577 QualType ResultType = readType(*Loc.F, Record, Idx);
5578
5579 FunctionProtoType::ExtProtoInfo EPI;
5580 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5581 /*hasregparm*/ Record[2],
5582 /*regparm*/ Record[3],
5583 static_cast<CallingConv>(Record[4]),
5584 /*produces*/ Record[5]);
5585
5586 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005587
5588 EPI.Variadic = Record[Idx++];
5589 EPI.HasTrailingReturn = Record[Idx++];
5590 EPI.TypeQuals = Record[Idx++];
5591 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005592 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005593 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005594
5595 unsigned NumParams = Record[Idx++];
5596 SmallVector<QualType, 16> ParamTypes;
5597 for (unsigned I = 0; I != NumParams; ++I)
5598 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5599
John McCall18afab72016-03-01 00:49:02 +00005600 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5601 if (Idx != Record.size()) {
5602 for (unsigned I = 0; I != NumParams; ++I)
5603 ExtParameterInfos.push_back(
5604 FunctionProtoType::ExtParameterInfo
5605 ::getFromOpaqueValue(Record[Idx++]));
5606 EPI.ExtParameterInfos = ExtParameterInfos.data();
5607 }
5608
5609 assert(Idx == Record.size());
5610
Jordan Rose5c382722013-03-08 21:51:21 +00005611 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005612 }
5613
5614 case TYPE_UNRESOLVED_USING: {
5615 unsigned Idx = 0;
5616 return Context.getTypeDeclType(
5617 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5618 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005619
Guy Benyei11169dd2012-12-18 14:30:41 +00005620 case TYPE_TYPEDEF: {
5621 if (Record.size() != 2) {
5622 Error("incorrect encoding of typedef type");
5623 return QualType();
5624 }
5625 unsigned Idx = 0;
5626 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5627 QualType Canonical = readType(*Loc.F, Record, Idx);
5628 if (!Canonical.isNull())
5629 Canonical = Context.getCanonicalType(Canonical);
5630 return Context.getTypedefType(Decl, Canonical);
5631 }
5632
5633 case TYPE_TYPEOF_EXPR:
5634 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5635
5636 case TYPE_TYPEOF: {
5637 if (Record.size() != 1) {
5638 Error("incorrect encoding of typeof(type) in AST file");
5639 return QualType();
5640 }
5641 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5642 return Context.getTypeOfType(UnderlyingType);
5643 }
5644
5645 case TYPE_DECLTYPE: {
5646 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5647 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5648 }
5649
5650 case TYPE_UNARY_TRANSFORM: {
5651 QualType BaseType = readType(*Loc.F, Record, Idx);
5652 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5653 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5654 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5655 }
5656
Richard Smith74aeef52013-04-26 16:15:35 +00005657 case TYPE_AUTO: {
5658 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005659 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005660 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005661 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005662 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005663
Richard Smith600b5262017-01-26 20:40:47 +00005664 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5665 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5666 QualType Deduced = readType(*Loc.F, Record, Idx);
5667 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5668 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5669 IsDependent);
5670 }
5671
Guy Benyei11169dd2012-12-18 14:30:41 +00005672 case TYPE_RECORD: {
5673 if (Record.size() != 2) {
5674 Error("incorrect encoding of record type");
5675 return QualType();
5676 }
5677 unsigned Idx = 0;
5678 bool IsDependent = Record[Idx++];
5679 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5680 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5681 QualType T = Context.getRecordType(RD);
5682 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5683 return T;
5684 }
5685
5686 case TYPE_ENUM: {
5687 if (Record.size() != 2) {
5688 Error("incorrect encoding of enum type");
5689 return QualType();
5690 }
5691 unsigned Idx = 0;
5692 bool IsDependent = Record[Idx++];
5693 QualType T
5694 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5695 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5696 return T;
5697 }
5698
5699 case TYPE_ATTRIBUTED: {
5700 if (Record.size() != 3) {
5701 Error("incorrect encoding of attributed type");
5702 return QualType();
5703 }
5704 QualType modifiedType = readType(*Loc.F, Record, Idx);
5705 QualType equivalentType = readType(*Loc.F, Record, Idx);
5706 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5707 return Context.getAttributedType(kind, modifiedType, equivalentType);
5708 }
5709
5710 case TYPE_PAREN: {
5711 if (Record.size() != 1) {
5712 Error("incorrect encoding of paren type");
5713 return QualType();
5714 }
5715 QualType InnerType = readType(*Loc.F, Record, Idx);
5716 return Context.getParenType(InnerType);
5717 }
5718
5719 case TYPE_PACK_EXPANSION: {
5720 if (Record.size() != 2) {
5721 Error("incorrect encoding of pack expansion type");
5722 return QualType();
5723 }
5724 QualType Pattern = readType(*Loc.F, Record, Idx);
5725 if (Pattern.isNull())
5726 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005727 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005728 if (Record[1])
5729 NumExpansions = Record[1] - 1;
5730 return Context.getPackExpansionType(Pattern, NumExpansions);
5731 }
5732
5733 case TYPE_ELABORATED: {
5734 unsigned Idx = 0;
5735 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5736 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5737 QualType NamedType = readType(*Loc.F, Record, Idx);
5738 return Context.getElaboratedType(Keyword, NNS, NamedType);
5739 }
5740
5741 case TYPE_OBJC_INTERFACE: {
5742 unsigned Idx = 0;
5743 ObjCInterfaceDecl *ItfD
5744 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5745 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5746 }
5747
Manman Rene6be26c2016-09-13 17:25:08 +00005748 case TYPE_OBJC_TYPE_PARAM: {
5749 unsigned Idx = 0;
5750 ObjCTypeParamDecl *Decl
5751 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5752 unsigned NumProtos = Record[Idx++];
5753 SmallVector<ObjCProtocolDecl*, 4> Protos;
5754 for (unsigned I = 0; I != NumProtos; ++I)
5755 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5756 return Context.getObjCTypeParamType(Decl, Protos);
5757 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005758 case TYPE_OBJC_OBJECT: {
5759 unsigned Idx = 0;
5760 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005761 unsigned NumTypeArgs = Record[Idx++];
5762 SmallVector<QualType, 4> TypeArgs;
5763 for (unsigned I = 0; I != NumTypeArgs; ++I)
5764 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005765 unsigned NumProtos = Record[Idx++];
5766 SmallVector<ObjCProtocolDecl*, 4> Protos;
5767 for (unsigned I = 0; I != NumProtos; ++I)
5768 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005769 bool IsKindOf = Record[Idx++];
5770 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005771 }
5772
5773 case TYPE_OBJC_OBJECT_POINTER: {
5774 unsigned Idx = 0;
5775 QualType Pointee = readType(*Loc.F, Record, Idx);
5776 return Context.getObjCObjectPointerType(Pointee);
5777 }
5778
5779 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5780 unsigned Idx = 0;
5781 QualType Parm = readType(*Loc.F, Record, Idx);
5782 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005783 return Context.getSubstTemplateTypeParmType(
5784 cast<TemplateTypeParmType>(Parm),
5785 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005786 }
5787
5788 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5789 unsigned Idx = 0;
5790 QualType Parm = readType(*Loc.F, Record, Idx);
5791 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5792 return Context.getSubstTemplateTypeParmPackType(
5793 cast<TemplateTypeParmType>(Parm),
5794 ArgPack);
5795 }
5796
5797 case TYPE_INJECTED_CLASS_NAME: {
5798 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5799 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5800 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5801 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005802 const Type *T = nullptr;
5803 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5804 if (const Type *Existing = DI->getTypeForDecl()) {
5805 T = Existing;
5806 break;
5807 }
5808 }
5809 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005810 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005811 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5812 DI->setTypeForDecl(T);
5813 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005814 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005815 }
5816
5817 case TYPE_TEMPLATE_TYPE_PARM: {
5818 unsigned Idx = 0;
5819 unsigned Depth = Record[Idx++];
5820 unsigned Index = Record[Idx++];
5821 bool Pack = Record[Idx++];
5822 TemplateTypeParmDecl *D
5823 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5824 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5825 }
5826
5827 case TYPE_DEPENDENT_NAME: {
5828 unsigned Idx = 0;
5829 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5830 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005831 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005832 QualType Canon = readType(*Loc.F, Record, Idx);
5833 if (!Canon.isNull())
5834 Canon = Context.getCanonicalType(Canon);
5835 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5836 }
5837
5838 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5839 unsigned Idx = 0;
5840 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5841 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005842 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005843 unsigned NumArgs = Record[Idx++];
5844 SmallVector<TemplateArgument, 8> Args;
5845 Args.reserve(NumArgs);
5846 while (NumArgs--)
5847 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5848 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005849 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005850 }
5851
5852 case TYPE_DEPENDENT_SIZED_ARRAY: {
5853 unsigned Idx = 0;
5854
5855 // ArrayType
5856 QualType ElementType = readType(*Loc.F, Record, Idx);
5857 ArrayType::ArraySizeModifier ASM
5858 = (ArrayType::ArraySizeModifier)Record[Idx++];
5859 unsigned IndexTypeQuals = Record[Idx++];
5860
5861 // DependentSizedArrayType
5862 Expr *NumElts = ReadExpr(*Loc.F);
5863 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5864
5865 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5866 IndexTypeQuals, Brackets);
5867 }
5868
5869 case TYPE_TEMPLATE_SPECIALIZATION: {
5870 unsigned Idx = 0;
5871 bool IsDependent = Record[Idx++];
5872 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5873 SmallVector<TemplateArgument, 8> Args;
5874 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5875 QualType Underlying = readType(*Loc.F, Record, Idx);
5876 QualType T;
5877 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005878 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005879 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005880 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005881 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5882 return T;
5883 }
5884
5885 case TYPE_ATOMIC: {
5886 if (Record.size() != 1) {
5887 Error("Incorrect encoding of atomic type");
5888 return QualType();
5889 }
5890 QualType ValueType = readType(*Loc.F, Record, Idx);
5891 return Context.getAtomicType(ValueType);
5892 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005893
Joey Goulye3c85de2016-12-01 11:30:49 +00005894 case TYPE_PIPE: {
5895 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005896 Error("Incorrect encoding of pipe type");
5897 return QualType();
5898 }
5899
5900 // Reading the pipe element type.
5901 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005902 unsigned ReadOnly = Record[1];
5903 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005904 }
5905
Guy Benyei11169dd2012-12-18 14:30:41 +00005906 }
5907 llvm_unreachable("Invalid TypeCode!");
5908}
5909
Richard Smith564417a2014-03-20 21:47:22 +00005910void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5911 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005912 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005913 const RecordData &Record, unsigned &Idx) {
5914 ExceptionSpecificationType EST =
5915 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005916 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005917 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005918 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005919 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005920 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005921 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005922 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005923 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005924 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5925 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005926 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005927 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005928 }
5929}
5930
Guy Benyei11169dd2012-12-18 14:30:41 +00005931class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005932 ModuleFile *F;
5933 ASTReader *Reader;
5934 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005935 unsigned &Idx;
5936
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005937 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005938 return Reader->ReadSourceLocation(*F, Record, Idx);
5939 }
5940
5941 TypeSourceInfo *GetTypeSourceInfo() {
5942 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5943 }
5944
5945 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5946 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005947 }
5948
Guy Benyei11169dd2012-12-18 14:30:41 +00005949public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005950 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005951 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005952 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005953
5954 // We want compile-time assurance that we've enumerated all of
5955 // these, so unfortunately we have to declare them first, then
5956 // define them out-of-line.
5957#define ABSTRACT_TYPELOC(CLASS, PARENT)
5958#define TYPELOC(CLASS, PARENT) \
5959 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5960#include "clang/AST/TypeLocNodes.def"
5961
5962 void VisitFunctionTypeLoc(FunctionTypeLoc);
5963 void VisitArrayTypeLoc(ArrayTypeLoc);
5964};
5965
5966void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5967 // nothing to do
5968}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005969
Guy Benyei11169dd2012-12-18 14:30:41 +00005970void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005971 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005972 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005973 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5974 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5975 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5976 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005977 }
5978}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005979
Guy Benyei11169dd2012-12-18 14:30:41 +00005980void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005981 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005982}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005983
Guy Benyei11169dd2012-12-18 14:30:41 +00005984void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005985 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005986}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005987
Reid Kleckner8a365022013-06-24 17:51:48 +00005988void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5989 // nothing to do
5990}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005991
Reid Kleckner0503a872013-12-05 01:23:43 +00005992void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5993 // nothing to do
5994}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005995
Guy Benyei11169dd2012-12-18 14:30:41 +00005996void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005997 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005998}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005999
Guy Benyei11169dd2012-12-18 14:30:41 +00006000void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006001 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006002}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006003
Guy Benyei11169dd2012-12-18 14:30:41 +00006004void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006005 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006006}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006007
Guy Benyei11169dd2012-12-18 14:30:41 +00006008void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006009 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006010 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006011}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006012
Guy Benyei11169dd2012-12-18 14:30:41 +00006013void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006014 TL.setLBracketLoc(ReadSourceLocation());
6015 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006016 if (Record[Idx++])
6017 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006018 else
Craig Toppera13603a2014-05-22 05:54:18 +00006019 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006020}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006021
Guy Benyei11169dd2012-12-18 14:30:41 +00006022void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6023 VisitArrayTypeLoc(TL);
6024}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006025
Guy Benyei11169dd2012-12-18 14:30:41 +00006026void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6027 VisitArrayTypeLoc(TL);
6028}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006029
Guy Benyei11169dd2012-12-18 14:30:41 +00006030void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6031 VisitArrayTypeLoc(TL);
6032}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006033
Guy Benyei11169dd2012-12-18 14:30:41 +00006034void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6035 DependentSizedArrayTypeLoc TL) {
6036 VisitArrayTypeLoc(TL);
6037}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006038
Guy Benyei11169dd2012-12-18 14:30:41 +00006039void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6040 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006041 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006042}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006043
Guy Benyei11169dd2012-12-18 14:30:41 +00006044void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006045 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006046}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006047
Guy Benyei11169dd2012-12-18 14:30:41 +00006048void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006049 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006050}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006051
Guy Benyei11169dd2012-12-18 14:30:41 +00006052void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006053 TL.setLocalRangeBegin(ReadSourceLocation());
6054 TL.setLParenLoc(ReadSourceLocation());
6055 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006056 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6057 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006058 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006059 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006060 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006061 }
6062}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006063
Guy Benyei11169dd2012-12-18 14:30:41 +00006064void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6065 VisitFunctionTypeLoc(TL);
6066}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006067
Guy Benyei11169dd2012-12-18 14:30:41 +00006068void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6069 VisitFunctionTypeLoc(TL);
6070}
6071void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006072 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006073}
6074void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006075 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006076}
6077void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006078 TL.setTypeofLoc(ReadSourceLocation());
6079 TL.setLParenLoc(ReadSourceLocation());
6080 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006081}
6082void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006083 TL.setTypeofLoc(ReadSourceLocation());
6084 TL.setLParenLoc(ReadSourceLocation());
6085 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006086 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006087}
6088void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006089 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006090}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006091
Guy Benyei11169dd2012-12-18 14:30:41 +00006092void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006093 TL.setKWLoc(ReadSourceLocation());
6094 TL.setLParenLoc(ReadSourceLocation());
6095 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006096 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006097}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006098
Guy Benyei11169dd2012-12-18 14:30:41 +00006099void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006100 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006101}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006102
Richard Smith600b5262017-01-26 20:40:47 +00006103void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6104 DeducedTemplateSpecializationTypeLoc TL) {
6105 TL.setTemplateNameLoc(ReadSourceLocation());
6106}
6107
Guy Benyei11169dd2012-12-18 14:30:41 +00006108void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006109 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006110}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006111
Guy Benyei11169dd2012-12-18 14:30:41 +00006112void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006113 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006114}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006115
Guy Benyei11169dd2012-12-18 14:30:41 +00006116void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006117 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006118 if (TL.hasAttrOperand()) {
6119 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006120 range.setBegin(ReadSourceLocation());
6121 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006122 TL.setAttrOperandParensRange(range);
6123 }
6124 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006125 if (Record[Idx++])
6126 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 else
Craig Toppera13603a2014-05-22 05:54:18 +00006128 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006129 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006130 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006131}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006132
Guy Benyei11169dd2012-12-18 14:30:41 +00006133void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006134 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006135}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006136
Guy Benyei11169dd2012-12-18 14:30:41 +00006137void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6138 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006139 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006140}
6141void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6142 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006143 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006144}
6145void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6146 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006147 TL.setTemplateKeywordLoc(ReadSourceLocation());
6148 TL.setTemplateNameLoc(ReadSourceLocation());
6149 TL.setLAngleLoc(ReadSourceLocation());
6150 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006152 TL.setArgLocInfo(
6153 i,
6154 Reader->GetTemplateArgumentLocInfo(
6155 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006156}
6157void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006158 TL.setLParenLoc(ReadSourceLocation());
6159 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006160}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006161
Guy Benyei11169dd2012-12-18 14:30:41 +00006162void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006163 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006164 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006165}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006166
Guy Benyei11169dd2012-12-18 14:30:41 +00006167void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006168 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006169}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006170
Guy Benyei11169dd2012-12-18 14:30:41 +00006171void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006172 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006173 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006174 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006175}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006176
Guy Benyei11169dd2012-12-18 14:30:41 +00006177void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6178 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006179 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006180 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006181 TL.setTemplateKeywordLoc(ReadSourceLocation());
6182 TL.setTemplateNameLoc(ReadSourceLocation());
6183 TL.setLAngleLoc(ReadSourceLocation());
6184 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006185 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006186 TL.setArgLocInfo(
6187 I,
6188 Reader->GetTemplateArgumentLocInfo(
6189 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006190}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006191
Guy Benyei11169dd2012-12-18 14:30:41 +00006192void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006193 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006194}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006195
Guy Benyei11169dd2012-12-18 14:30:41 +00006196void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006197 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006198}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006199
Manman Rene6be26c2016-09-13 17:25:08 +00006200void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6201 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006202 TL.setProtocolLAngleLoc(ReadSourceLocation());
6203 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006204 }
6205 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006206 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006207}
6208
Guy Benyei11169dd2012-12-18 14:30:41 +00006209void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006210 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006211 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6212 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006213 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006214 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006215 TL.setProtocolLAngleLoc(ReadSourceLocation());
6216 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006217 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006218 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006219}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006220
Guy Benyei11169dd2012-12-18 14:30:41 +00006221void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006222 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006223}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006224
Guy Benyei11169dd2012-12-18 14:30:41 +00006225void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006226 TL.setKWLoc(ReadSourceLocation());
6227 TL.setLParenLoc(ReadSourceLocation());
6228 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006229}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006230
Xiuli Pan9c14e282016-01-09 12:53:17 +00006231void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006232 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006233}
Guy Benyei11169dd2012-12-18 14:30:41 +00006234
David L. Jonesbe1557a2016-12-21 00:17:49 +00006235TypeSourceInfo *
6236ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6237 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006238 QualType InfoTy = readType(F, Record, Idx);
6239 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006240 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006241
6242 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006243 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006244 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6245 TLR.Visit(TL);
6246 return TInfo;
6247}
6248
6249QualType ASTReader::GetType(TypeID ID) {
6250 unsigned FastQuals = ID & Qualifiers::FastMask;
6251 unsigned Index = ID >> Qualifiers::FastWidth;
6252
6253 if (Index < NUM_PREDEF_TYPE_IDS) {
6254 QualType T;
6255 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006256 case PREDEF_TYPE_NULL_ID:
6257 return QualType();
6258 case PREDEF_TYPE_VOID_ID:
6259 T = Context.VoidTy;
6260 break;
6261 case PREDEF_TYPE_BOOL_ID:
6262 T = Context.BoolTy;
6263 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006264
6265 case PREDEF_TYPE_CHAR_U_ID:
6266 case PREDEF_TYPE_CHAR_S_ID:
6267 // FIXME: Check that the signedness of CharTy is correct!
6268 T = Context.CharTy;
6269 break;
6270
Alexey Baderbdf7c842015-09-15 12:18:29 +00006271 case PREDEF_TYPE_UCHAR_ID:
6272 T = Context.UnsignedCharTy;
6273 break;
6274 case PREDEF_TYPE_USHORT_ID:
6275 T = Context.UnsignedShortTy;
6276 break;
6277 case PREDEF_TYPE_UINT_ID:
6278 T = Context.UnsignedIntTy;
6279 break;
6280 case PREDEF_TYPE_ULONG_ID:
6281 T = Context.UnsignedLongTy;
6282 break;
6283 case PREDEF_TYPE_ULONGLONG_ID:
6284 T = Context.UnsignedLongLongTy;
6285 break;
6286 case PREDEF_TYPE_UINT128_ID:
6287 T = Context.UnsignedInt128Ty;
6288 break;
6289 case PREDEF_TYPE_SCHAR_ID:
6290 T = Context.SignedCharTy;
6291 break;
6292 case PREDEF_TYPE_WCHAR_ID:
6293 T = Context.WCharTy;
6294 break;
6295 case PREDEF_TYPE_SHORT_ID:
6296 T = Context.ShortTy;
6297 break;
6298 case PREDEF_TYPE_INT_ID:
6299 T = Context.IntTy;
6300 break;
6301 case PREDEF_TYPE_LONG_ID:
6302 T = Context.LongTy;
6303 break;
6304 case PREDEF_TYPE_LONGLONG_ID:
6305 T = Context.LongLongTy;
6306 break;
6307 case PREDEF_TYPE_INT128_ID:
6308 T = Context.Int128Ty;
6309 break;
6310 case PREDEF_TYPE_HALF_ID:
6311 T = Context.HalfTy;
6312 break;
6313 case PREDEF_TYPE_FLOAT_ID:
6314 T = Context.FloatTy;
6315 break;
6316 case PREDEF_TYPE_DOUBLE_ID:
6317 T = Context.DoubleTy;
6318 break;
6319 case PREDEF_TYPE_LONGDOUBLE_ID:
6320 T = Context.LongDoubleTy;
6321 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006322 case PREDEF_TYPE_FLOAT128_ID:
6323 T = Context.Float128Ty;
6324 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006325 case PREDEF_TYPE_OVERLOAD_ID:
6326 T = Context.OverloadTy;
6327 break;
6328 case PREDEF_TYPE_BOUND_MEMBER:
6329 T = Context.BoundMemberTy;
6330 break;
6331 case PREDEF_TYPE_PSEUDO_OBJECT:
6332 T = Context.PseudoObjectTy;
6333 break;
6334 case PREDEF_TYPE_DEPENDENT_ID:
6335 T = Context.DependentTy;
6336 break;
6337 case PREDEF_TYPE_UNKNOWN_ANY:
6338 T = Context.UnknownAnyTy;
6339 break;
6340 case PREDEF_TYPE_NULLPTR_ID:
6341 T = Context.NullPtrTy;
6342 break;
6343 case PREDEF_TYPE_CHAR16_ID:
6344 T = Context.Char16Ty;
6345 break;
6346 case PREDEF_TYPE_CHAR32_ID:
6347 T = Context.Char32Ty;
6348 break;
6349 case PREDEF_TYPE_OBJC_ID:
6350 T = Context.ObjCBuiltinIdTy;
6351 break;
6352 case PREDEF_TYPE_OBJC_CLASS:
6353 T = Context.ObjCBuiltinClassTy;
6354 break;
6355 case PREDEF_TYPE_OBJC_SEL:
6356 T = Context.ObjCBuiltinSelTy;
6357 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006358#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6359 case PREDEF_TYPE_##Id##_ID: \
6360 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006361 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006362#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006363 case PREDEF_TYPE_SAMPLER_ID:
6364 T = Context.OCLSamplerTy;
6365 break;
6366 case PREDEF_TYPE_EVENT_ID:
6367 T = Context.OCLEventTy;
6368 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006369 case PREDEF_TYPE_CLK_EVENT_ID:
6370 T = Context.OCLClkEventTy;
6371 break;
6372 case PREDEF_TYPE_QUEUE_ID:
6373 T = Context.OCLQueueTy;
6374 break;
6375 case PREDEF_TYPE_NDRANGE_ID:
6376 T = Context.OCLNDRangeTy;
6377 break;
6378 case PREDEF_TYPE_RESERVE_ID_ID:
6379 T = Context.OCLReserveIDTy;
6380 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006381 case PREDEF_TYPE_AUTO_DEDUCT:
6382 T = Context.getAutoDeductType();
6383 break;
6384
6385 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6386 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006387 break;
6388
6389 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6390 T = Context.ARCUnbridgedCastTy;
6391 break;
6392
Guy Benyei11169dd2012-12-18 14:30:41 +00006393 case PREDEF_TYPE_BUILTIN_FN:
6394 T = Context.BuiltinFnTy;
6395 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006396
6397 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6398 T = Context.OMPArraySectionTy;
6399 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006400 }
6401
6402 assert(!T.isNull() && "Unknown predefined type");
6403 return T.withFastQualifiers(FastQuals);
6404 }
6405
6406 Index -= NUM_PREDEF_TYPE_IDS;
6407 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6408 if (TypesLoaded[Index].isNull()) {
6409 TypesLoaded[Index] = readTypeRecord(Index);
6410 if (TypesLoaded[Index].isNull())
6411 return QualType();
6412
6413 TypesLoaded[Index]->setFromAST();
6414 if (DeserializationListener)
6415 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6416 TypesLoaded[Index]);
6417 }
6418
6419 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6420}
6421
6422QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6423 return GetType(getGlobalTypeID(F, LocalID));
6424}
6425
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006426serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006427ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6428 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6429 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006430
Guy Benyei11169dd2012-12-18 14:30:41 +00006431 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6432 return LocalID;
6433
6434 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6435 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6436 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006437
Guy Benyei11169dd2012-12-18 14:30:41 +00006438 unsigned GlobalIndex = LocalIndex + I->second;
6439 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6440}
6441
6442TemplateArgumentLocInfo
6443ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6444 TemplateArgument::ArgKind Kind,
6445 const RecordData &Record,
6446 unsigned &Index) {
6447 switch (Kind) {
6448 case TemplateArgument::Expression:
6449 return ReadExpr(F);
6450 case TemplateArgument::Type:
6451 return GetTypeSourceInfo(F, Record, Index);
6452 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006453 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006454 Index);
6455 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6456 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6457 SourceLocation());
6458 }
6459 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006460 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006461 Index);
6462 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6463 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006464 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006465 EllipsisLoc);
6466 }
6467 case TemplateArgument::Null:
6468 case TemplateArgument::Integral:
6469 case TemplateArgument::Declaration:
6470 case TemplateArgument::NullPtr:
6471 case TemplateArgument::Pack:
6472 // FIXME: Is this right?
6473 return TemplateArgumentLocInfo();
6474 }
6475 llvm_unreachable("unexpected template argument loc");
6476}
6477
6478TemplateArgumentLoc
6479ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6480 const RecordData &Record, unsigned &Index) {
6481 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6482
6483 if (Arg.getKind() == TemplateArgument::Expression) {
6484 if (Record[Index++]) // bool InfoHasSameExpr.
6485 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6486 }
6487 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6488 Record, Index));
6489}
6490
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006491const ASTTemplateArgumentListInfo*
6492ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6493 const RecordData &Record,
6494 unsigned &Index) {
6495 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6496 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6497 unsigned NumArgsAsWritten = Record[Index++];
6498 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6499 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6500 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6501 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6502}
6503
Guy Benyei11169dd2012-12-18 14:30:41 +00006504Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6505 return GetDecl(ID);
6506}
6507
Richard Smith50895422015-01-31 03:04:55 +00006508template<typename TemplateSpecializationDecl>
6509static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6510 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6511 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6512}
6513
Richard Smith053f6c62014-05-16 23:01:30 +00006514void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006515 if (NumCurrentElementsDeserializing) {
6516 // We arrange to not care about the complete redeclaration chain while we're
6517 // deserializing. Just remember that the AST has marked this one as complete
6518 // but that it's not actually complete yet, so we know we still need to
6519 // complete it later.
6520 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6521 return;
6522 }
6523
Richard Smith053f6c62014-05-16 23:01:30 +00006524 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6525
Richard Smith053f6c62014-05-16 23:01:30 +00006526 // If this is a named declaration, complete it by looking it up
6527 // within its context.
6528 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006529 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006530 // all mergeable entities within it.
6531 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6532 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6533 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006534 if (!getContext().getLangOpts().CPlusPlus &&
6535 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006536 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006537 // the identifier instead. (For C++ modules, we don't store decls
6538 // in the serialized identifier table, so we do the lookup in the TU.)
6539 auto *II = Name.getAsIdentifierInfo();
6540 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006541 if (II->isOutOfDate())
6542 updateOutOfDateIdentifier(*II);
6543 } else
6544 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006545 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006546 // Find all declarations of this kind from the relevant context.
6547 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6548 auto *DC = cast<DeclContext>(DCDecl);
6549 SmallVector<Decl*, 8> Decls;
6550 FindExternalLexicalDecls(
6551 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6552 }
Richard Smith053f6c62014-05-16 23:01:30 +00006553 }
6554 }
Richard Smith50895422015-01-31 03:04:55 +00006555
6556 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6557 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6558 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6559 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6560 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6561 if (auto *Template = FD->getPrimaryTemplate())
6562 Template->LoadLazySpecializations();
6563 }
Richard Smith053f6c62014-05-16 23:01:30 +00006564}
6565
Richard Smithc2bb8182015-03-24 06:36:48 +00006566CXXCtorInitializer **
6567ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6568 RecordLocation Loc = getLocalBitOffset(Offset);
6569 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6570 SavedStreamPosition SavedPosition(Cursor);
6571 Cursor.JumpToBit(Loc.Offset);
6572 ReadingKindTracker ReadingKind(Read_Decl, *this);
6573
6574 RecordData Record;
6575 unsigned Code = Cursor.ReadCode();
6576 unsigned RecCode = Cursor.readRecord(Code, Record);
6577 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6578 Error("malformed AST file: missing C++ ctor initializers");
6579 return nullptr;
6580 }
6581
6582 unsigned Idx = 0;
6583 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6584}
6585
Guy Benyei11169dd2012-12-18 14:30:41 +00006586CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6587 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006588 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006589 SavedStreamPosition SavedPosition(Cursor);
6590 Cursor.JumpToBit(Loc.Offset);
6591 ReadingKindTracker ReadingKind(Read_Decl, *this);
6592 RecordData Record;
6593 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006594 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006595 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006596 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006597 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 }
6599
6600 unsigned Idx = 0;
6601 unsigned NumBases = Record[Idx++];
6602 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6603 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6604 for (unsigned I = 0; I != NumBases; ++I)
6605 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6606 return Bases;
6607}
6608
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006609serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006610ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6611 if (LocalID < NUM_PREDEF_DECL_IDS)
6612 return LocalID;
6613
6614 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6615 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6616 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006617
Guy Benyei11169dd2012-12-18 14:30:41 +00006618 return LocalID + I->second;
6619}
6620
6621bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6622 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006623 // Predefined decls aren't from any module.
6624 if (ID < NUM_PREDEF_DECL_IDS)
6625 return false;
6626
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006627 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006628 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006629}
6630
Douglas Gregor9f782892013-01-21 15:25:38 +00006631ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006632 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006633 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6635 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6636 return I->second;
6637}
6638
6639SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6640 if (ID < NUM_PREDEF_DECL_IDS)
6641 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6644
6645 if (Index > DeclsLoaded.size()) {
6646 Error("declaration ID out-of-range for AST file");
6647 return SourceLocation();
6648 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006649
Guy Benyei11169dd2012-12-18 14:30:41 +00006650 if (Decl *D = DeclsLoaded[Index])
6651 return D->getLocation();
6652
Richard Smithcb34bd32016-03-27 07:28:06 +00006653 SourceLocation Loc;
6654 DeclCursorForID(ID, Loc);
6655 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006656}
6657
Richard Smithfe620d22015-03-05 23:24:12 +00006658static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6659 switch (ID) {
6660 case PREDEF_DECL_NULL_ID:
6661 return nullptr;
6662
6663 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6664 return Context.getTranslationUnitDecl();
6665
6666 case PREDEF_DECL_OBJC_ID_ID:
6667 return Context.getObjCIdDecl();
6668
6669 case PREDEF_DECL_OBJC_SEL_ID:
6670 return Context.getObjCSelDecl();
6671
6672 case PREDEF_DECL_OBJC_CLASS_ID:
6673 return Context.getObjCClassDecl();
6674
6675 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6676 return Context.getObjCProtocolDecl();
6677
6678 case PREDEF_DECL_INT_128_ID:
6679 return Context.getInt128Decl();
6680
6681 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6682 return Context.getUInt128Decl();
6683
6684 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6685 return Context.getObjCInstanceTypeDecl();
6686
6687 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6688 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006689
Richard Smith9b88a4c2015-07-27 05:40:23 +00006690 case PREDEF_DECL_VA_LIST_TAG:
6691 return Context.getVaListTagDecl();
6692
Charles Davisc7d5c942015-09-17 20:55:33 +00006693 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6694 return Context.getBuiltinMSVaListDecl();
6695
Richard Smithf19e1272015-03-07 00:04:49 +00006696 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6697 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006698
6699 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6700 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006701
6702 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6703 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006704
6705 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6706 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006707
6708 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6709 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006710 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006711 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006712}
6713
Richard Smithcd45dbc2014-04-19 03:48:30 +00006714Decl *ASTReader::GetExistingDecl(DeclID ID) {
6715 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006716 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6717 if (D) {
6718 // Track that we have merged the declaration with ID \p ID into the
6719 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006720 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006721 if (Merged.empty())
6722 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006723 }
Richard Smithfe620d22015-03-05 23:24:12 +00006724 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006725 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006726
Guy Benyei11169dd2012-12-18 14:30:41 +00006727 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6728
6729 if (Index >= DeclsLoaded.size()) {
6730 assert(0 && "declaration ID out-of-range for AST file");
6731 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006732 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006733 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006734
6735 return DeclsLoaded[Index];
6736}
6737
6738Decl *ASTReader::GetDecl(DeclID ID) {
6739 if (ID < NUM_PREDEF_DECL_IDS)
6740 return GetExistingDecl(ID);
6741
6742 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6743
6744 if (Index >= DeclsLoaded.size()) {
6745 assert(0 && "declaration ID out-of-range for AST file");
6746 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006747 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006748 }
6749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 if (!DeclsLoaded[Index]) {
6751 ReadDeclRecord(ID);
6752 if (DeserializationListener)
6753 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6754 }
6755
6756 return DeclsLoaded[Index];
6757}
6758
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006759DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006760 DeclID GlobalID) {
6761 if (GlobalID < NUM_PREDEF_DECL_IDS)
6762 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006763
Guy Benyei11169dd2012-12-18 14:30:41 +00006764 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6765 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6766 ModuleFile *Owner = I->second;
6767
6768 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6769 = M.GlobalToLocalDeclIDs.find(Owner);
6770 if (Pos == M.GlobalToLocalDeclIDs.end())
6771 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006772
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 return GlobalID - Owner->BaseDeclID + Pos->second;
6774}
6775
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006776serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 const RecordData &Record,
6778 unsigned &Idx) {
6779 if (Idx >= Record.size()) {
6780 Error("Corrupted AST file");
6781 return 0;
6782 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006783
Guy Benyei11169dd2012-12-18 14:30:41 +00006784 return getGlobalDeclID(F, Record[Idx++]);
6785}
6786
6787/// \brief Resolve the offset of a statement into a statement.
6788///
6789/// This operation will read a new statement from the external
6790/// source each time it is called, and is meant to be used via a
6791/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6792Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6793 // Switch case IDs are per Decl.
6794 ClearSwitchCaseIDs();
6795
6796 // Offset here is a global offset across the entire chain.
6797 RecordLocation Loc = getLocalBitOffset(Offset);
6798 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6799 return ReadStmtFromStream(*Loc.F);
6800}
6801
Richard Smith3cb15722015-08-05 22:41:45 +00006802void ASTReader::FindExternalLexicalDecls(
6803 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6804 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006805 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6806
Richard Smith9ccdd932015-08-06 22:14:12 +00006807 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006808 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6809 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6810 auto K = (Decl::Kind)+LexicalDecls[I];
6811 if (!IsKindWeWant(K))
6812 continue;
6813
6814 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6815
6816 // Don't add predefined declarations to the lexical context more
6817 // than once.
6818 if (ID < NUM_PREDEF_DECL_IDS) {
6819 if (PredefsVisited[ID])
6820 continue;
6821
6822 PredefsVisited[ID] = true;
6823 }
6824
6825 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006826 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006827 if (!DC->isDeclInLexicalTraversal(D))
6828 Decls.push_back(D);
6829 }
6830 }
6831 };
6832
6833 if (isa<TranslationUnitDecl>(DC)) {
6834 for (auto Lexical : TULexicalDecls)
6835 Visit(Lexical.first, Lexical.second);
6836 } else {
6837 auto I = LexicalDecls.find(DC);
6838 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006839 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006840 }
6841
Guy Benyei11169dd2012-12-18 14:30:41 +00006842 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006843}
6844
6845namespace {
6846
6847class DeclIDComp {
6848 ASTReader &Reader;
6849 ModuleFile &Mod;
6850
6851public:
6852 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6853
6854 bool operator()(LocalDeclID L, LocalDeclID R) const {
6855 SourceLocation LHS = getLocation(L);
6856 SourceLocation RHS = getLocation(R);
6857 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6858 }
6859
6860 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6861 SourceLocation RHS = getLocation(R);
6862 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6863 }
6864
6865 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6866 SourceLocation LHS = getLocation(L);
6867 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6868 }
6869
6870 SourceLocation getLocation(LocalDeclID ID) const {
6871 return Reader.getSourceManager().getFileLoc(
6872 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6873 }
6874};
6875
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006876} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006877
6878void ASTReader::FindFileRegionDecls(FileID File,
6879 unsigned Offset, unsigned Length,
6880 SmallVectorImpl<Decl *> &Decls) {
6881 SourceManager &SM = getSourceManager();
6882
6883 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6884 if (I == FileDeclIDs.end())
6885 return;
6886
6887 FileDeclsInfo &DInfo = I->second;
6888 if (DInfo.Decls.empty())
6889 return;
6890
6891 SourceLocation
6892 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6893 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6894
6895 DeclIDComp DIDComp(*this, *DInfo.Mod);
6896 ArrayRef<serialization::LocalDeclID>::iterator
6897 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6898 BeginLoc, DIDComp);
6899 if (BeginIt != DInfo.Decls.begin())
6900 --BeginIt;
6901
6902 // If we are pointing at a top-level decl inside an objc container, we need
6903 // to backtrack until we find it otherwise we will fail to report that the
6904 // region overlaps with an objc container.
6905 while (BeginIt != DInfo.Decls.begin() &&
6906 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6907 ->isTopLevelDeclInObjCContainer())
6908 --BeginIt;
6909
6910 ArrayRef<serialization::LocalDeclID>::iterator
6911 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6912 EndLoc, DIDComp);
6913 if (EndIt != DInfo.Decls.end())
6914 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006915
Guy Benyei11169dd2012-12-18 14:30:41 +00006916 for (ArrayRef<serialization::LocalDeclID>::iterator
6917 DIt = BeginIt; DIt != EndIt; ++DIt)
6918 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6919}
6920
Richard Smith9ce12e32013-02-07 03:30:24 +00006921bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006922ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6923 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006924 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006925 "DeclContext has no visible decls in storage");
6926 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006927 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006928
Richard Smithd88a7f12015-09-01 20:35:42 +00006929 auto It = Lookups.find(DC);
6930 if (It == Lookups.end())
6931 return false;
6932
Richard Smith8c913ec2014-08-14 02:21:01 +00006933 Deserializing LookupResults(this);
6934
Richard Smithd88a7f12015-09-01 20:35:42 +00006935 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006936 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006937 for (DeclID ID : It->second.Table.find(Name)) {
6938 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6939 if (ND->getDeclName() == Name)
6940 Decls.push_back(ND);
6941 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006942
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 ++NumVisibleDeclContextsRead;
6944 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006945 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006946}
6947
Guy Benyei11169dd2012-12-18 14:30:41 +00006948void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6949 if (!DC->hasExternalVisibleStorage())
6950 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006951
6952 auto It = Lookups.find(DC);
6953 assert(It != Lookups.end() &&
6954 "have external visible storage but no lookup tables");
6955
Craig Topper79be4cd2013-07-05 04:33:53 +00006956 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006957
Richard Smithd88a7f12015-09-01 20:35:42 +00006958 for (DeclID ID : It->second.Table.findAll()) {
6959 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6960 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006961 }
6962
Guy Benyei11169dd2012-12-18 14:30:41 +00006963 ++NumVisibleDeclContextsRead;
6964
Craig Topper79be4cd2013-07-05 04:33:53 +00006965 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6967 }
6968 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6969}
6970
Richard Smithd88a7f12015-09-01 20:35:42 +00006971const serialization::reader::DeclContextLookupTable *
6972ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6973 auto I = Lookups.find(Primary);
6974 return I == Lookups.end() ? nullptr : &I->second;
6975}
6976
Guy Benyei11169dd2012-12-18 14:30:41 +00006977/// \brief Under non-PCH compilation the consumer receives the objc methods
6978/// before receiving the implementation, and codegen depends on this.
6979/// We simulate this by deserializing and passing to consumer the methods of the
6980/// implementation before passing the deserialized implementation decl.
6981static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6982 ASTConsumer *Consumer) {
6983 assert(ImplD && Consumer);
6984
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006985 for (auto *I : ImplD->methods())
6986 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006987
6988 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6989}
6990
6991void ASTReader::PassInterestingDeclsToConsumer() {
6992 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006993
6994 if (PassingDeclsToConsumer)
6995 return;
6996
6997 // Guard variable to avoid recursively redoing the process of passing
6998 // decls to consumer.
6999 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7000 true);
7001
Richard Smith9e2341d2015-03-23 03:25:59 +00007002 // Ensure that we've loaded all potentially-interesting declarations
7003 // that need to be eagerly loaded.
7004 for (auto ID : EagerlyDeserializedDecls)
7005 GetDecl(ID);
7006 EagerlyDeserializedDecls.clear();
7007
Guy Benyei11169dd2012-12-18 14:30:41 +00007008 while (!InterestingDecls.empty()) {
7009 Decl *D = InterestingDecls.front();
7010 InterestingDecls.pop_front();
7011
7012 PassInterestingDeclToConsumer(D);
7013 }
7014}
7015
7016void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7017 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7018 PassObjCImplDeclToConsumer(ImplD, Consumer);
7019 else
7020 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7021}
7022
7023void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7024 this->Consumer = Consumer;
7025
Richard Smith9e2341d2015-03-23 03:25:59 +00007026 if (Consumer)
7027 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007028
7029 if (DeserializationListener)
7030 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007031}
7032
7033void ASTReader::PrintStats() {
7034 std::fprintf(stderr, "*** AST File Statistics:\n");
7035
7036 unsigned NumTypesLoaded
7037 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7038 QualType());
7039 unsigned NumDeclsLoaded
7040 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007041 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007042 unsigned NumIdentifiersLoaded
7043 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7044 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007045 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007046 unsigned NumMacrosLoaded
7047 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7048 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007049 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007050 unsigned NumSelectorsLoaded
7051 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7052 SelectorsLoaded.end(),
7053 Selector());
7054
7055 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7056 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7057 NumSLocEntriesRead, TotalNumSLocEntries,
7058 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7059 if (!TypesLoaded.empty())
7060 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7061 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7062 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7063 if (!DeclsLoaded.empty())
7064 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7065 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7066 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7067 if (!IdentifiersLoaded.empty())
7068 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7069 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7070 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7071 if (!MacrosLoaded.empty())
7072 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7073 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7074 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7075 if (!SelectorsLoaded.empty())
7076 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7077 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7078 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7079 if (TotalNumStatements)
7080 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7081 NumStatementsRead, TotalNumStatements,
7082 ((float)NumStatementsRead/TotalNumStatements * 100));
7083 if (TotalNumMacros)
7084 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7085 NumMacrosRead, TotalNumMacros,
7086 ((float)NumMacrosRead/TotalNumMacros * 100));
7087 if (TotalLexicalDeclContexts)
7088 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7089 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7090 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7091 * 100));
7092 if (TotalVisibleDeclContexts)
7093 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7094 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7095 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7096 * 100));
7097 if (TotalNumMethodPoolEntries) {
7098 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7099 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7100 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7101 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007102 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007103 if (NumMethodPoolLookups) {
7104 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7105 NumMethodPoolHits, NumMethodPoolLookups,
7106 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7107 }
7108 if (NumMethodPoolTableLookups) {
7109 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7110 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7111 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7112 * 100.0));
7113 }
7114
Douglas Gregor00a50f72013-01-25 00:38:33 +00007115 if (NumIdentifierLookupHits) {
7116 std::fprintf(stderr,
7117 " %u / %u identifier table lookups succeeded (%f%%)\n",
7118 NumIdentifierLookupHits, NumIdentifierLookups,
7119 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7120 }
7121
Douglas Gregore060e572013-01-25 01:03:03 +00007122 if (GlobalIndex) {
7123 std::fprintf(stderr, "\n");
7124 GlobalIndex->printStats();
7125 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007126
Guy Benyei11169dd2012-12-18 14:30:41 +00007127 std::fprintf(stderr, "\n");
7128 dump();
7129 std::fprintf(stderr, "\n");
7130}
7131
7132template<typename Key, typename ModuleFile, unsigned InitialCapacity>
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007133static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007134dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007135 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007136 InitialCapacity> &Map) {
7137 if (Map.begin() == Map.end())
7138 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007139
Guy Benyei11169dd2012-12-18 14:30:41 +00007140 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7141 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007142 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 I != IEnd; ++I) {
7144 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7145 << "\n";
7146 }
7147}
7148
Yaron Kerencdae9412016-01-29 19:38:18 +00007149LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007150 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7151 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7152 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7153 dumpModuleIDMap("Global type map", GlobalTypeMap);
7154 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7155 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7156 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7157 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7158 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007159 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007160 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007161
Guy Benyei11169dd2012-12-18 14:30:41 +00007162 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007163 for (ModuleFile &M : ModuleMgr)
7164 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007165}
7166
7167/// Return the amount of memory used by memory buffers, breaking down
7168/// by heap-backed versus mmap'ed memory.
7169void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007170 for (ModuleFile &I : ModuleMgr) {
7171 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007172 size_t bytes = buf->getBufferSize();
7173 switch (buf->getBufferKind()) {
7174 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7175 sizes.malloc_bytes += bytes;
7176 break;
7177 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7178 sizes.mmap_bytes += bytes;
7179 break;
7180 }
7181 }
7182 }
7183}
7184
7185void ASTReader::InitializeSema(Sema &S) {
7186 SemaObj = &S;
7187 S.addExternalSource(this);
7188
7189 // Makes sure any declarations that were deserialized "too early"
7190 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007191 for (uint64_t ID : PreloadedDeclIDs) {
7192 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7193 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007194 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007195 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007196
Richard Smith3d8e97e2013-10-18 06:54:39 +00007197 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007198 if (!FPPragmaOptions.empty()) {
7199 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7200 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7201 }
7202
Yaxun Liu5b746652016-12-18 05:18:55 +00007203 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7204 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7205 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007206
7207 UpdateSema();
7208}
7209
7210void ASTReader::UpdateSema() {
7211 assert(SemaObj && "no Sema to update");
7212
7213 // Load the offsets of the declarations that Sema references.
7214 // They will be lazily deserialized when needed.
7215 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007216 assert(SemaDeclRefs.size() % 3 == 0);
7217 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007218 if (!SemaObj->StdNamespace)
7219 SemaObj->StdNamespace = SemaDeclRefs[I];
7220 if (!SemaObj->StdBadAlloc)
7221 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007222 if (!SemaObj->StdAlignValT)
7223 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007224 }
7225 SemaDeclRefs.clear();
7226 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007227
Nico Weber779355f2016-03-02 23:22:00 +00007228 // Update the state of pragmas. Use the same API as if we had encountered the
7229 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007230 if(OptimizeOffPragmaLocation.isValid())
7231 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007232 if (PragmaMSStructState != -1)
7233 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007234 if (PointersToMembersPragmaLocation.isValid()) {
7235 SemaObj->ActOnPragmaMSPointersToMembers(
7236 (LangOptions::PragmaMSPointersToMembersKind)
7237 PragmaMSPointersToMembersState,
7238 PointersToMembersPragmaLocation);
7239 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007240 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007241}
7242
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007243IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007244 // Note that we are loading an identifier.
7245 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007246
Douglas Gregor7211ac12013-01-25 23:32:03 +00007247 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007248 NumIdentifierLookups,
7249 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007250
7251 // We don't need to do identifier table lookups in C++ modules (we preload
7252 // all interesting declarations, and don't need to use the scope for name
7253 // lookups). Perform the lookup in PCH files, though, since we don't build
7254 // a complete initial identifier table if we're carrying on from a PCH.
7255 if (Context.getLangOpts().CPlusPlus) {
7256 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007257 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007258 break;
7259 } else {
7260 // If there is a global index, look there first to determine which modules
7261 // provably do not have any results for this identifier.
7262 GlobalModuleIndex::HitSet Hits;
7263 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7264 if (!loadGlobalIndex()) {
7265 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7266 HitsPtr = &Hits;
7267 }
7268 }
7269
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007270 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007271 }
7272
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 IdentifierInfo *II = Visitor.getIdentifierInfo();
7274 markIdentifierUpToDate(II);
7275 return II;
7276}
7277
7278namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007279
Guy Benyei11169dd2012-12-18 14:30:41 +00007280 /// \brief An identifier-lookup iterator that enumerates all of the
7281 /// identifiers stored within a set of AST files.
7282 class ASTIdentifierIterator : public IdentifierIterator {
7283 /// \brief The AST reader whose identifiers are being enumerated.
7284 const ASTReader &Reader;
7285
7286 /// \brief The current index into the chain of AST files stored in
7287 /// the AST reader.
7288 unsigned Index;
7289
7290 /// \brief The current position within the identifier lookup table
7291 /// of the current AST file.
7292 ASTIdentifierLookupTable::key_iterator Current;
7293
7294 /// \brief The end position within the identifier lookup table of
7295 /// the current AST file.
7296 ASTIdentifierLookupTable::key_iterator End;
7297
Ben Langmuir537c5b52016-05-04 00:53:13 +00007298 /// \brief Whether to skip any modules in the ASTReader.
7299 bool SkipModules;
7300
Guy Benyei11169dd2012-12-18 14:30:41 +00007301 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007302 explicit ASTIdentifierIterator(const ASTReader &Reader,
7303 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007304
Craig Topper3e89dfe2014-03-13 02:13:41 +00007305 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007306 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007307
7308} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007309
Ben Langmuir537c5b52016-05-04 00:53:13 +00007310ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7311 bool SkipModules)
7312 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007313}
7314
7315StringRef ASTIdentifierIterator::Next() {
7316 while (Current == End) {
7317 // If we have exhausted all of our AST files, we're done.
7318 if (Index == 0)
7319 return StringRef();
7320
7321 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007322 ModuleFile &F = Reader.ModuleMgr[Index];
7323 if (SkipModules && F.isModule())
7324 continue;
7325
7326 ASTIdentifierLookupTable *IdTable =
7327 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007328 Current = IdTable->key_begin();
7329 End = IdTable->key_end();
7330 }
7331
7332 // We have any identifiers remaining in the current AST file; return
7333 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007334 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007335 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007336 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007337}
7338
Ben Langmuir537c5b52016-05-04 00:53:13 +00007339namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007340
Ben Langmuir537c5b52016-05-04 00:53:13 +00007341/// A utility for appending two IdentifierIterators.
7342class ChainedIdentifierIterator : public IdentifierIterator {
7343 std::unique_ptr<IdentifierIterator> Current;
7344 std::unique_ptr<IdentifierIterator> Queued;
7345
7346public:
7347 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7348 std::unique_ptr<IdentifierIterator> Second)
7349 : Current(std::move(First)), Queued(std::move(Second)) {}
7350
7351 StringRef Next() override {
7352 if (!Current)
7353 return StringRef();
7354
7355 StringRef result = Current->Next();
7356 if (!result.empty())
7357 return result;
7358
7359 // Try the queued iterator, which may itself be empty.
7360 Current.reset();
7361 std::swap(Current, Queued);
7362 return Next();
7363 }
7364};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007365
Ben Langmuir537c5b52016-05-04 00:53:13 +00007366} // end anonymous namespace.
7367
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007368IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007369 if (!loadGlobalIndex()) {
7370 std::unique_ptr<IdentifierIterator> ReaderIter(
7371 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7372 std::unique_ptr<IdentifierIterator> ModulesIter(
7373 GlobalIndex->createIdentifierIterator());
7374 return new ChainedIdentifierIterator(std::move(ReaderIter),
7375 std::move(ModulesIter));
7376 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007377
Guy Benyei11169dd2012-12-18 14:30:41 +00007378 return new ASTIdentifierIterator(*this);
7379}
7380
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007381namespace clang {
7382namespace serialization {
7383
Guy Benyei11169dd2012-12-18 14:30:41 +00007384 class ReadMethodPoolVisitor {
7385 ASTReader &Reader;
7386 Selector Sel;
7387 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007388 unsigned InstanceBits;
7389 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007390 bool InstanceHasMoreThanOneDecl;
7391 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007392 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7393 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007394
7395 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007396 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007397 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007398 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007399 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7400 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007401
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007402 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007403 if (!M.SelectorLookupTable)
7404 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007405
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007407 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007408 return true;
7409
Richard Smithbdf2d932015-07-30 03:37:16 +00007410 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 ASTSelectorLookupTable *PoolTable
7412 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007413 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 if (Pos == PoolTable->end())
7415 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007416
Richard Smithbdf2d932015-07-30 03:37:16 +00007417 ++Reader.NumMethodPoolTableHits;
7418 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007419 // FIXME: Not quite happy with the statistics here. We probably should
7420 // disable this tracking when called via LoadSelector.
7421 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007422 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007424 if (Reader.DeserializationListener)
7425 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007426
Richard Smithbdf2d932015-07-30 03:37:16 +00007427 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7428 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7429 InstanceBits = Data.InstanceBits;
7430 FactoryBits = Data.FactoryBits;
7431 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7432 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007433 return true;
7434 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007435
Guy Benyei11169dd2012-12-18 14:30:41 +00007436 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007437 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7438 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 }
7440
7441 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007442 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007443 return FactoryMethods;
7444 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007445
7446 unsigned getInstanceBits() const { return InstanceBits; }
7447 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007448 bool instanceHasMoreThanOneDecl() const {
7449 return InstanceHasMoreThanOneDecl;
7450 }
7451 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007452 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007453
7454} // end namespace serialization
7455} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007456
7457/// \brief Add the given set of methods to the method list.
7458static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7459 ObjCMethodList &List) {
7460 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7461 S.addMethodToGlobalList(&List, Methods[I]);
7462 }
7463}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007464
Guy Benyei11169dd2012-12-18 14:30:41 +00007465void ASTReader::ReadMethodPool(Selector Sel) {
7466 // Get the selector generation and update it to the current generation.
7467 unsigned &Generation = SelectorGeneration[Sel];
7468 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007469 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007470 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007471
Guy Benyei11169dd2012-12-18 14:30:41 +00007472 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007473 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007474 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007475 ModuleMgr.visit(Visitor);
7476
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007478 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007479 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007480
7481 ++NumMethodPoolHits;
7482
Guy Benyei11169dd2012-12-18 14:30:41 +00007483 if (!getSema())
7484 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007485
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 Sema &S = *getSema();
7487 Sema::GlobalMethodPool::iterator Pos
7488 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007489
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007490 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007491 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007492 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007493 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007494
7495 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7496 // when building a module we keep every method individually and may need to
7497 // update hasMoreThanOneDecl as we add the methods.
7498 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7499 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007500}
7501
Manman Rena0f31a02016-04-29 19:04:05 +00007502void ASTReader::updateOutOfDateSelector(Selector Sel) {
7503 if (SelectorOutOfDate[Sel])
7504 ReadMethodPool(Sel);
7505}
7506
Guy Benyei11169dd2012-12-18 14:30:41 +00007507void ASTReader::ReadKnownNamespaces(
7508 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7509 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007510
Guy Benyei11169dd2012-12-18 14:30:41 +00007511 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007512 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007513 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7514 Namespaces.push_back(Namespace);
7515 }
7516}
7517
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007518void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007519 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007520 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7521 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007522 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007523 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007524 Undefined.insert(std::make_pair(D, Loc));
7525 }
7526}
Nick Lewycky8334af82013-01-26 00:35:08 +00007527
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007528void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7529 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7530 Exprs) {
7531 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7532 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7533 uint64_t Count = DelayedDeleteExprs[Idx++];
7534 for (uint64_t C = 0; C < Count; ++C) {
7535 SourceLocation DeleteLoc =
7536 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7537 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7538 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7539 }
7540 }
7541}
7542
Guy Benyei11169dd2012-12-18 14:30:41 +00007543void ASTReader::ReadTentativeDefinitions(
7544 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7545 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7546 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7547 if (Var)
7548 TentativeDefs.push_back(Var);
7549 }
7550 TentativeDefinitions.clear();
7551}
7552
7553void ASTReader::ReadUnusedFileScopedDecls(
7554 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7555 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7556 DeclaratorDecl *D
7557 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7558 if (D)
7559 Decls.push_back(D);
7560 }
7561 UnusedFileScopedDecls.clear();
7562}
7563
7564void ASTReader::ReadDelegatingConstructors(
7565 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7566 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7567 CXXConstructorDecl *D
7568 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7569 if (D)
7570 Decls.push_back(D);
7571 }
7572 DelegatingCtorDecls.clear();
7573}
7574
7575void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7576 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7577 TypedefNameDecl *D
7578 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7579 if (D)
7580 Decls.push_back(D);
7581 }
7582 ExtVectorDecls.clear();
7583}
7584
Nico Weber72889432014-09-06 01:25:55 +00007585void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7586 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7587 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7588 ++I) {
7589 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7590 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7591 if (D)
7592 Decls.insert(D);
7593 }
7594 UnusedLocalTypedefNameCandidates.clear();
7595}
7596
Guy Benyei11169dd2012-12-18 14:30:41 +00007597void ASTReader::ReadReferencedSelectors(
7598 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7599 if (ReferencedSelectorsData.empty())
7600 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007601
Guy Benyei11169dd2012-12-18 14:30:41 +00007602 // If there are @selector references added them to its pool. This is for
7603 // implementation of -Wselector.
7604 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7605 unsigned I = 0;
7606 while (I < DataSize) {
7607 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7608 SourceLocation SelLoc
7609 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7610 Sels.push_back(std::make_pair(Sel, SelLoc));
7611 }
7612 ReferencedSelectorsData.clear();
7613}
7614
7615void ASTReader::ReadWeakUndeclaredIdentifiers(
7616 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7617 if (WeakUndeclaredIdentifiers.empty())
7618 return;
7619
7620 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007621 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007622 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007623 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007624 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7625 SourceLocation Loc
7626 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7627 bool Used = WeakUndeclaredIdentifiers[I++];
7628 WeakInfo WI(AliasId, Loc);
7629 WI.setUsed(Used);
7630 WeakIDs.push_back(std::make_pair(WeakId, WI));
7631 }
7632 WeakUndeclaredIdentifiers.clear();
7633}
7634
7635void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7636 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7637 ExternalVTableUse VT;
7638 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7639 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7640 VT.DefinitionRequired = VTableUses[Idx++];
7641 VTables.push_back(VT);
7642 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007643
Guy Benyei11169dd2012-12-18 14:30:41 +00007644 VTableUses.clear();
7645}
7646
7647void ASTReader::ReadPendingInstantiations(
7648 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7649 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7650 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7651 SourceLocation Loc
7652 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7653
7654 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007655 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007656 PendingInstantiations.clear();
7657}
7658
Richard Smithe40f2ba2013-08-07 21:41:30 +00007659void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007660 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7661 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007662 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7663 /* In loop */) {
7664 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7665
Justin Lebar28f09c52016-10-10 16:26:08 +00007666 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007667 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7668
7669 ModuleFile *F = getOwningModuleFile(LT->D);
7670 assert(F && "No module");
7671
7672 unsigned TokN = LateParsedTemplates[Idx++];
7673 LT->Toks.reserve(TokN);
7674 for (unsigned T = 0; T < TokN; ++T)
7675 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7676
Justin Lebar28f09c52016-10-10 16:26:08 +00007677 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007678 }
7679
7680 LateParsedTemplates.clear();
7681}
7682
Guy Benyei11169dd2012-12-18 14:30:41 +00007683void ASTReader::LoadSelector(Selector Sel) {
7684 // It would be complicated to avoid reading the methods anyway. So don't.
7685 ReadMethodPool(Sel);
7686}
7687
7688void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7689 assert(ID && "Non-zero identifier ID required");
7690 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7691 IdentifiersLoaded[ID - 1] = II;
7692 if (DeserializationListener)
7693 DeserializationListener->IdentifierRead(ID, II);
7694}
7695
7696/// \brief Set the globally-visible declarations associated with the given
7697/// identifier.
7698///
7699/// If the AST reader is currently in a state where the given declaration IDs
7700/// cannot safely be resolved, they are queued until it is safe to resolve
7701/// them.
7702///
7703/// \param II an IdentifierInfo that refers to one or more globally-visible
7704/// declarations.
7705///
7706/// \param DeclIDs the set of declaration IDs with the name @p II that are
7707/// visible at global scope.
7708///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007709/// \param Decls if non-null, this vector will be populated with the set of
7710/// deserialized declarations. These declarations will not be pushed into
7711/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007712void
7713ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7714 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007715 SmallVectorImpl<Decl *> *Decls) {
7716 if (NumCurrentElementsDeserializing && !Decls) {
7717 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 return;
7719 }
7720
7721 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007722 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007723 // Queue this declaration so that it will be added to the
7724 // translation unit scope and identifier's declaration chain
7725 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007726 PreloadedDeclIDs.push_back(DeclIDs[I]);
7727 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007728 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007729
7730 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7731
7732 // If we're simply supposed to record the declarations, do so now.
7733 if (Decls) {
7734 Decls->push_back(D);
7735 continue;
7736 }
7737
7738 // Introduce this declaration into the translation-unit scope
7739 // and add it to the declaration chain for this identifier, so
7740 // that (unqualified) name lookup will find it.
7741 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007742 }
7743}
7744
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007745IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007746 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007747 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748
7749 if (IdentifiersLoaded.empty()) {
7750 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007751 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007752 }
7753
7754 ID -= 1;
7755 if (!IdentifiersLoaded[ID]) {
7756 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7757 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7758 ModuleFile *M = I->second;
7759 unsigned Index = ID - M->BaseIdentifierID;
7760 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7761
7762 // All of the strings in the AST file are preceded by a 16-bit length.
7763 // Extract that 16-bit length to avoid having to execute strlen().
7764 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7765 // unsigned integers. This is important to avoid integer overflow when
7766 // we cast them to 'unsigned'.
7767 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7768 unsigned StrLen = (((unsigned) StrLenPtr[0])
7769 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007770 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7771 IdentifiersLoaded[ID] = &II;
7772 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007773 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007774 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007775 }
7776
7777 return IdentifiersLoaded[ID];
7778}
7779
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007780IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7781 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007782}
7783
7784IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7785 if (LocalID < NUM_PREDEF_IDENT_IDS)
7786 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007787
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7789 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007790 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007791 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007792
Guy Benyei11169dd2012-12-18 14:30:41 +00007793 return LocalID + I->second;
7794}
7795
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007796MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007797 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007798 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007799
7800 if (MacrosLoaded.empty()) {
7801 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007802 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007803 }
7804
7805 ID -= NUM_PREDEF_MACRO_IDS;
7806 if (!MacrosLoaded[ID]) {
7807 GlobalMacroMapType::iterator I
7808 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7809 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7810 ModuleFile *M = I->second;
7811 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007812 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007813
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007814 if (DeserializationListener)
7815 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7816 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007817 }
7818
7819 return MacrosLoaded[ID];
7820}
7821
7822MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7823 if (LocalID < NUM_PREDEF_MACRO_IDS)
7824 return LocalID;
7825
7826 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7827 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7828 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7829
7830 return LocalID + I->second;
7831}
7832
7833serialization::SubmoduleID
7834ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7835 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7836 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007837
Guy Benyei11169dd2012-12-18 14:30:41 +00007838 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7839 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007840 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007842
Guy Benyei11169dd2012-12-18 14:30:41 +00007843 return LocalID + I->second;
7844}
7845
7846Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7847 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7848 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007849 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007850 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007851
Guy Benyei11169dd2012-12-18 14:30:41 +00007852 if (GlobalID > SubmodulesLoaded.size()) {
7853 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007854 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007855 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007856
Guy Benyei11169dd2012-12-18 14:30:41 +00007857 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7858}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007859
7860Module *ASTReader::getModule(unsigned ID) {
7861 return getSubmodule(ID);
7862}
7863
Richard Smithd88a7f12015-09-01 20:35:42 +00007864ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7865 if (ID & 1) {
7866 // It's a module, look it up by submodule ID.
7867 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7868 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7869 } else {
7870 // It's a prefix (preamble, PCH, ...). Look it up by index.
7871 unsigned IndexFromEnd = ID >> 1;
7872 assert(IndexFromEnd && "got reference to unknown module file");
7873 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7874 }
7875}
7876
7877unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7878 if (!F)
7879 return 1;
7880
7881 // For a file representing a module, use the submodule ID of the top-level
7882 // module as the file ID. For any other kind of file, the number of such
7883 // files loaded beforehand will be the same on reload.
7884 // FIXME: Is this true even if we have an explicit module file and a PCH?
7885 if (F->isModule())
7886 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7887
7888 auto PCHModules = getModuleManager().pch_modules();
7889 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7890 assert(I != PCHModules.end() && "emitting reference to unknown file");
7891 return (I - PCHModules.end()) << 1;
7892}
7893
Adrian Prantl15bcf702015-06-30 17:39:43 +00007894llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7895ASTReader::getSourceDescriptor(unsigned ID) {
7896 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007897 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007898
7899 // If there is only a single PCH, return it instead.
7900 // Chained PCH are not suported.
7901 if (ModuleMgr.size() == 1) {
7902 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007903 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007904 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7905 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7906 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007907 }
7908 return None;
7909}
7910
David Blaikie9ffe5a32017-01-30 05:00:26 +00007911ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
7912 const Module *M = getSubmodule(ID);
7913 if (!M || !M->WithCodegen)
7914 return EK_ReplyHazy;
7915
7916 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
7917 assert(MF); // ?
7918 if (MF->Kind == ModuleKind::MK_MainFile)
7919 return EK_Never;
7920 return EK_Always;
7921}
7922
Guy Benyei11169dd2012-12-18 14:30:41 +00007923Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7924 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7925}
7926
7927Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7928 if (ID == 0)
7929 return Selector();
7930
7931 if (ID > SelectorsLoaded.size()) {
7932 Error("selector ID out of range in AST file");
7933 return Selector();
7934 }
7935
Craig Toppera13603a2014-05-22 05:54:18 +00007936 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 // Load this selector from the selector table.
7938 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7939 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7940 ModuleFile &M = *I->second;
7941 ASTSelectorLookupTrait Trait(*this, M);
7942 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7943 SelectorsLoaded[ID - 1] =
7944 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7945 if (DeserializationListener)
7946 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7947 }
7948
7949 return SelectorsLoaded[ID - 1];
7950}
7951
7952Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7953 return DecodeSelector(ID);
7954}
7955
7956uint32_t ASTReader::GetNumExternalSelectors() {
7957 // ID 0 (the null selector) is considered an external selector.
7958 return getTotalNumSelectors() + 1;
7959}
7960
7961serialization::SelectorID
7962ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7963 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7964 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007965
Guy Benyei11169dd2012-12-18 14:30:41 +00007966 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7967 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007968 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007970
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 return LocalID + I->second;
7972}
7973
7974DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007975ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007976 const RecordData &Record, unsigned &Idx) {
7977 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7978 switch (Kind) {
7979 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007980 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007981
7982 case DeclarationName::ObjCZeroArgSelector:
7983 case DeclarationName::ObjCOneArgSelector:
7984 case DeclarationName::ObjCMultiArgSelector:
7985 return DeclarationName(ReadSelector(F, Record, Idx));
7986
7987 case DeclarationName::CXXConstructorName:
7988 return Context.DeclarationNames.getCXXConstructorName(
7989 Context.getCanonicalType(readType(F, Record, Idx)));
7990
7991 case DeclarationName::CXXDestructorName:
7992 return Context.DeclarationNames.getCXXDestructorName(
7993 Context.getCanonicalType(readType(F, Record, Idx)));
7994
7995 case DeclarationName::CXXConversionFunctionName:
7996 return Context.DeclarationNames.getCXXConversionFunctionName(
7997 Context.getCanonicalType(readType(F, Record, Idx)));
7998
7999 case DeclarationName::CXXOperatorName:
8000 return Context.DeclarationNames.getCXXOperatorName(
8001 (OverloadedOperatorKind)Record[Idx++]);
8002
8003 case DeclarationName::CXXLiteralOperatorName:
8004 return Context.DeclarationNames.getCXXLiteralOperatorName(
8005 GetIdentifierInfo(F, Record, Idx));
8006
8007 case DeclarationName::CXXUsingDirective:
8008 return DeclarationName::getUsingDirectiveName();
8009 }
8010
8011 llvm_unreachable("Invalid NameKind!");
8012}
8013
8014void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8015 DeclarationNameLoc &DNLoc,
8016 DeclarationName Name,
8017 const RecordData &Record, unsigned &Idx) {
8018 switch (Name.getNameKind()) {
8019 case DeclarationName::CXXConstructorName:
8020 case DeclarationName::CXXDestructorName:
8021 case DeclarationName::CXXConversionFunctionName:
8022 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8023 break;
8024
8025 case DeclarationName::CXXOperatorName:
8026 DNLoc.CXXOperatorName.BeginOpNameLoc
8027 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8028 DNLoc.CXXOperatorName.EndOpNameLoc
8029 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8030 break;
8031
8032 case DeclarationName::CXXLiteralOperatorName:
8033 DNLoc.CXXLiteralOperatorName.OpNameLoc
8034 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8035 break;
8036
8037 case DeclarationName::Identifier:
8038 case DeclarationName::ObjCZeroArgSelector:
8039 case DeclarationName::ObjCOneArgSelector:
8040 case DeclarationName::ObjCMultiArgSelector:
8041 case DeclarationName::CXXUsingDirective:
8042 break;
8043 }
8044}
8045
8046void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8047 DeclarationNameInfo &NameInfo,
8048 const RecordData &Record, unsigned &Idx) {
8049 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8050 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8051 DeclarationNameLoc DNLoc;
8052 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8053 NameInfo.setInfo(DNLoc);
8054}
8055
8056void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8057 const RecordData &Record, unsigned &Idx) {
8058 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8059 unsigned NumTPLists = Record[Idx++];
8060 Info.NumTemplParamLists = NumTPLists;
8061 if (NumTPLists) {
8062 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008063 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008064 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8065 }
8066}
8067
8068TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008069ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008070 unsigned &Idx) {
8071 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8072 switch (Kind) {
8073 case TemplateName::Template:
8074 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8075
8076 case TemplateName::OverloadedTemplate: {
8077 unsigned size = Record[Idx++];
8078 UnresolvedSet<8> Decls;
8079 while (size--)
8080 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8081
8082 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8083 }
8084
8085 case TemplateName::QualifiedTemplate: {
8086 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8087 bool hasTemplKeyword = Record[Idx++];
8088 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8089 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8090 }
8091
8092 case TemplateName::DependentTemplate: {
8093 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8094 if (Record[Idx++]) // isIdentifier
8095 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008096 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008097 Idx));
8098 return Context.getDependentTemplateName(NNS,
8099 (OverloadedOperatorKind)Record[Idx++]);
8100 }
8101
8102 case TemplateName::SubstTemplateTemplateParm: {
8103 TemplateTemplateParmDecl *param
8104 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8105 if (!param) return TemplateName();
8106 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8107 return Context.getSubstTemplateTemplateParm(param, replacement);
8108 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008109
Guy Benyei11169dd2012-12-18 14:30:41 +00008110 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008111 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008112 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8113 if (!Param)
8114 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008115
Guy Benyei11169dd2012-12-18 14:30:41 +00008116 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8117 if (ArgPack.getKind() != TemplateArgument::Pack)
8118 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008119
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8121 }
8122 }
8123
8124 llvm_unreachable("Unhandled template name kind!");
8125}
8126
Richard Smith2bb3c342015-08-09 01:05:31 +00008127TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8128 const RecordData &Record,
8129 unsigned &Idx,
8130 bool Canonicalize) {
8131 if (Canonicalize) {
8132 // The caller wants a canonical template argument. Sometimes the AST only
8133 // wants template arguments in canonical form (particularly as the template
8134 // argument lists of template specializations) so ensure we preserve that
8135 // canonical form across serialization.
8136 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8137 return Context.getCanonicalTemplateArgument(Arg);
8138 }
8139
Guy Benyei11169dd2012-12-18 14:30:41 +00008140 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8141 switch (Kind) {
8142 case TemplateArgument::Null:
8143 return TemplateArgument();
8144 case TemplateArgument::Type:
8145 return TemplateArgument(readType(F, Record, Idx));
8146 case TemplateArgument::Declaration: {
8147 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008148 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008149 }
8150 case TemplateArgument::NullPtr:
8151 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8152 case TemplateArgument::Integral: {
8153 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8154 QualType T = readType(F, Record, Idx);
8155 return TemplateArgument(Context, Value, T);
8156 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008157 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008158 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8159 case TemplateArgument::TemplateExpansion: {
8160 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008161 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 if (unsigned NumExpansions = Record[Idx++])
8163 NumTemplateExpansions = NumExpansions - 1;
8164 return TemplateArgument(Name, NumTemplateExpansions);
8165 }
8166 case TemplateArgument::Expression:
8167 return TemplateArgument(ReadExpr(F));
8168 case TemplateArgument::Pack: {
8169 unsigned NumArgs = Record[Idx++];
8170 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8171 for (unsigned I = 0; I != NumArgs; ++I)
8172 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008173 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 }
8175 }
8176
8177 llvm_unreachable("Unhandled template argument kind!");
8178}
8179
8180TemplateParameterList *
8181ASTReader::ReadTemplateParameterList(ModuleFile &F,
8182 const RecordData &Record, unsigned &Idx) {
8183 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8184 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8185 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8186
8187 unsigned NumParams = Record[Idx++];
8188 SmallVector<NamedDecl *, 16> Params;
8189 Params.reserve(NumParams);
8190 while (NumParams--)
8191 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8192
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008193 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008194 TemplateParameterList* TemplateParams =
8195 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008196 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008197 return TemplateParams;
8198}
8199
8200void
8201ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008202ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008203 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008204 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 unsigned NumTemplateArgs = Record[Idx++];
8206 TemplArgs.reserve(NumTemplateArgs);
8207 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008208 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008209}
8210
8211/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008212void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 const RecordData &Record, unsigned &Idx) {
8214 unsigned NumDecls = Record[Idx++];
8215 Set.reserve(Context, NumDecls);
8216 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008217 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008218 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008219 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008220 }
8221}
8222
8223CXXBaseSpecifier
8224ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8225 const RecordData &Record, unsigned &Idx) {
8226 bool isVirtual = static_cast<bool>(Record[Idx++]);
8227 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8228 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8229 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8230 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8231 SourceRange Range = ReadSourceRange(F, Record, Idx);
8232 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008233 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008234 EllipsisLoc);
8235 Result.setInheritConstructors(inheritConstructors);
8236 return Result;
8237}
8238
Richard Smithc2bb8182015-03-24 06:36:48 +00008239CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008240ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8241 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008243 assert(NumInitializers && "wrote ctor initializers but have no inits");
8244 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8245 for (unsigned i = 0; i != NumInitializers; ++i) {
8246 TypeSourceInfo *TInfo = nullptr;
8247 bool IsBaseVirtual = false;
8248 FieldDecl *Member = nullptr;
8249 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008250
Richard Smithc2bb8182015-03-24 06:36:48 +00008251 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8252 switch (Type) {
8253 case CTOR_INITIALIZER_BASE:
8254 TInfo = GetTypeSourceInfo(F, Record, Idx);
8255 IsBaseVirtual = Record[Idx++];
8256 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008257
Richard Smithc2bb8182015-03-24 06:36:48 +00008258 case CTOR_INITIALIZER_DELEGATING:
8259 TInfo = GetTypeSourceInfo(F, Record, Idx);
8260 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008261
Richard Smithc2bb8182015-03-24 06:36:48 +00008262 case CTOR_INITIALIZER_MEMBER:
8263 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8264 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008265
Richard Smithc2bb8182015-03-24 06:36:48 +00008266 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8267 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8268 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008269 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008270
8271 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8272 Expr *Init = ReadExpr(F);
8273 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8274 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008275
8276 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008277 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008278 BOMInit = new (Context)
8279 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8280 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008281 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008282 BOMInit = new (Context)
8283 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008284 else if (Member)
8285 BOMInit = new (Context)
8286 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8287 Init, RParenLoc);
8288 else
8289 BOMInit = new (Context)
8290 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8291 LParenLoc, Init, RParenLoc);
8292
Richard Smith418ed822016-12-14 19:45:03 +00008293 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008294 unsigned SourceOrder = Record[Idx++];
8295 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008296 }
8297
Richard Smithc2bb8182015-03-24 06:36:48 +00008298 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 }
8300
Richard Smithc2bb8182015-03-24 06:36:48 +00008301 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008302}
8303
8304NestedNameSpecifier *
8305ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8306 const RecordData &Record, unsigned &Idx) {
8307 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008308 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008309 for (unsigned I = 0; I != N; ++I) {
8310 NestedNameSpecifier::SpecifierKind Kind
8311 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8312 switch (Kind) {
8313 case NestedNameSpecifier::Identifier: {
8314 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8315 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8316 break;
8317 }
8318
8319 case NestedNameSpecifier::Namespace: {
8320 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8321 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8322 break;
8323 }
8324
8325 case NestedNameSpecifier::NamespaceAlias: {
8326 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8327 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8328 break;
8329 }
8330
8331 case NestedNameSpecifier::TypeSpec:
8332 case NestedNameSpecifier::TypeSpecWithTemplate: {
8333 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8334 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008335 return nullptr;
8336
Guy Benyei11169dd2012-12-18 14:30:41 +00008337 bool Template = Record[Idx++];
8338 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8339 break;
8340 }
8341
8342 case NestedNameSpecifier::Global: {
8343 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8344 // No associated value, and there can't be a prefix.
8345 break;
8346 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008347
8348 case NestedNameSpecifier::Super: {
8349 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8350 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8351 break;
8352 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008353 }
8354 Prev = NNS;
8355 }
8356 return NNS;
8357}
8358
8359NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008360ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008361 unsigned &Idx) {
8362 unsigned N = Record[Idx++];
8363 NestedNameSpecifierLocBuilder Builder;
8364 for (unsigned I = 0; I != N; ++I) {
8365 NestedNameSpecifier::SpecifierKind Kind
8366 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8367 switch (Kind) {
8368 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008369 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 SourceRange Range = ReadSourceRange(F, Record, Idx);
8371 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8372 break;
8373 }
8374
8375 case NestedNameSpecifier::Namespace: {
8376 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8377 SourceRange Range = ReadSourceRange(F, Record, Idx);
8378 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8379 break;
8380 }
8381
8382 case NestedNameSpecifier::NamespaceAlias: {
8383 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8384 SourceRange Range = ReadSourceRange(F, Record, Idx);
8385 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8386 break;
8387 }
8388
8389 case NestedNameSpecifier::TypeSpec:
8390 case NestedNameSpecifier::TypeSpecWithTemplate: {
8391 bool Template = Record[Idx++];
8392 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8393 if (!T)
8394 return NestedNameSpecifierLoc();
8395 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8396
8397 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008398 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008399 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8400 T->getTypeLoc(), ColonColonLoc);
8401 break;
8402 }
8403
8404 case NestedNameSpecifier::Global: {
8405 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8406 Builder.MakeGlobal(Context, ColonColonLoc);
8407 break;
8408 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008409
8410 case NestedNameSpecifier::Super: {
8411 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8412 SourceRange Range = ReadSourceRange(F, Record, Idx);
8413 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8414 break;
8415 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008416 }
8417 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008418
Guy Benyei11169dd2012-12-18 14:30:41 +00008419 return Builder.getWithLocInContext(Context);
8420}
8421
8422SourceRange
8423ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8424 unsigned &Idx) {
8425 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8426 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8427 return SourceRange(beg, end);
8428}
8429
8430/// \brief Read an integral value
8431llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8432 unsigned BitWidth = Record[Idx++];
8433 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8434 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8435 Idx += NumWords;
8436 return Result;
8437}
8438
8439/// \brief Read a signed integral value
8440llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8441 bool isUnsigned = Record[Idx++];
8442 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8443}
8444
8445/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008446llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8447 const llvm::fltSemantics &Sem,
8448 unsigned &Idx) {
8449 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008450}
8451
8452// \brief Read a string
8453std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8454 unsigned Len = Record[Idx++];
8455 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8456 Idx += Len;
8457 return Result;
8458}
8459
Richard Smith7ed1bc92014-12-05 22:42:13 +00008460std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8461 unsigned &Idx) {
8462 std::string Filename = ReadString(Record, Idx);
8463 ResolveImportedPath(F, Filename);
8464 return Filename;
8465}
8466
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008467VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008468 unsigned &Idx) {
8469 unsigned Major = Record[Idx++];
8470 unsigned Minor = Record[Idx++];
8471 unsigned Subminor = Record[Idx++];
8472 if (Minor == 0)
8473 return VersionTuple(Major);
8474 if (Subminor == 0)
8475 return VersionTuple(Major, Minor - 1);
8476 return VersionTuple(Major, Minor - 1, Subminor - 1);
8477}
8478
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008479CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008480 const RecordData &Record,
8481 unsigned &Idx) {
8482 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8483 return CXXTemporary::Create(Context, Decl);
8484}
8485
8486DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008487 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008488}
8489
8490DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8491 return Diags.Report(Loc, DiagID);
8492}
8493
8494/// \brief Retrieve the identifier table associated with the
8495/// preprocessor.
8496IdentifierTable &ASTReader::getIdentifierTable() {
8497 return PP.getIdentifierTable();
8498}
8499
8500/// \brief Record that the given ID maps to the given switch-case
8501/// statement.
8502void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008503 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008504 "Already have a SwitchCase with this ID");
8505 (*CurrSwitchCaseStmts)[ID] = SC;
8506}
8507
8508/// \brief Retrieve the switch-case statement with the given ID.
8509SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008510 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008511 return (*CurrSwitchCaseStmts)[ID];
8512}
8513
8514void ASTReader::ClearSwitchCaseIDs() {
8515 CurrSwitchCaseStmts->clear();
8516}
8517
8518void ASTReader::ReadComments() {
8519 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008520 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008521 serialization::ModuleFile *> >::iterator
8522 I = CommentsCursors.begin(),
8523 E = CommentsCursors.end();
8524 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008525 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008526 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008527 serialization::ModuleFile &F = *I->second;
8528 SavedStreamPosition SavedPosition(Cursor);
8529
8530 RecordData Record;
8531 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008532 llvm::BitstreamEntry Entry =
8533 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008534
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008535 switch (Entry.Kind) {
8536 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8537 case llvm::BitstreamEntry::Error:
8538 Error("malformed block record in AST file");
8539 return;
8540 case llvm::BitstreamEntry::EndBlock:
8541 goto NextCursor;
8542 case llvm::BitstreamEntry::Record:
8543 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008544 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008545 }
8546
8547 // Read a record.
8548 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008549 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008550 case COMMENTS_RAW_COMMENT: {
8551 unsigned Idx = 0;
8552 SourceRange SR = ReadSourceRange(F, Record, Idx);
8553 RawComment::CommentKind Kind =
8554 (RawComment::CommentKind) Record[Idx++];
8555 bool IsTrailingComment = Record[Idx++];
8556 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008557 Comments.push_back(new (Context) RawComment(
8558 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8559 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008560 break;
8561 }
8562 }
8563 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008564 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008565 // De-serialized SourceLocations get negative FileIDs for other modules,
8566 // potentially invalidating the original order. Sort it again.
8567 std::sort(Comments.begin(), Comments.end(),
8568 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008569 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008570 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008571}
8572
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008573void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8574 bool IncludeSystem, bool Complain,
8575 llvm::function_ref<void(const serialization::InputFile &IF,
8576 bool isSystem)> Visitor) {
8577 unsigned NumUserInputs = MF.NumUserInputFiles;
8578 unsigned NumInputs = MF.InputFilesLoaded.size();
8579 assert(NumUserInputs <= NumInputs);
8580 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8581 for (unsigned I = 0; I < N; ++I) {
8582 bool IsSystem = I >= NumUserInputs;
8583 InputFile IF = getInputFile(MF, I+1, Complain);
8584 Visitor(IF, IsSystem);
8585 }
8586}
8587
Richard Smithcd45dbc2014-04-19 03:48:30 +00008588std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8589 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008590 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008591 return M->getFullModuleName();
8592
8593 // Otherwise, use the name of the top-level module the decl is within.
8594 if (ModuleFile *M = getOwningModuleFile(D))
8595 return M->ModuleName;
8596
8597 // Not from a module.
8598 return "";
8599}
8600
Guy Benyei11169dd2012-12-18 14:30:41 +00008601void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008602 while (!PendingIdentifierInfos.empty() ||
8603 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008604 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008605 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008606 // If any identifiers with corresponding top-level declarations have
8607 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008608 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8609 TopLevelDeclsMap;
8610 TopLevelDeclsMap TopLevelDecls;
8611
Guy Benyei11169dd2012-12-18 14:30:41 +00008612 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008613 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008614 SmallVector<uint32_t, 4> DeclIDs =
8615 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008616 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008617
8618 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008619 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008620
Richard Smith851072e2014-05-19 20:59:20 +00008621 // For each decl chain that we wanted to complete while deserializing, mark
8622 // it as "still needs to be completed".
8623 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8624 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8625 }
8626 PendingIncompleteDeclChains.clear();
8627
Guy Benyei11169dd2012-12-18 14:30:41 +00008628 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008629 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008630 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008631 PendingDeclChains.clear();
8632
Douglas Gregor6168bd22013-02-18 15:53:43 +00008633 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008634 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8635 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008636 IdentifierInfo *II = TLD->first;
8637 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008638 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008639 }
8640 }
8641
Guy Benyei11169dd2012-12-18 14:30:41 +00008642 // Load any pending macro definitions.
8643 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008644 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8645 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8646 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8647 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008648 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008649 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008650 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008651 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008652 resolvePendingMacro(II, Info);
8653 }
8654 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008655 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008656 ++IDIdx) {
8657 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008658 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008659 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008660 }
8661 }
8662 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008663
8664 // Wire up the DeclContexts for Decls that we delayed setting until
8665 // recursive loading is completed.
8666 while (!PendingDeclContextInfos.empty()) {
8667 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8668 PendingDeclContextInfos.pop_front();
8669 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8670 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8671 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8672 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008673
Richard Smithd1c46742014-04-30 02:24:17 +00008674 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008675 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008676 auto Update = PendingUpdateRecords.pop_back_val();
8677 ReadingKindTracker ReadingKind(Read_Decl, *this);
8678 loadDeclUpdateRecords(Update.first, Update.second);
8679 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008680 }
Richard Smith8a639892015-01-24 01:07:20 +00008681
8682 // At this point, all update records for loaded decls are in place, so any
8683 // fake class definitions should have become real.
8684 assert(PendingFakeDefinitionData.empty() &&
8685 "faked up a class definition but never saw the real one");
8686
Guy Benyei11169dd2012-12-18 14:30:41 +00008687 // If we deserialized any C++ or Objective-C class definitions, any
8688 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008689 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008690 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008691 for (Decl *D : PendingDefinitions) {
8692 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008693 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008694 // Make sure that the TagType points at the definition.
8695 const_cast<TagType*>(TagT)->decl = TD;
8696 }
Richard Smith8ce51082015-03-11 01:44:51 +00008697
Craig Topperc6914d02014-08-25 04:15:02 +00008698 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008699 for (auto *R = getMostRecentExistingDecl(RD); R;
8700 R = R->getPreviousDecl()) {
8701 assert((R == D) ==
8702 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008703 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008704 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008705 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008706 }
8707
8708 continue;
8709 }
Richard Smith8ce51082015-03-11 01:44:51 +00008710
Craig Topperc6914d02014-08-25 04:15:02 +00008711 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008712 // Make sure that the ObjCInterfaceType points at the definition.
8713 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8714 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008715
8716 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8717 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8718
Guy Benyei11169dd2012-12-18 14:30:41 +00008719 continue;
8720 }
Richard Smith8ce51082015-03-11 01:44:51 +00008721
Craig Topperc6914d02014-08-25 04:15:02 +00008722 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008723 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8724 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8725
Guy Benyei11169dd2012-12-18 14:30:41 +00008726 continue;
8727 }
Richard Smith8ce51082015-03-11 01:44:51 +00008728
Craig Topperc6914d02014-08-25 04:15:02 +00008729 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008730 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8731 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008732 }
8733 PendingDefinitions.clear();
8734
8735 // Load the bodies of any functions or methods we've encountered. We do
8736 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008737 // have been fully wired up (hasBody relies on this).
8738 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008739 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8740 PBEnd = PendingBodies.end();
8741 PB != PBEnd; ++PB) {
8742 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8743 // FIXME: Check for =delete/=default?
8744 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008745 const FunctionDecl *Defn = nullptr;
8746 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008747 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008748 else
Richard Smith6561f922016-09-12 21:06:40 +00008749 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008750 continue;
8751 }
8752
8753 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8754 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8755 MD->setLazyBody(PB->second);
8756 }
8757 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008758
8759 // Do some cleanup.
8760 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8761 getContext().deduplicateMergedDefinitonsFor(ND);
8762 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008763}
8764
8765void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008766 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8767 return;
8768
Richard Smitha0ce9c42014-07-29 23:23:27 +00008769 // Trigger the import of the full definition of each class that had any
8770 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008771 // These updates may in turn find and diagnose some ODR failures, so take
8772 // ownership of the set first.
8773 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8774 PendingOdrMergeFailures.clear();
8775 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008776 Merge.first->buildLookup();
8777 Merge.first->decls_begin();
8778 Merge.first->bases_begin();
8779 Merge.first->vbases_begin();
8780 for (auto *RD : Merge.second) {
8781 RD->decls_begin();
8782 RD->bases_begin();
8783 RD->vbases_begin();
8784 }
8785 }
8786
8787 // For each declaration from a merged context, check that the canonical
8788 // definition of that context also contains a declaration of the same
8789 // entity.
8790 //
8791 // Caution: this loop does things that might invalidate iterators into
8792 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8793 while (!PendingOdrMergeChecks.empty()) {
8794 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8795
8796 // FIXME: Skip over implicit declarations for now. This matters for things
8797 // like implicitly-declared special member functions. This isn't entirely
8798 // correct; we can end up with multiple unmerged declarations of the same
8799 // implicit entity.
8800 if (D->isImplicit())
8801 continue;
8802
8803 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008804
8805 bool Found = false;
8806 const Decl *DCanon = D->getCanonicalDecl();
8807
Richard Smith01bdb7a2014-08-28 05:44:07 +00008808 for (auto RI : D->redecls()) {
8809 if (RI->getLexicalDeclContext() == CanonDef) {
8810 Found = true;
8811 break;
8812 }
8813 }
8814 if (Found)
8815 continue;
8816
Richard Smith0f4e2c42015-08-06 04:23:48 +00008817 // Quick check failed, time to do the slow thing. Note, we can't just
8818 // look up the name of D in CanonDef here, because the member that is
8819 // in CanonDef might not be found by name lookup (it might have been
8820 // replaced by a more recent declaration in the lookup table), and we
8821 // can't necessarily find it in the redeclaration chain because it might
8822 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008823 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008824 for (auto *CanonMember : CanonDef->decls()) {
8825 if (CanonMember->getCanonicalDecl() == DCanon) {
8826 // This can happen if the declaration is merely mergeable and not
8827 // actually redeclarable (we looked for redeclarations earlier).
8828 //
8829 // FIXME: We should be able to detect this more efficiently, without
8830 // pulling in all of the members of CanonDef.
8831 Found = true;
8832 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008833 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008834 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8835 if (ND->getDeclName() == D->getDeclName())
8836 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008837 }
8838
8839 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008840 // The AST doesn't like TagDecls becoming invalid after they've been
8841 // completed. We only really need to mark FieldDecls as invalid here.
8842 if (!isa<TagDecl>(D))
8843 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008844
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008845 // Ensure we don't accidentally recursively enter deserialization while
8846 // we're producing our diagnostic.
8847 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008848
8849 std::string CanonDefModule =
8850 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8851 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8852 << D << getOwningModuleNameForDiagnostic(D)
8853 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8854
8855 if (Candidates.empty())
8856 Diag(cast<Decl>(CanonDef)->getLocation(),
8857 diag::note_module_odr_violation_no_possible_decls) << D;
8858 else {
8859 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8860 Diag(Candidates[I]->getLocation(),
8861 diag::note_module_odr_violation_possible_decl)
8862 << Candidates[I];
8863 }
8864
8865 DiagnosedOdrMergeFailures.insert(CanonDef);
8866 }
8867 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008868
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008869 if (OdrMergeFailures.empty())
8870 return;
8871
8872 // Ensure we don't accidentally recursively enter deserialization while
8873 // we're producing our diagnostics.
8874 Deserializing RecursionGuard(this);
8875
Richard Smithcd45dbc2014-04-19 03:48:30 +00008876 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008877 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008878 // If we've already pointed out a specific problem with this class, don't
8879 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008880 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008881 continue;
8882
8883 bool Diagnosed = false;
8884 for (auto *RD : Merge.second) {
8885 // Multiple different declarations got merged together; tell the user
8886 // where they came from.
Sam McCall61e29aa2017-01-31 08:24:40 +00008887 if (Merge.first != RD) {
8888 // FIXME: Walk the definition, figure out what's different,
8889 // and diagnose that.
8890 if (!Diagnosed) {
8891 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8892 Diag(Merge.first->getLocation(),
8893 diag::err_module_odr_violation_different_definitions)
Richard Trieufa3d93a2017-01-31 01:44:15 +00008894 << Merge.first << Module.empty() << Module;
Sam McCall61e29aa2017-01-31 08:24:40 +00008895 Diagnosed = true;
8896 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008897
8898 Diag(RD->getLocation(),
8899 diag::note_module_odr_violation_different_definitions)
Sam McCall61e29aa2017-01-31 08:24:40 +00008900 << getOwningModuleNameForDiagnostic(RD);
Richard Smithcd45dbc2014-04-19 03:48:30 +00008901 }
8902 }
8903
8904 if (!Diagnosed) {
8905 // All definitions are updates to the same declaration. This happens if a
8906 // module instantiates the declaration of a class template specialization
8907 // and two or more other modules instantiate its definition.
8908 //
8909 // FIXME: Indicate which modules had instantiations of this definition.
8910 // FIXME: How can this even happen?
8911 Diag(Merge.first->getLocation(),
8912 diag::err_module_odr_violation_different_instantiations)
8913 << Merge.first;
8914 }
8915 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008916}
8917
Richard Smithce18a182015-07-14 00:26:00 +00008918void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008919 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00008920 ReadTimer->startTimer();
8921}
8922
Guy Benyei11169dd2012-12-18 14:30:41 +00008923void ASTReader::FinishedDeserializing() {
8924 assert(NumCurrentElementsDeserializing &&
8925 "FinishedDeserializing not paired with StartedDeserializing");
8926 if (NumCurrentElementsDeserializing == 1) {
8927 // We decrease NumCurrentElementsDeserializing only after pending actions
8928 // are finished, to avoid recursively re-calling finishPendingActions().
8929 finishPendingActions();
8930 }
8931 --NumCurrentElementsDeserializing;
8932
Richard Smitha0ce9c42014-07-29 23:23:27 +00008933 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008934 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008935 while (!PendingExceptionSpecUpdates.empty()) {
8936 auto Updates = std::move(PendingExceptionSpecUpdates);
8937 PendingExceptionSpecUpdates.clear();
8938 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008939 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008940 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008941 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008942 if (auto *Listener = Context.getASTMutationListener())
8943 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008944 for (auto *Redecl : Update.second->redecls())
8945 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008946 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008947 }
8948
Richard Smithce18a182015-07-14 00:26:00 +00008949 if (ReadTimer)
8950 ReadTimer->stopTimer();
8951
Richard Smith0f4e2c42015-08-06 04:23:48 +00008952 diagnoseOdrViolations();
8953
Richard Smith04d05b52014-03-23 00:27:18 +00008954 // We are not in recursive loading, so it's safe to pass the "interesting"
8955 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008956 if (Consumer)
8957 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008958 }
8959}
8960
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008961void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008962 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8963 // Remove any fake results before adding any real ones.
8964 auto It = PendingFakeLookupResults.find(II);
8965 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008966 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008967 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008968 // FIXME: this works around module+PCH performance issue.
8969 // Rather than erase the result from the map, which is O(n), just clear
8970 // the vector of NamedDecls.
8971 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008972 }
8973 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008974
8975 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8976 SemaObj->TUScope->AddDecl(D);
8977 } else if (SemaObj->TUScope) {
8978 // Adding the decl to IdResolver may have failed because it was already in
8979 // (even though it was not added in scope). If it is already in, make sure
8980 // it gets in the scope as well.
8981 if (std::find(SemaObj->IdResolver.begin(Name),
8982 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8983 SemaObj->TUScope->AddDecl(D);
8984 }
8985}
8986
David Blaikie61137e12017-01-05 18:23:18 +00008987ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8988 const PCHContainerReader &PCHContainerRdr,
8989 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
8990 StringRef isysroot, bool DisableValidation,
8991 bool AllowASTWithCompilerErrors,
8992 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
8993 bool UseGlobalIndex,
8994 std::unique_ptr<llvm::Timer> ReadTimer)
8995 : Listener(DisableValidation
8996 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
8997 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00008998 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00008999 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9000 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9001 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009002 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009003 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9004 AllowConfigurationMismatch(AllowConfigurationMismatch),
9005 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009006 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009007 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009008
9009 for (const auto &Ext : Extensions) {
9010 auto BlockName = Ext->getExtensionMetadata().BlockName;
9011 auto Known = ModuleFileExtensions.find(BlockName);
9012 if (Known != ModuleFileExtensions.end()) {
9013 Diags.Report(diag::warn_duplicate_module_file_extension)
9014 << BlockName;
9015 continue;
9016 }
9017
9018 ModuleFileExtensions.insert({BlockName, Ext});
9019 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009020}
9021
9022ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009023 if (OwnsDeserializationListener)
9024 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009025}
Richard Smith10379092016-05-06 23:14:07 +00009026
9027IdentifierResolver &ASTReader::getIdResolver() {
9028 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9029}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009030
9031unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9032 unsigned AbbrevID) {
9033 Idx = 0;
9034 Record.clear();
9035 return Cursor.readRecord(AbbrevID, Record);
9036}