blob: 67c7e46099738e8f2190c81de8830d9bf99ca8fb [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;
Richard Smith35845152017-02-07 01:37:30 +0000947 case DeclarationName::CXXDeductionGuideName:
948 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
949 ->getDeclName().getAsIdentifierInfo();
950 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000951 case DeclarationName::CXXConstructorName:
952 case DeclarationName::CXXDestructorName:
953 case DeclarationName::CXXConversionFunctionName:
954 case DeclarationName::CXXUsingDirective:
955 Data = 0;
956 break;
957 }
958}
959
960unsigned DeclarationNameKey::getHash() const {
961 llvm::FoldingSetNodeID ID;
962 ID.AddInteger(Kind);
963
964 switch (Kind) {
965 case DeclarationName::Identifier:
966 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +0000967 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000968 ID.AddString(((IdentifierInfo*)Data)->getName());
969 break;
970 case DeclarationName::ObjCZeroArgSelector:
971 case DeclarationName::ObjCOneArgSelector:
972 case DeclarationName::ObjCMultiArgSelector:
973 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
974 break;
975 case DeclarationName::CXXOperatorName:
976 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +0000977 break;
978 case DeclarationName::CXXConstructorName:
979 case DeclarationName::CXXDestructorName:
980 case DeclarationName::CXXConversionFunctionName:
981 case DeclarationName::CXXUsingDirective:
982 break;
983 }
984
985 return ID.ComputeHash();
986}
987
Richard Smithd88a7f12015-09-01 20:35:42 +0000988ModuleFile *
989ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
990 using namespace llvm::support;
991 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
992 return Reader.getLocalModuleFile(F, ModuleFileID);
993}
994
Guy Benyei11169dd2012-12-18 14:30:41 +0000995std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +0000996ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000997 using namespace llvm::support;
998 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
999 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 return std::make_pair(KeyLen, DataLen);
1001}
1002
Richard Smitha06c7e62015-08-26 23:55:49 +00001003ASTDeclContextNameLookupTrait::internal_key_type
1004ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001005 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001006
Richard Smitha06c7e62015-08-26 23:55:49 +00001007 auto Kind = (DeclarationName::NameKind)*d++;
1008 uint64_t Data;
1009 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001011 case DeclarationName::CXXLiteralOperatorName:
1012 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001013 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001014 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 break;
1016 case DeclarationName::ObjCZeroArgSelector:
1017 case DeclarationName::ObjCOneArgSelector:
1018 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001019 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001020 (uint64_t)Reader.getLocalSelector(
1021 F, endian::readNext<uint32_t, little, unaligned>(
1022 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 break;
1024 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001025 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001026 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001027 case DeclarationName::CXXConstructorName:
1028 case DeclarationName::CXXDestructorName:
1029 case DeclarationName::CXXConversionFunctionName:
1030 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001031 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001032 break;
1033 }
1034
Richard Smitha06c7e62015-08-26 23:55:49 +00001035 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001036}
1037
Richard Smithd88a7f12015-09-01 20:35:42 +00001038void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1039 const unsigned char *d,
1040 unsigned DataLen,
1041 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001042 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001043 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1044 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1045 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1046 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001047}
1048
Richard Smith0f4e2c42015-08-06 04:23:48 +00001049bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1050 BitstreamCursor &Cursor,
1051 uint64_t Offset,
1052 DeclContext *DC) {
1053 assert(Offset != 0);
1054
Guy Benyei11169dd2012-12-18 14:30:41 +00001055 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001056 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001057
Richard Smith0f4e2c42015-08-06 04:23:48 +00001058 RecordData Record;
1059 StringRef Blob;
1060 unsigned Code = Cursor.ReadCode();
1061 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1062 if (RecCode != DECL_CONTEXT_LEXICAL) {
1063 Error("Expected lexical block");
1064 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 }
1066
Richard Smith82f8fcd2015-08-06 22:07:25 +00001067 assert(!isa<TranslationUnitDecl>(DC) &&
1068 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001069 // If we are handling a C++ class template instantiation, we can see multiple
1070 // lexical updates for the same record. It's important that we select only one
1071 // of them, so that field numbering works properly. Just pick the first one we
1072 // see.
1073 auto &Lex = LexicalDecls[DC];
1074 if (!Lex.first) {
1075 Lex = std::make_pair(
1076 &M, llvm::makeArrayRef(
1077 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1078 Blob.data()),
1079 Blob.size() / 4));
1080 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001081 DC->setHasExternalLexicalStorage(true);
1082 return false;
1083}
Guy Benyei11169dd2012-12-18 14:30:41 +00001084
Richard Smith0f4e2c42015-08-06 04:23:48 +00001085bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1086 BitstreamCursor &Cursor,
1087 uint64_t Offset,
1088 DeclID ID) {
1089 assert(Offset != 0);
1090
1091 SavedStreamPosition SavedPosition(Cursor);
1092 Cursor.JumpToBit(Offset);
1093
1094 RecordData Record;
1095 StringRef Blob;
1096 unsigned Code = Cursor.ReadCode();
1097 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1098 if (RecCode != DECL_CONTEXT_VISIBLE) {
1099 Error("Expected visible lookup table block");
1100 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 }
1102
Richard Smith0f4e2c42015-08-06 04:23:48 +00001103 // We can't safely determine the primary context yet, so delay attaching the
1104 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001105 auto *Data = (const unsigned char*)Blob.data();
1106 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 return false;
1108}
1109
1110void ASTReader::Error(StringRef Msg) {
1111 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001112 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1113 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001114 Diag(diag::note_module_cache_path)
1115 << PP.getHeaderSearchInfo().getModuleCachePath();
1116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001117}
1118
1119void ASTReader::Error(unsigned DiagID,
1120 StringRef Arg1, StringRef Arg2) {
1121 if (Diags.isDiagnosticInFlight())
1122 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1123 else
1124 Diag(DiagID) << Arg1 << Arg2;
1125}
1126
1127//===----------------------------------------------------------------------===//
1128// Source Manager Deserialization
1129//===----------------------------------------------------------------------===//
1130
1131/// \brief Read the line table in the source manager block.
1132/// \returns true if there was an error.
1133bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001134 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 unsigned Idx = 0;
1136 LineTableInfo &LineTable = SourceMgr.getLineTable();
1137
1138 // Parse the file names
1139 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001140 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001141 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001142 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001143 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1144 }
Richard Smith63078492015-09-01 07:41:55 +00001145 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001146
1147 // Parse the line entries
1148 std::vector<LineEntry> Entries;
1149 while (Idx < Record.size()) {
1150 int FID = Record[Idx++];
1151 assert(FID >= 0 && "Serialized line entries for non-local file.");
1152 // Remap FileID from 1-based old view.
1153 FID += F.SLocEntryBaseID - 1;
1154
1155 // Extract the line entries
1156 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001157 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 Entries.clear();
1159 Entries.reserve(NumEntries);
1160 for (unsigned I = 0; I != NumEntries; ++I) {
1161 unsigned FileOffset = Record[Idx++];
1162 unsigned LineNo = Record[Idx++];
1163 int FilenameID = FileIDs[Record[Idx++]];
1164 SrcMgr::CharacteristicKind FileKind
1165 = (SrcMgr::CharacteristicKind)Record[Idx++];
1166 unsigned IncludeOffset = Record[Idx++];
1167 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1168 FileKind, IncludeOffset));
1169 }
1170 LineTable.AddEntry(FileID::get(FID), Entries);
1171 }
1172
1173 return false;
1174}
1175
1176/// \brief Read a source manager block
1177bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1178 using namespace SrcMgr;
1179
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001180 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001181
1182 // Set the source-location entry cursor to the current position in
1183 // the stream. This cursor will be used to read the contents of the
1184 // source manager block initially, and then lazily read
1185 // source-location entries as needed.
1186 SLocEntryCursor = F.Stream;
1187
1188 // The stream itself is going to skip over the source manager block.
1189 if (F.Stream.SkipBlock()) {
1190 Error("malformed block record in AST file");
1191 return true;
1192 }
1193
1194 // Enter the source manager block.
1195 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1196 Error("malformed source manager block record in AST file");
1197 return true;
1198 }
1199
1200 RecordData Record;
1201 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001202 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001203
Chris Lattnere7b154b2013-01-19 21:39:22 +00001204 switch (E.Kind) {
1205 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1206 case llvm::BitstreamEntry::Error:
1207 Error("malformed block record in AST file");
1208 return true;
1209 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001211 case llvm::BitstreamEntry::Record:
1212 // The interesting case.
1213 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001215
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001218 StringRef Blob;
1219 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001220 default: // Default behavior: ignore.
1221 break;
1222
1223 case SM_SLOC_FILE_ENTRY:
1224 case SM_SLOC_BUFFER_ENTRY:
1225 case SM_SLOC_EXPANSION_ENTRY:
1226 // Once we hit one of the source location entries, we're done.
1227 return false;
1228 }
1229 }
1230}
1231
1232/// \brief If a header file is not found at the path that we expect it to be
1233/// and the PCH file was moved from its original location, try to resolve the
1234/// file by assuming that header+PCH were moved together and the header is in
1235/// the same place relative to the PCH.
1236static std::string
1237resolveFileRelativeToOriginalDir(const std::string &Filename,
1238 const std::string &OriginalDir,
1239 const std::string &CurrDir) {
1240 assert(OriginalDir != CurrDir &&
1241 "No point trying to resolve the file if the PCH dir didn't change");
1242 using namespace llvm::sys;
1243 SmallString<128> filePath(Filename);
1244 fs::make_absolute(filePath);
1245 assert(path::is_absolute(OriginalDir));
1246 SmallString<128> currPCHPath(CurrDir);
1247
1248 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1249 fileDirE = path::end(path::parent_path(filePath));
1250 path::const_iterator origDirI = path::begin(OriginalDir),
1251 origDirE = path::end(OriginalDir);
1252 // Skip the common path components from filePath and OriginalDir.
1253 while (fileDirI != fileDirE && origDirI != origDirE &&
1254 *fileDirI == *origDirI) {
1255 ++fileDirI;
1256 ++origDirI;
1257 }
1258 for (; origDirI != origDirE; ++origDirI)
1259 path::append(currPCHPath, "..");
1260 path::append(currPCHPath, fileDirI, fileDirE);
1261 path::append(currPCHPath, path::filename(Filename));
1262 return currPCHPath.str();
1263}
1264
1265bool ASTReader::ReadSLocEntry(int ID) {
1266 if (ID == 0)
1267 return false;
1268
1269 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1270 Error("source location entry ID out-of-range for AST file");
1271 return true;
1272 }
1273
Richard Smithaada85c2016-02-06 02:06:43 +00001274 // Local helper to read the (possibly-compressed) buffer data following the
1275 // entry record.
1276 auto ReadBuffer = [this](
1277 BitstreamCursor &SLocEntryCursor,
1278 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1279 RecordData Record;
1280 StringRef Blob;
1281 unsigned Code = SLocEntryCursor.ReadCode();
1282 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1283
1284 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001285 if (!llvm::zlib::isAvailable()) {
1286 Error("zlib is not available");
1287 return nullptr;
1288 }
Richard Smithaada85c2016-02-06 02:06:43 +00001289 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001290 if (llvm::Error E =
1291 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1292 Error("could not decompress embedded file contents: " +
1293 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001294 return nullptr;
1295 }
1296 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1297 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1298 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1299 } else {
1300 Error("AST record has invalid code");
1301 return nullptr;
1302 }
1303 };
1304
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1306 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001307 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001308 unsigned BaseOffset = F->SLocEntryBaseOffset;
1309
1310 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001311 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1312 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 Error("incorrectly-formatted source location entry in AST file");
1314 return true;
1315 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001318 StringRef Blob;
1319 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001320 default:
1321 Error("incorrectly-formatted source location entry in AST file");
1322 return true;
1323
1324 case SM_SLOC_FILE_ENTRY: {
1325 // We will detect whether a file changed and return 'Failure' for it, but
1326 // we will also try to fail gracefully by setting up the SLocEntry.
1327 unsigned InputID = Record[4];
1328 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001329 const FileEntry *File = IF.getFile();
1330 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001331
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001332 // Note that we only check if a File was returned. If it was out-of-date
1333 // we have complained but we will continue creating a FileID to recover
1334 // gracefully.
1335 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001336 return true;
1337
1338 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1339 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1340 // This is the module's main file.
1341 IncludeLoc = getImportLocation(F);
1342 }
1343 SrcMgr::CharacteristicKind
1344 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1345 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1346 ID, BaseOffset + Record[0]);
1347 SrcMgr::FileInfo &FileInfo =
1348 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1349 FileInfo.NumCreatedFIDs = Record[5];
1350 if (Record[3])
1351 FileInfo.setHasLineDirectives();
1352
1353 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1354 unsigned NumFileDecls = Record[7];
1355 if (NumFileDecls) {
1356 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1357 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1358 NumFileDecls));
1359 }
Richard Smithaada85c2016-02-06 02:06:43 +00001360
Guy Benyei11169dd2012-12-18 14:30:41 +00001361 const SrcMgr::ContentCache *ContentCache
1362 = SourceMgr.getOrCreateContentCache(File,
1363 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1364 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001365 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1366 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001367 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1368 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001369 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001370 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001371 }
1372
1373 break;
1374 }
1375
1376 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001377 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001378 unsigned Offset = Record[0];
1379 SrcMgr::CharacteristicKind
1380 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1381 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001382 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001383 IncludeLoc = getImportLocation(F);
1384 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001385
Richard Smithaada85c2016-02-06 02:06:43 +00001386 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1387 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001389 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001390 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 break;
1392 }
1393
1394 case SM_SLOC_EXPANSION_ENTRY: {
1395 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1396 SourceMgr.createExpansionLoc(SpellingLoc,
1397 ReadSourceLocation(*F, Record[2]),
1398 ReadSourceLocation(*F, Record[3]),
1399 Record[4],
1400 ID,
1401 BaseOffset + Record[0]);
1402 break;
1403 }
1404 }
1405
1406 return false;
1407}
1408
1409std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1410 if (ID == 0)
1411 return std::make_pair(SourceLocation(), "");
1412
1413 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1414 Error("source location entry ID out-of-range for AST file");
1415 return std::make_pair(SourceLocation(), "");
1416 }
1417
1418 // Find which module file this entry lands in.
1419 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001420 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 return std::make_pair(SourceLocation(), "");
1422
1423 // FIXME: Can we map this down to a particular submodule? That would be
1424 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001425 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001426}
1427
1428/// \brief Find the location where the module F is imported.
1429SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1430 if (F->ImportLoc.isValid())
1431 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001432
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 // Otherwise we have a PCH. It's considered to be "imported" at the first
1434 // location of its includer.
1435 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001436 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001437 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001438 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001439 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 return F->ImportedBy[0]->FirstLoc;
1441}
1442
1443/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1444/// specified cursor. Read the abbreviations that are at the top of the block
1445/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001446bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001447 if (Cursor.EnterSubBlock(BlockID))
1448 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001449
1450 while (true) {
1451 uint64_t Offset = Cursor.GetCurrentBitNo();
1452 unsigned Code = Cursor.ReadCode();
1453
1454 // We expect all abbrevs to be at the start of the block.
1455 if (Code != llvm::bitc::DEFINE_ABBREV) {
1456 Cursor.JumpToBit(Offset);
1457 return false;
1458 }
1459 Cursor.ReadAbbrevRecord();
1460 }
1461}
1462
Richard Smithe40f2ba2013-08-07 21:41:30 +00001463Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001464 unsigned &Idx) {
1465 Token Tok;
1466 Tok.startToken();
1467 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1468 Tok.setLength(Record[Idx++]);
1469 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1470 Tok.setIdentifierInfo(II);
1471 Tok.setKind((tok::TokenKind)Record[Idx++]);
1472 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1473 return Tok;
1474}
1475
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001476MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001477 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001478
1479 // Keep track of where we are in the stream, then jump back there
1480 // after reading this macro.
1481 SavedStreamPosition SavedPosition(Stream);
1482
1483 Stream.JumpToBit(Offset);
1484 RecordData Record;
1485 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001486 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001487
Guy Benyei11169dd2012-12-18 14:30:41 +00001488 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001489 // Advance to the next record, but if we get to the end of the block, don't
1490 // pop it (removing all the abbreviations from the cursor) since we want to
1491 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001492 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001493 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001494
Chris Lattnerefa77172013-01-20 00:00:22 +00001495 switch (Entry.Kind) {
1496 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1497 case llvm::BitstreamEntry::Error:
1498 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001499 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001500 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001501 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001502 case llvm::BitstreamEntry::Record:
1503 // The interesting case.
1504 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 }
1506
1507 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 Record.clear();
1509 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001510 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001511 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001512 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001513 case PP_MACRO_DIRECTIVE_HISTORY:
1514 return Macro;
1515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516 case PP_MACRO_OBJECT_LIKE:
1517 case PP_MACRO_FUNCTION_LIKE: {
1518 // If we already have a macro, that means that we've hit the end
1519 // of the definition of the macro we were looking for. We're
1520 // done.
1521 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001522 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001523
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001524 unsigned NextIndex = 1; // Skip identifier ID.
1525 SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001527 MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001528 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001530 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1533 // Decode function-like macro info.
1534 bool isC99VarArgs = Record[NextIndex++];
1535 bool isGNUVarArgs = Record[NextIndex++];
1536 bool hasCommaPasting = Record[NextIndex++];
1537 MacroArgs.clear();
1538 unsigned NumArgs = Record[NextIndex++];
1539 for (unsigned i = 0; i != NumArgs; ++i)
1540 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1541
1542 // Install function-like macro info.
1543 MI->setIsFunctionLike();
1544 if (isC99VarArgs) MI->setIsC99Varargs();
1545 if (isGNUVarArgs) MI->setIsGNUVarargs();
1546 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001547 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 }
1549
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 // Remember that we saw this macro last so that we add the tokens that
1551 // form its body to it.
1552 Macro = MI;
1553
1554 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1555 Record[NextIndex]) {
1556 // We have a macro definition. Register the association
1557 PreprocessedEntityID
1558 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1559 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001560 PreprocessingRecord::PPEntityID PPID =
1561 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1562 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1563 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001564 if (PPDef)
1565 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 }
1567
1568 ++NumMacrosRead;
1569 break;
1570 }
1571
1572 case PP_TOKEN: {
1573 // If we see a TOKEN before a PP_MACRO_*, then the file is
1574 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001575 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001576
John McCallf413f5e2013-05-03 00:10:13 +00001577 unsigned Idx = 0;
1578 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 Macro->AddTokenToBody(Tok);
1580 break;
1581 }
1582 }
1583 }
1584}
1585
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001586PreprocessedEntityID
Guy Benyei11169dd2012-12-18 14:30:41 +00001587ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001588 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001590 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001592
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 return LocalID + I->second;
1594}
1595
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001596unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1597 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001598}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001599
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001600HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001601HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001602 internal_key_type ikey = {FE->getSize(),
1603 M.HasTimestamps ? FE->getModificationTime() : 0,
1604 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001605 return ikey;
1606}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001607
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001608bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001609 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001610 return false;
1611
Mehdi Amini004b9c72016-10-10 22:52:47 +00001612 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001613 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001614
Guy Benyei11169dd2012-12-18 14:30:41 +00001615 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001616 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001617 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1618 if (!Key.Imported)
1619 return FileMgr.getFile(Key.Filename);
1620
1621 std::string Resolved = Key.Filename;
1622 Reader.ResolveImportedPath(M, Resolved);
1623 return FileMgr.getFile(Resolved);
1624 };
1625
1626 const FileEntry *FEA = GetFile(a);
1627 const FileEntry *FEB = GetFile(b);
1628 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001629}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001630
Guy Benyei11169dd2012-12-18 14:30:41 +00001631std::pair<unsigned, unsigned>
1632HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001633 using namespace llvm::support;
1634 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001636 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001637}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001638
1639HeaderFileInfoTrait::internal_key_type
1640HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001641 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001643 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1644 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001645 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001646 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001647 return ikey;
1648}
1649
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001650HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001651HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 unsigned DataLen) {
1653 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001654 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 HeaderFileInfo HFI;
1656 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001657 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1658 HFI.isImport |= (Flags >> 4) & 0x01;
1659 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1660 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001661 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001662 // FIXME: Find a better way to handle this. Maybe just store a
1663 // "has been included" flag?
1664 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1665 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001666 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1667 M, endian::readNext<uint32_t, little, unaligned>(d));
1668 if (unsigned FrameworkOffset =
1669 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001670 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 // since 0 is used as an indicator for "no framework name".
1672 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1673 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1674 }
Richard Smith386bb072015-08-18 23:42:23 +00001675
1676 assert((End - d) % 4 == 0 &&
1677 "Wrong data length in HeaderFileInfo deserialization");
1678 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001679 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001680 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1681 LocalSMID >>= 2;
1682
1683 // This header is part of a module. Associate it with the module to enable
1684 // implicit module import.
1685 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1686 Module *Mod = Reader.getSubmodule(GlobalSMID);
1687 FileManager &FileMgr = Reader.getFileManager();
1688 ModuleMap &ModMap =
1689 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1690
1691 std::string Filename = key.Filename;
1692 if (key.Imported)
1693 Reader.ResolveImportedPath(M, Filename);
1694 // FIXME: This is not always the right filename-as-written, but we're not
1695 // going to use this information to rebuild the module, so it doesn't make
1696 // a lot of difference.
1697 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001698 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1699 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001700 }
1701
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 // This HeaderFileInfo was externally loaded.
1703 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001704 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001705 return HFI;
1706}
1707
Richard Smithd7329392015-04-21 21:46:32 +00001708void ASTReader::addPendingMacro(IdentifierInfo *II,
1709 ModuleFile *M,
1710 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001711 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1712 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001713}
1714
1715void ASTReader::ReadDefinedMacros() {
1716 // Note that we are loading defined macros.
1717 Deserializing Macros(this);
1718
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001719 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1720 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001721
1722 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001723 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001724 continue;
1725
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001726 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001727 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001728
1729 RecordData Record;
1730 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001731 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001732
Chris Lattnere7b154b2013-01-19 21:39:22 +00001733 switch (E.Kind) {
1734 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1735 case llvm::BitstreamEntry::Error:
1736 Error("malformed block record in AST file");
1737 return;
1738 case llvm::BitstreamEntry::EndBlock:
1739 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001740
Chris Lattnere7b154b2013-01-19 21:39:22 +00001741 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001742 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001743 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001744 default: // Default behavior: ignore.
1745 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001746
Chris Lattnere7b154b2013-01-19 21:39:22 +00001747 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001748 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001749 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001750 if (II->isOutOfDate())
1751 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001752 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001753 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001754
Chris Lattnere7b154b2013-01-19 21:39:22 +00001755 case PP_TOKEN:
1756 // Ignore tokens.
1757 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001758 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001759 break;
1760 }
1761 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001762 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763 }
1764}
1765
1766namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001767
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 /// \brief Visitor class used to look up identifirs in an AST file.
1769 class IdentifierLookupVisitor {
1770 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001771 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001773 unsigned &NumIdentifierLookups;
1774 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001775 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001776
Guy Benyei11169dd2012-12-18 14:30:41 +00001777 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001778 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1779 unsigned &NumIdentifierLookups,
1780 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001781 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1782 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001783 NumIdentifierLookups(NumIdentifierLookups),
1784 NumIdentifierLookupHits(NumIdentifierLookupHits),
1785 Found()
1786 {
1787 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001788
1789 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001791 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001793
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 ASTIdentifierLookupTable *IdTable
1795 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1796 if (!IdTable)
1797 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001798
1799 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001800 Found);
1801 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001802 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001803 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 if (Pos == IdTable->end())
1805 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001806
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 // Dereferencing the iterator has the effect of building the
1808 // IdentifierInfo node and populating it with the various
1809 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001810 ++NumIdentifierLookupHits;
1811 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001812 return true;
1813 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001814
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 // \brief Retrieve the identifier info found within the module
1816 // files.
1817 IdentifierInfo *getIdentifierInfo() const { return Found; }
1818 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001819
1820} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001821
1822void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1823 // Note that we are loading an identifier.
1824 Deserializing AnIdentifier(this);
1825
1826 unsigned PriorGeneration = 0;
1827 if (getContext().getLangOpts().Modules)
1828 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001829
1830 // If there is a global index, look there first to determine which modules
1831 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001832 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001833 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001834 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001835 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1836 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001837 }
1838 }
1839
Douglas Gregor7211ac12013-01-25 23:32:03 +00001840 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001841 NumIdentifierLookups,
1842 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001843 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001844 markIdentifierUpToDate(&II);
1845}
1846
1847void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1848 if (!II)
1849 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001850
Guy Benyei11169dd2012-12-18 14:30:41 +00001851 II->setOutOfDate(false);
1852
1853 // Update the generation for this identifier.
1854 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001855 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001856}
1857
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001858void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1859 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001860 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001861
1862 BitstreamCursor &Cursor = M.MacroCursor;
1863 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001864 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001865
Richard Smith713369b2015-04-23 20:40:50 +00001866 struct ModuleMacroRecord {
1867 SubmoduleID SubModID;
1868 MacroInfo *MI;
1869 SmallVector<SubmoduleID, 8> Overrides;
1870 };
1871 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001872
Richard Smithd7329392015-04-21 21:46:32 +00001873 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1874 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1875 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001876 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001877 while (true) {
1878 llvm::BitstreamEntry Entry =
1879 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1880 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1881 Error("malformed block record in AST file");
1882 return;
1883 }
1884
1885 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001886 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001887 case PP_MACRO_DIRECTIVE_HISTORY:
1888 break;
1889
1890 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001891 ModuleMacros.push_back(ModuleMacroRecord());
1892 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001893 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1894 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001895 for (int I = 2, N = Record.size(); I != N; ++I)
1896 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001897 continue;
1898 }
1899
1900 default:
1901 Error("malformed block record in AST file");
1902 return;
1903 }
1904
1905 // We found the macro directive history; that's the last record
1906 // for this macro.
1907 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001908 }
1909
Richard Smithd7329392015-04-21 21:46:32 +00001910 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001911 {
1912 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001913 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001914 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001915 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001916 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001917 Module *Mod = getSubmodule(ModID);
1918 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001919 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001920 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001921 }
1922
1923 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001924 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001925 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001926 }
1927 }
1928
1929 // Don't read the directive history for a module; we don't have anywhere
1930 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001931 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001932 return;
1933
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001934 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001935 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001936 unsigned Idx = 0, N = Record.size();
1937 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001938 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001939 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001940 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1941 switch (K) {
1942 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001943 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001944 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001945 break;
1946 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001947 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001948 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001949 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001950 }
1951 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001952 bool isPublic = Record[Idx++];
1953 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1954 break;
1955 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001956
1957 if (!Latest)
1958 Latest = MD;
1959 if (Earliest)
1960 Earliest->setPrevious(MD);
1961 Earliest = MD;
1962 }
1963
Richard Smithd6e8c0d2015-05-04 19:58:00 +00001964 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00001965 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001966}
1967
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00001968ASTReader::InputFileInfo
1969ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00001970 // Go find this input file.
1971 BitstreamCursor &Cursor = F.InputFilesCursor;
1972 SavedStreamPosition SavedPosition(Cursor);
1973 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
1974
1975 unsigned Code = Cursor.ReadCode();
1976 RecordData Record;
1977 StringRef Blob;
1978
1979 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
1980 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
1981 "invalid record type for input file");
1982 (void)Result;
1983
1984 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00001985 InputFileInfo R;
1986 R.StoredSize = static_cast<off_t>(Record[1]);
1987 R.StoredTime = static_cast<time_t>(Record[2]);
1988 R.Overridden = static_cast<bool>(Record[3]);
1989 R.Transient = static_cast<bool>(Record[4]);
1990 R.Filename = Blob;
1991 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00001992 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00001993}
1994
Manman Renc8c94152016-10-21 23:35:03 +00001995static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001996InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001997 // If this ID is bogus, just return an empty input file.
1998 if (ID == 0 || ID > F.InputFilesLoaded.size())
1999 return InputFile();
2000
2001 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002002 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002003 return F.InputFilesLoaded[ID-1];
2004
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002005 if (F.InputFilesLoaded[ID-1].isNotFound())
2006 return InputFile();
2007
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002009 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002010 SavedStreamPosition SavedPosition(Cursor);
2011 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002012
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002013 InputFileInfo FI = readInputFileInfo(F, ID);
2014 off_t StoredSize = FI.StoredSize;
2015 time_t StoredTime = FI.StoredTime;
2016 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002017 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002018 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002019
Richard Smitha8cfffa2015-11-26 02:04:16 +00002020 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002021
2022 // If we didn't find the file, resolve it relative to the
2023 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002024 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002025 F.OriginalDir != CurrentDir) {
2026 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2027 F.OriginalDir,
2028 CurrentDir);
2029 if (!Resolved.empty())
2030 File = FileMgr.getFile(Resolved);
2031 }
2032
2033 // For an overridden file, create a virtual file with the stored
2034 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002035 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002036 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002037
Craig Toppera13603a2014-05-22 05:54:18 +00002038 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002039 if (Complain) {
2040 std::string ErrorStr = "could not find file '";
2041 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002042 ErrorStr += "' referenced by AST file '";
2043 ErrorStr += F.FileName;
2044 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002045 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002046 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002047 // Record that we didn't find the file.
2048 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2049 return InputFile();
2050 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002051
Ben Langmuir198c1682014-03-07 07:27:49 +00002052 // Check if there was a request to override the contents of the file
2053 // that was part of the precompiled header. Overridding such a file
2054 // can lead to problems when lexing using the source locations from the
2055 // PCH.
2056 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002057 // FIXME: Reject if the overrides are different.
2058 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002059 if (Complain)
2060 Error(diag::err_fe_pch_file_overridden, Filename);
2061 // After emitting the diagnostic, recover by disabling the override so
2062 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002063 //
2064 // FIXME: This recovery is just as broken as the original state; there may
2065 // be another precompiled module that's using the overridden contents, or
2066 // we might be half way through parsing it. Instead, we should treat the
2067 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002068 SM.disableFileContentsOverride(File);
2069 // The FileEntry is a virtual file entry with the size of the contents
2070 // that would override the original contents. Set it to the original's
2071 // size/time.
2072 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2073 StoredSize, StoredTime);
2074 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002075
Ben Langmuir198c1682014-03-07 07:27:49 +00002076 bool IsOutOfDate = false;
2077
2078 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002079 if (!Overridden && //
2080 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002081 (StoredTime && StoredTime != File->getModificationTime() &&
2082 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002083 )) {
2084 if (Complain) {
2085 // Build a list of the PCH imports that got us here (in reverse).
2086 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2087 while (ImportStack.back()->ImportedBy.size() > 0)
2088 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002089
Ben Langmuir198c1682014-03-07 07:27:49 +00002090 // The top-level PCH is stale.
2091 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002092 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2093 if (DiagnosticKind == 0)
2094 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2095 else if (DiagnosticKind == 1)
2096 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2097 else
2098 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002099
Ben Langmuir198c1682014-03-07 07:27:49 +00002100 // Print the import stack.
2101 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2102 Diag(diag::note_pch_required_by)
2103 << Filename << ImportStack[0]->FileName;
2104 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002105 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002106 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002107 }
2108
Ben Langmuir198c1682014-03-07 07:27:49 +00002109 if (!Diags.isDiagnosticInFlight())
2110 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 }
2112
Ben Langmuir198c1682014-03-07 07:27:49 +00002113 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002114 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002115 // FIXME: If the file is overridden and we've already opened it,
2116 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002117
Richard Smitha8cfffa2015-11-26 02:04:16 +00002118 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002119
2120 // Note that we've loaded this input file.
2121 F.InputFilesLoaded[ID-1] = IF;
2122 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002123}
2124
Richard Smith7ed1bc92014-12-05 22:42:13 +00002125/// \brief If we are loading a relocatable PCH or module file, and the filename
2126/// is not an absolute path, add the system or module root to the beginning of
2127/// the file name.
2128void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2129 // Resolve relative to the base directory, if we have one.
2130 if (!M.BaseDirectory.empty())
2131 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002132}
2133
Richard Smith7ed1bc92014-12-05 22:42:13 +00002134void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2136 return;
2137
Richard Smith7ed1bc92014-12-05 22:42:13 +00002138 SmallString<128> Buffer;
2139 llvm::sys::path::append(Buffer, Prefix, Filename);
2140 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002141}
2142
Richard Smith0f99d6a2015-08-09 08:48:41 +00002143static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2144 switch (ARR) {
2145 case ASTReader::Failure: return true;
2146 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2147 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2148 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2149 case ASTReader::ConfigurationMismatch:
2150 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2151 case ASTReader::HadErrors: return true;
2152 case ASTReader::Success: return false;
2153 }
2154
2155 llvm_unreachable("unknown ASTReadResult");
2156}
2157
Richard Smith0516b182015-09-08 19:40:14 +00002158ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2159 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2160 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Manman Ren47a44452016-07-26 17:12:17 +00002161 std::string &SuggestedPredefines, bool ValidateDiagnosticOptions) {
Richard Smith0516b182015-09-08 19:40:14 +00002162 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2163 return Failure;
2164
2165 // Read all of the records in the options block.
2166 RecordData Record;
2167 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002168 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002169 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002170
Richard Smith0516b182015-09-08 19:40:14 +00002171 switch (Entry.Kind) {
2172 case llvm::BitstreamEntry::Error:
2173 case llvm::BitstreamEntry::SubBlock:
2174 return Failure;
2175
2176 case llvm::BitstreamEntry::EndBlock:
2177 return Result;
2178
2179 case llvm::BitstreamEntry::Record:
2180 // The interesting case.
2181 break;
2182 }
2183
2184 // Read and process a record.
2185 Record.clear();
2186 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2187 case LANGUAGE_OPTIONS: {
2188 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2189 if (ParseLanguageOptions(Record, Complain, Listener,
2190 AllowCompatibleConfigurationMismatch))
2191 Result = ConfigurationMismatch;
2192 break;
2193 }
2194
2195 case TARGET_OPTIONS: {
2196 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2197 if (ParseTargetOptions(Record, Complain, Listener,
2198 AllowCompatibleConfigurationMismatch))
2199 Result = ConfigurationMismatch;
2200 break;
2201 }
2202
2203 case DIAGNOSTIC_OPTIONS: {
2204 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Manman Ren47a44452016-07-26 17:12:17 +00002205 if (ValidateDiagnosticOptions &&
2206 !AllowCompatibleConfigurationMismatch &&
Richard Smith0516b182015-09-08 19:40:14 +00002207 ParseDiagnosticOptions(Record, Complain, Listener))
2208 return OutOfDate;
2209 break;
2210 }
2211
2212 case FILE_SYSTEM_OPTIONS: {
2213 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2214 if (!AllowCompatibleConfigurationMismatch &&
2215 ParseFileSystemOptions(Record, Complain, Listener))
2216 Result = ConfigurationMismatch;
2217 break;
2218 }
2219
2220 case HEADER_SEARCH_OPTIONS: {
2221 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2222 if (!AllowCompatibleConfigurationMismatch &&
2223 ParseHeaderSearchOptions(Record, Complain, Listener))
2224 Result = ConfigurationMismatch;
2225 break;
2226 }
2227
2228 case PREPROCESSOR_OPTIONS:
2229 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2230 if (!AllowCompatibleConfigurationMismatch &&
2231 ParsePreprocessorOptions(Record, Complain, Listener,
2232 SuggestedPredefines))
2233 Result = ConfigurationMismatch;
2234 break;
2235 }
2236 }
2237}
2238
Guy Benyei11169dd2012-12-18 14:30:41 +00002239ASTReader::ASTReadResult
2240ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002241 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002242 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002243 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002244 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002245 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002246
2247 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2248 Error("malformed block record in AST file");
2249 return Failure;
2250 }
2251
2252 // Read all of the records and blocks in the control block.
2253 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002254 unsigned NumInputs = 0;
2255 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002256 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002257 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002258
Chris Lattnere7b154b2013-01-19 21:39:22 +00002259 switch (Entry.Kind) {
2260 case llvm::BitstreamEntry::Error:
2261 Error("malformed block record in AST file");
2262 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002263 case llvm::BitstreamEntry::EndBlock: {
2264 // Validate input files.
2265 const HeaderSearchOptions &HSOpts =
2266 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002267
Richard Smitha1825302014-10-23 22:18:29 +00002268 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002269 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2270 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002271 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2272 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002273 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002274
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002275 // If we are reading a module, we will create a verification timestamp,
2276 // so we verify all input files. Otherwise, verify only user input
2277 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002278
2279 unsigned N = NumUserInputs;
2280 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002281 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002282 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002283 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002284 N = NumInputs;
2285
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002286 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002287 InputFile IF = getInputFile(F, I+1, Complain);
2288 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002290 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002291 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002292
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002293 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002294 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002295
Ben Langmuircb69b572014-03-07 06:40:32 +00002296 if (Listener && Listener->needsInputFileVisitation()) {
2297 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2298 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002299 for (unsigned I = 0; I < N; ++I) {
2300 bool IsSystem = I >= NumUserInputs;
2301 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002302 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002303 F.Kind == MK_ExplicitModule ||
2304 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002305 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002306 }
2307
Richard Smith8a308ec2015-11-05 00:54:55 +00002308 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002309 }
2310
Chris Lattnere7b154b2013-01-19 21:39:22 +00002311 case llvm::BitstreamEntry::SubBlock:
2312 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002313 case INPUT_FILES_BLOCK_ID:
2314 F.InputFilesCursor = Stream;
2315 if (Stream.SkipBlock() || // Skip with the main cursor
2316 // Read the abbreviations
2317 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2318 Error("malformed block record in AST file");
2319 return Failure;
2320 }
2321 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002322
2323 case OPTIONS_BLOCK_ID:
2324 // If we're reading the first module for this group, check its options
2325 // are compatible with ours. For modules it imports, no further checking
2326 // is required, because we checked them when we built it.
2327 if (Listener && !ImportedBy) {
2328 // Should we allow the configuration of the module file to differ from
2329 // the configuration of the current translation unit in a compatible
2330 // way?
2331 //
2332 // FIXME: Allow this for files explicitly specified with -include-pch.
2333 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002334 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Manman Ren47a44452016-07-26 17:12:17 +00002335 const HeaderSearchOptions &HSOpts =
2336 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Richard Smith0516b182015-09-08 19:40:14 +00002337
Richard Smith8a308ec2015-11-05 00:54:55 +00002338 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2339 AllowCompatibleConfigurationMismatch,
Manman Ren47a44452016-07-26 17:12:17 +00002340 *Listener, SuggestedPredefines,
2341 HSOpts.ModulesValidateDiagnosticOptions);
Richard Smith0516b182015-09-08 19:40:14 +00002342 if (Result == Failure) {
2343 Error("malformed block record in AST file");
2344 return Result;
2345 }
2346
Richard Smith8a308ec2015-11-05 00:54:55 +00002347 if (DisableValidation ||
2348 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2349 Result = Success;
2350
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002351 // If we can't load the module, exit early since we likely
2352 // will rebuild the module anyway. The stream may be in the
2353 // middle of a block.
2354 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002355 return Result;
2356 } else if (Stream.SkipBlock()) {
2357 Error("malformed block record in AST file");
2358 return Failure;
2359 }
2360 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002361
Guy Benyei11169dd2012-12-18 14:30:41 +00002362 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002363 if (Stream.SkipBlock()) {
2364 Error("malformed block record in AST file");
2365 return Failure;
2366 }
2367 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002369
Chris Lattnere7b154b2013-01-19 21:39:22 +00002370 case llvm::BitstreamEntry::Record:
2371 // The interesting case.
2372 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002373 }
2374
2375 // Read and process a record.
2376 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002377 StringRef Blob;
2378 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002379 case METADATA: {
2380 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2381 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002382 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2383 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002384 return VersionMismatch;
2385 }
2386
Richard Smithe75ee0f2015-08-17 07:13:32 +00002387 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002388 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2389 Diag(diag::err_pch_with_compiler_errors);
2390 return HadErrors;
2391 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002392 if (hasErrors) {
2393 Diags.ErrorOccurred = true;
2394 Diags.UncompilableErrorOccurred = true;
2395 Diags.UnrecoverableErrorOccurred = true;
2396 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002397
2398 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002399 // Relative paths in a relocatable PCH are relative to our sysroot.
2400 if (F.RelocatablePCH)
2401 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002402
Richard Smithe75ee0f2015-08-17 07:13:32 +00002403 F.HasTimestamps = Record[5];
2404
Guy Benyei11169dd2012-12-18 14:30:41 +00002405 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002406 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002407 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2408 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002409 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002410 return VersionMismatch;
2411 }
2412 break;
2413 }
2414
Ben Langmuir487ea142014-10-23 18:05:36 +00002415 case SIGNATURE:
2416 assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
2417 F.Signature = Record[0];
2418 break;
2419
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 case IMPORTS: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002421 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 unsigned Idx = 0, N = Record.size();
2423 while (Idx < N) {
2424 // Read information about the AST file.
2425 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2426 // The import location will be the local one for now; we will adjust
2427 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002428 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002430 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002431 off_t StoredSize = (off_t)Record[Idx++];
2432 time_t StoredModTime = (time_t)Record[Idx++];
Ben Langmuir487ea142014-10-23 18:05:36 +00002433 ASTFileSignature StoredSignature = Record[Idx++];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002434 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002435
Richard Smith0f99d6a2015-08-09 08:48:41 +00002436 // If our client can't cope with us being out of date, we can't cope with
2437 // our dependency being missing.
2438 unsigned Capabilities = ClientLoadCapabilities;
2439 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2440 Capabilities &= ~ARR_Missing;
2441
Guy Benyei11169dd2012-12-18 14:30:41 +00002442 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002443 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2444 Loaded, StoredSize, StoredModTime,
2445 StoredSignature, Capabilities);
2446
2447 // If we diagnosed a problem, produce a backtrace.
2448 if (isDiagnosedResult(Result, Capabilities))
2449 Diag(diag::note_module_file_imported_by)
2450 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2451
2452 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002453 case Failure: return Failure;
2454 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002455 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002456 case OutOfDate: return OutOfDate;
2457 case VersionMismatch: return VersionMismatch;
2458 case ConfigurationMismatch: return ConfigurationMismatch;
2459 case HadErrors: return HadErrors;
2460 case Success: break;
2461 }
2462 }
2463 break;
2464 }
2465
Guy Benyei11169dd2012-12-18 14:30:41 +00002466 case ORIGINAL_FILE:
2467 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002468 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002470 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002471 break;
2472
2473 case ORIGINAL_FILE_ID:
2474 F.OriginalSourceFileID = FileID::get(Record[0]);
2475 break;
2476
2477 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002478 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002479 break;
2480
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002481 case MODULE_NAME:
2482 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002483 if (Listener)
2484 Listener->ReadModuleName(F.ModuleName);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002485 break;
2486
Richard Smith223d3f22014-12-06 03:21:08 +00002487 case MODULE_DIRECTORY: {
2488 assert(!F.ModuleName.empty() &&
2489 "MODULE_DIRECTORY found before MODULE_NAME");
2490 // If we've already loaded a module map file covering this module, we may
2491 // have a better path for it (relative to the current build).
2492 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2493 if (M && M->Directory) {
2494 // If we're implicitly loading a module, the base directory can't
2495 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002496 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002497 const DirectoryEntry *BuildDir =
2498 PP.getFileManager().getDirectory(Blob);
2499 if (!BuildDir || BuildDir != M->Directory) {
2500 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2501 Diag(diag::err_imported_module_relocated)
2502 << F.ModuleName << Blob << M->Directory->getName();
2503 return OutOfDate;
2504 }
2505 }
2506 F.BaseDirectory = M->Directory->getName();
2507 } else {
2508 F.BaseDirectory = Blob;
2509 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002510 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002511 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002512
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002513 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002514 if (ASTReadResult Result =
2515 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2516 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002517 break;
2518
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002519 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002520 NumInputs = Record[0];
2521 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002522 F.InputFileOffsets =
2523 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002524 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002525 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 break;
2527 }
2528 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002529}
2530
Ben Langmuir2c9af442014-04-10 17:57:43 +00002531ASTReader::ASTReadResult
2532ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002533 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002534
2535 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2536 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002537 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002538 }
2539
2540 // Read all of the records and blocks for the AST file.
2541 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002542 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002543 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002544
Chris Lattnere7b154b2013-01-19 21:39:22 +00002545 switch (Entry.Kind) {
2546 case llvm::BitstreamEntry::Error:
2547 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002548 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002549 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002550 // Outside of C++, we do not store a lookup map for the translation unit.
2551 // Instead, mark it as needing a lookup map to be built if this module
2552 // contains any declarations lexically within it (which it always does!).
2553 // This usually has no cost, since we very rarely need the lookup map for
2554 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002555 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002556 if (DC->hasExternalLexicalStorage() &&
2557 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002558 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002559
Ben Langmuir2c9af442014-04-10 17:57:43 +00002560 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002562 case llvm::BitstreamEntry::SubBlock:
2563 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002564 case DECLTYPES_BLOCK_ID:
2565 // We lazily load the decls block, but we want to set up the
2566 // DeclsCursor cursor to point into it. Clone our current bitcode
2567 // cursor to it, enter the block and read the abbrevs in that block.
2568 // With the main cursor, we just skip over it.
2569 F.DeclsCursor = Stream;
2570 if (Stream.SkipBlock() || // Skip with the main cursor.
2571 // Read the abbrevs.
2572 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2573 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002574 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002575 }
2576 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002577
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 case PREPROCESSOR_BLOCK_ID:
2579 F.MacroCursor = Stream;
2580 if (!PP.getExternalSource())
2581 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002582
Guy Benyei11169dd2012-12-18 14:30:41 +00002583 if (Stream.SkipBlock() ||
2584 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2585 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002586 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 }
2588 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2589 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002590
Guy Benyei11169dd2012-12-18 14:30:41 +00002591 case PREPROCESSOR_DETAIL_BLOCK_ID:
2592 F.PreprocessorDetailCursor = Stream;
2593 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002594 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002595 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002596 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002597 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002598 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002599 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002600 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 if (!PP.getPreprocessingRecord())
2603 PP.createPreprocessingRecord();
2604 if (!PP.getPreprocessingRecord()->getExternalSource())
2605 PP.getPreprocessingRecord()->SetExternalSource(*this);
2606 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002607
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 case SOURCE_MANAGER_BLOCK_ID:
2609 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002611 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002612
Guy Benyei11169dd2012-12-18 14:30:41 +00002613 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002614 if (ASTReadResult Result =
2615 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002616 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002618
Guy Benyei11169dd2012-12-18 14:30:41 +00002619 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002620 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002621 if (Stream.SkipBlock() ||
2622 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2623 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002624 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002625 }
2626 CommentsCursors.push_back(std::make_pair(C, &F));
2627 break;
2628 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002629
Guy Benyei11169dd2012-12-18 14:30:41 +00002630 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002631 if (Stream.SkipBlock()) {
2632 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002633 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002634 }
2635 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002636 }
2637 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002638
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639 case llvm::BitstreamEntry::Record:
2640 // The interesting case.
2641 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002642 }
2643
2644 // Read and process a record.
2645 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002646 StringRef Blob;
2647 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002648 default: // Default behavior: ignore.
2649 break;
2650
2651 case TYPE_OFFSET: {
2652 if (F.LocalNumTypes != 0) {
2653 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002654 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002656 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 F.LocalNumTypes = Record[0];
2658 unsigned LocalBaseTypeIndex = Record[1];
2659 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002660
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 if (F.LocalNumTypes > 0) {
2662 // Introduce the global -> local mapping for types within this module.
2663 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002664
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 // Introduce the local -> global mapping for types within this module.
2666 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002667 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002669
2670 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002671 }
2672 break;
2673 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002674
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 case DECL_OFFSET: {
2676 if (F.LocalNumDecls != 0) {
2677 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002678 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002680 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 F.LocalNumDecls = Record[0];
2682 unsigned LocalBaseDeclID = Record[1];
2683 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002684
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002686 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 // module.
2688 GlobalDeclMap.insert(
2689 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002690
Guy Benyei11169dd2012-12-18 14:30:41 +00002691 // Introduce the local -> global mapping for declarations within this
2692 // module.
2693 F.DeclRemap.insertOrReplace(
2694 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 // Introduce the global -> local mapping for declarations within this
2697 // module.
2698 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002699
Ben Langmuir52ca6782014-10-20 16:27:32 +00002700 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2701 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 break;
2703 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002704
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 case TU_UPDATE_LEXICAL: {
2706 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002707 LexicalContents Contents(
2708 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2709 Blob.data()),
2710 static_cast<unsigned int>(Blob.size() / 4));
2711 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 TU->setHasExternalLexicalStorage(true);
2713 break;
2714 }
2715
2716 case UPDATE_VISIBLE: {
2717 unsigned Idx = 0;
2718 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002719 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002720 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002721 // If we've already loaded the decl, perform the updates when we finish
2722 // loading this block.
2723 if (Decl *D = GetExistingDecl(ID))
2724 PendingUpdateRecords.push_back(std::make_pair(ID, D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002725 break;
2726 }
2727
2728 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002729 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002731 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2732 (const unsigned char *)F.IdentifierTableData + Record[0],
2733 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2734 (const unsigned char *)F.IdentifierTableData,
2735 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2738 }
2739 break;
2740
2741 case IDENTIFIER_OFFSET: {
2742 if (F.LocalNumIdentifiers != 0) {
2743 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002744 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002745 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002746 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 F.LocalNumIdentifiers = Record[0];
2748 unsigned LocalBaseIdentifierID = Record[1];
2749 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002750
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 if (F.LocalNumIdentifiers > 0) {
2752 // Introduce the global -> local mapping for identifiers within this
2753 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002754 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002755 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002756
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 // Introduce the local -> global mapping for identifiers within this
2758 // module.
2759 F.IdentifierRemap.insertOrReplace(
2760 std::make_pair(LocalBaseIdentifierID,
2761 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002762
Ben Langmuir52ca6782014-10-20 16:27:32 +00002763 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2764 + F.LocalNumIdentifiers);
2765 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002766 break;
2767 }
2768
Richard Smith33e0f7e2015-07-22 02:08:40 +00002769 case INTERESTING_IDENTIFIERS:
2770 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2771 break;
2772
Ben Langmuir332aafe2014-01-31 01:06:56 +00002773 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002774 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2775 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002777 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 break;
2779
David Blaikie9ffe5a32017-01-30 05:00:26 +00002780 case MODULAR_CODEGEN_DECLS:
2781 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2782 // them (ie: if we're not codegenerating this module).
2783 if (F.Kind == MK_MainFile)
2784 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2785 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2786 break;
2787
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002789 if (SpecialTypes.empty()) {
2790 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2791 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2792 break;
2793 }
2794
2795 if (SpecialTypes.size() != Record.size()) {
2796 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002797 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002798 }
2799
2800 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2801 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2802 if (!SpecialTypes[I])
2803 SpecialTypes[I] = ID;
2804 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2805 // merge step?
2806 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002807 break;
2808
2809 case STATISTICS:
2810 TotalNumStatements += Record[0];
2811 TotalNumMacros += Record[1];
2812 TotalLexicalDeclContexts += Record[2];
2813 TotalVisibleDeclContexts += Record[3];
2814 break;
2815
2816 case UNUSED_FILESCOPED_DECLS:
2817 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2818 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2819 break;
2820
2821 case DELEGATING_CTORS:
2822 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2823 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2824 break;
2825
2826 case WEAK_UNDECLARED_IDENTIFIERS:
2827 if (Record.size() % 4 != 0) {
2828 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002829 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002830 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002831
2832 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002833 // files. This isn't the way to do it :)
2834 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002835
Guy Benyei11169dd2012-12-18 14:30:41 +00002836 // Translate the weak, undeclared identifiers into global IDs.
2837 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2838 WeakUndeclaredIdentifiers.push_back(
2839 getGlobalIdentifierID(F, Record[I++]));
2840 WeakUndeclaredIdentifiers.push_back(
2841 getGlobalIdentifierID(F, Record[I++]));
2842 WeakUndeclaredIdentifiers.push_back(
2843 ReadSourceLocation(F, Record, I).getRawEncoding());
2844 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2845 }
2846 break;
2847
Guy Benyei11169dd2012-12-18 14:30:41 +00002848 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002849 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002850 F.LocalNumSelectors = Record[0];
2851 unsigned LocalBaseSelectorID = Record[1];
2852 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002853
Guy Benyei11169dd2012-12-18 14:30:41 +00002854 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002855 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 // module.
2857 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002858
2859 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 // module.
2861 F.SelectorRemap.insertOrReplace(
2862 std::make_pair(LocalBaseSelectorID,
2863 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002864
2865 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 }
2867 break;
2868 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002869
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002871 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002872 if (Record[0])
2873 F.SelectorLookupTable
2874 = ASTSelectorLookupTable::Create(
2875 F.SelectorLookupTableData + Record[0],
2876 F.SelectorLookupTableData,
2877 ASTSelectorLookupTrait(*this, F));
2878 TotalNumMethodPoolEntries += Record[1];
2879 break;
2880
2881 case REFERENCED_SELECTOR_POOL:
2882 if (!Record.empty()) {
2883 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002884 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 Record[Idx++]));
2886 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2887 getRawEncoding());
2888 }
2889 }
2890 break;
2891
2892 case PP_COUNTER_VALUE:
2893 if (!Record.empty() && Listener)
2894 Listener->ReadCounter(F, Record[0]);
2895 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002896
Guy Benyei11169dd2012-12-18 14:30:41 +00002897 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002898 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 F.NumFileSortedDecls = Record[0];
2900 break;
2901
2902 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002903 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 F.LocalNumSLocEntries = Record[0];
2905 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002906 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002907 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002908 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002909 if (!F.SLocEntryBaseID) {
2910 Error("ran out of source locations");
2911 break;
2912 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 // Make our entry in the range map. BaseID is negative and growing, so
2914 // we invert it. Because we invert it, though, we need the other end of
2915 // the range.
2916 unsigned RangeStart =
2917 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2918 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2919 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2920
2921 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
2922 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
2923 GlobalSLocOffsetMap.insert(
2924 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
2925 - SLocSpaceSize,&F));
2926
2927 // Initialize the remapping table.
2928 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002929 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002930 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00002931 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00002932 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002933
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 TotalNumSLocEntries += F.LocalNumSLocEntries;
2935 break;
2936 }
2937
2938 case MODULE_OFFSET_MAP: {
2939 // Additional remapping information.
Chris Lattner0e6c9402013-01-20 02:38:54 +00002940 const unsigned char *Data = (const unsigned char*)Blob.data();
2941 const unsigned char *DataEnd = Data + Blob.size();
Richard Smithb9eab6d2014-03-20 19:44:17 +00002942
2943 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
2944 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
2945 F.SLocRemap.insert(std::make_pair(0U, 0));
2946 F.SLocRemap.insert(std::make_pair(2U, 1));
2947 }
2948
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 // Continuous range maps we may be updating in our module.
Ben Langmuir785180e2014-10-20 16:27:30 +00002950 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
2951 RemapBuilder;
2952 RemapBuilder SLocRemap(F.SLocRemap);
2953 RemapBuilder IdentifierRemap(F.IdentifierRemap);
2954 RemapBuilder MacroRemap(F.MacroRemap);
2955 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
2956 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
2957 RemapBuilder SelectorRemap(F.SelectorRemap);
2958 RemapBuilder DeclRemap(F.DeclRemap);
2959 RemapBuilder TypeRemap(F.TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00002960
Richard Smithd8879c82015-08-24 21:59:32 +00002961 while (Data < DataEnd) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00002962 using namespace llvm::support;
2963 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 StringRef Name = StringRef((const char*)Data, Len);
2965 Data += Len;
2966 ModuleFile *OM = ModuleMgr.lookup(Name);
2967 if (!OM) {
2968 Error("SourceLocation remap refers to unknown module");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002969 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 }
2971
Justin Bogner57ba0b22014-03-28 22:03:24 +00002972 uint32_t SLocOffset =
2973 endian::readNext<uint32_t, little, unaligned>(Data);
2974 uint32_t IdentifierIDOffset =
2975 endian::readNext<uint32_t, little, unaligned>(Data);
2976 uint32_t MacroIDOffset =
2977 endian::readNext<uint32_t, little, unaligned>(Data);
2978 uint32_t PreprocessedEntityIDOffset =
2979 endian::readNext<uint32_t, little, unaligned>(Data);
2980 uint32_t SubmoduleIDOffset =
2981 endian::readNext<uint32_t, little, unaligned>(Data);
2982 uint32_t SelectorIDOffset =
2983 endian::readNext<uint32_t, little, unaligned>(Data);
2984 uint32_t DeclIDOffset =
2985 endian::readNext<uint32_t, little, unaligned>(Data);
2986 uint32_t TypeIndexOffset =
2987 endian::readNext<uint32_t, little, unaligned>(Data);
2988
Ben Langmuir785180e2014-10-20 16:27:30 +00002989 uint32_t None = std::numeric_limits<uint32_t>::max();
2990
2991 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
2992 RemapBuilder &Remap) {
2993 if (Offset != None)
2994 Remap.insert(std::make_pair(Offset,
2995 static_cast<int>(BaseOffset - Offset)));
2996 };
2997 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
2998 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
2999 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3000 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3001 PreprocessedEntityRemap);
3002 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3003 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3004 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3005 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
Guy Benyei11169dd2012-12-18 14:30:41 +00003006
3007 // Global -> local mappings.
3008 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3009 }
3010 break;
3011 }
3012
3013 case SOURCE_MANAGER_LINE_TABLE:
3014 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003015 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 break;
3017
3018 case SOURCE_LOCATION_PRELOADS: {
3019 // Need to transform from the local view (1-based IDs) to the global view,
3020 // which is based off F.SLocEntryBaseID.
3021 if (!F.PreloadSLocEntries.empty()) {
3022 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003023 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003024 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003025
Guy Benyei11169dd2012-12-18 14:30:41 +00003026 F.PreloadSLocEntries.swap(Record);
3027 break;
3028 }
3029
3030 case EXT_VECTOR_DECLS:
3031 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3032 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3033 break;
3034
3035 case VTABLE_USES:
3036 if (Record.size() % 3 != 0) {
3037 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003038 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003039 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003040
Guy Benyei11169dd2012-12-18 14:30:41 +00003041 // Later tables overwrite earlier ones.
3042 // FIXME: Modules will have some trouble with this. This is clearly not
3043 // the right way to do this.
3044 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003045
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3047 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3048 VTableUses.push_back(
3049 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3050 VTableUses.push_back(Record[Idx++]);
3051 }
3052 break;
3053
Guy Benyei11169dd2012-12-18 14:30:41 +00003054 case PENDING_IMPLICIT_INSTANTIATIONS:
3055 if (PendingInstantiations.size() % 2 != 0) {
3056 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003057 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003058 }
3059
3060 if (Record.size() % 2 != 0) {
3061 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003062 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 }
3064
3065 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3066 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3067 PendingInstantiations.push_back(
3068 ReadSourceLocation(F, Record, I).getRawEncoding());
3069 }
3070 break;
3071
3072 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003073 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003074 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003075 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003076 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003077 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3078 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3079 break;
3080
3081 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003082 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3083 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3084 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003085
3086 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003087
Guy Benyei11169dd2012-12-18 14:30:41 +00003088 unsigned StartingID;
3089 if (!PP.getPreprocessingRecord())
3090 PP.createPreprocessingRecord();
3091 if (!PP.getPreprocessingRecord()->getExternalSource())
3092 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003093 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003095 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003096 F.BasePreprocessedEntityID = StartingID;
3097
3098 if (F.NumPreprocessedEntities > 0) {
3099 // Introduce the global -> local mapping for preprocessed entities in
3100 // this module.
3101 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003102
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 // Introduce the local -> global mapping for preprocessed entities in
3104 // this module.
3105 F.PreprocessedEntityRemap.insertOrReplace(
3106 std::make_pair(LocalBasePreprocessedEntityID,
3107 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3108 }
3109
3110 break;
3111 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003112
Guy Benyei11169dd2012-12-18 14:30:41 +00003113 case DECL_UPDATE_OFFSETS: {
3114 if (Record.size() % 2 != 0) {
3115 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003116 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003117 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003118 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3119 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3120 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3121
3122 // If we've already loaded the decl, perform the updates when we finish
3123 // loading this block.
3124 if (Decl *D = GetExistingDecl(ID))
3125 PendingUpdateRecords.push_back(std::make_pair(ID, D));
3126 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003127 break;
3128 }
3129
Guy Benyei11169dd2012-12-18 14:30:41 +00003130 case OBJC_CATEGORIES_MAP: {
3131 if (F.LocalNumObjCCategoriesInMap != 0) {
3132 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003133 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003137 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 break;
3139 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003140
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 case OBJC_CATEGORIES:
3142 F.ObjCCategories.swap(Record);
3143 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003144
Guy Benyei11169dd2012-12-18 14:30:41 +00003145 case DIAG_PRAGMA_MAPPINGS:
3146 if (F.PragmaDiagMappings.empty())
3147 F.PragmaDiagMappings.swap(Record);
3148 else
3149 F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
3150 Record.begin(), Record.end());
3151 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003152
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 case CUDA_SPECIAL_DECL_REFS:
3154 // Later tables overwrite earlier ones.
3155 // FIXME: Modules will have trouble with this.
3156 CUDASpecialDeclRefs.clear();
3157 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3158 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3159 break;
3160
3161 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003162 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003163 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 if (Record[0]) {
3165 F.HeaderFileInfoTable
3166 = HeaderFileInfoLookupTable::Create(
3167 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3168 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003169 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003170 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003171 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003172
Guy Benyei11169dd2012-12-18 14:30:41 +00003173 PP.getHeaderSearchInfo().SetExternalSource(this);
3174 if (!PP.getHeaderSearchInfo().getExternalLookup())
3175 PP.getHeaderSearchInfo().SetExternalLookup(this);
3176 }
3177 break;
3178 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003179
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 case FP_PRAGMA_OPTIONS:
3181 // Later tables overwrite earlier ones.
3182 FPPragmaOptions.swap(Record);
3183 break;
3184
3185 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003186 for (unsigned I = 0, E = Record.size(); I != E; ) {
3187 auto Name = ReadString(Record, I);
3188 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003189 Opt.Supported = Record[I++] != 0;
3190 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003191 Opt.Avail = Record[I++];
3192 Opt.Core = Record[I++];
3193 }
3194 break;
3195
3196 case OPENCL_EXTENSION_TYPES:
3197 for (unsigned I = 0, E = Record.size(); I != E;) {
3198 auto TypeID = static_cast<::TypeID>(Record[I++]);
3199 auto *Type = GetType(TypeID).getTypePtr();
3200 auto NumExt = static_cast<unsigned>(Record[I++]);
3201 for (unsigned II = 0; II != NumExt; ++II) {
3202 auto Ext = ReadString(Record, I);
3203 OpenCLTypeExtMap[Type].insert(Ext);
3204 }
3205 }
3206 break;
3207
3208 case OPENCL_EXTENSION_DECLS:
3209 for (unsigned I = 0, E = Record.size(); I != E;) {
3210 auto DeclID = static_cast<::DeclID>(Record[I++]);
3211 auto *Decl = GetDecl(DeclID);
3212 auto NumExt = static_cast<unsigned>(Record[I++]);
3213 for (unsigned II = 0; II != NumExt; ++II) {
3214 auto Ext = ReadString(Record, I);
3215 OpenCLDeclExtMap[Decl].insert(Ext);
3216 }
3217 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003218 break;
3219
3220 case TENTATIVE_DEFINITIONS:
3221 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3222 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3223 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003224
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 case KNOWN_NAMESPACES:
3226 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3227 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3228 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003229
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003230 case UNDEFINED_BUT_USED:
3231 if (UndefinedButUsed.size() % 2 != 0) {
3232 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003233 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003234 }
3235
3236 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003237 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003238 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003239 }
3240 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003241 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3242 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003243 ReadSourceLocation(F, Record, I).getRawEncoding());
3244 }
3245 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003246 case DELETE_EXPRS_TO_ANALYZE:
3247 for (unsigned I = 0, N = Record.size(); I != N;) {
3248 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3249 const uint64_t Count = Record[I++];
3250 DelayedDeleteExprs.push_back(Count);
3251 for (uint64_t C = 0; C < Count; ++C) {
3252 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3253 bool IsArrayForm = Record[I++] == 1;
3254 DelayedDeleteExprs.push_back(IsArrayForm);
3255 }
3256 }
3257 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003258
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003260 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003261 // If we aren't loading a module (which has its own exports), make
3262 // all of the imported modules visible.
3263 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003264 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3265 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3266 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003267 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003268 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003269 if (DeserializationListener)
3270 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3271 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 }
3273 }
3274 break;
3275 }
3276
Guy Benyei11169dd2012-12-18 14:30:41 +00003277 case MACRO_OFFSET: {
3278 if (F.LocalNumMacros != 0) {
3279 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003280 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003282 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 F.LocalNumMacros = Record[0];
3284 unsigned LocalBaseMacroID = Record[1];
3285 F.BaseMacroID = getTotalNumMacros();
3286
3287 if (F.LocalNumMacros > 0) {
3288 // Introduce the global -> local mapping for macros within this module.
3289 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3290
3291 // Introduce the local -> global mapping for macros within this module.
3292 F.MacroRemap.insertOrReplace(
3293 std::make_pair(LocalBaseMacroID,
3294 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003295
3296 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003297 }
3298 break;
3299 }
3300
Richard Smithe40f2ba2013-08-07 21:41:30 +00003301 case LATE_PARSED_TEMPLATE: {
3302 LateParsedTemplates.append(Record.begin(), Record.end());
3303 break;
3304 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003305
3306 case OPTIMIZE_PRAGMA_OPTIONS:
3307 if (Record.size() != 1) {
3308 Error("invalid pragma optimize record");
3309 return Failure;
3310 }
3311 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3312 break;
Nico Weber72889432014-09-06 01:25:55 +00003313
Nico Weber779355f2016-03-02 23:22:00 +00003314 case MSSTRUCT_PRAGMA_OPTIONS:
3315 if (Record.size() != 1) {
3316 Error("invalid pragma ms_struct record");
3317 return Failure;
3318 }
3319 PragmaMSStructState = Record[0];
3320 break;
3321
Nico Weber42932312016-03-03 00:17:35 +00003322 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3323 if (Record.size() != 2) {
3324 Error("invalid pragma ms_struct record");
3325 return Failure;
3326 }
3327 PragmaMSPointersToMembersState = Record[0];
3328 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3329 break;
3330
Nico Weber72889432014-09-06 01:25:55 +00003331 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3332 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3333 UnusedLocalTypedefNameCandidates.push_back(
3334 getGlobalDeclID(F, Record[I]));
3335 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003336
3337 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3338 if (Record.size() != 1) {
3339 Error("invalid cuda pragma options record");
3340 return Failure;
3341 }
3342 ForceCUDAHostDeviceDepth = Record[0];
3343 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 }
3345 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003346}
3347
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003348ASTReader::ASTReadResult
3349ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3350 const ModuleFile *ImportedBy,
3351 unsigned ClientLoadCapabilities) {
3352 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003353 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003354
Manman Ren11f2a472016-08-18 17:42:15 +00003355 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003356 // For an explicitly-loaded module, we don't care whether the original
3357 // module map file exists or matches.
3358 return Success;
3359 }
3360
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003361 // Try to resolve ModuleName in the current header search context and
3362 // verify that it is found in the same module map file as we saved. If the
3363 // top-level AST file is a main file, skip this check because there is no
3364 // usable header search context.
3365 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003366 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003367 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003368 // An implicitly-loaded module file should have its module listed in some
3369 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003370 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003371 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3372 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3373 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003374 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003375 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3376 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3377 // This module was defined by an imported (explicit) module.
3378 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3379 << ASTFE->getName();
3380 else
3381 // This module was built with a different module map.
3382 Diag(diag::err_imported_module_not_found)
3383 << F.ModuleName << F.FileName << ImportedBy->FileName
3384 << F.ModuleMapPath;
3385 }
3386 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003387 }
3388
Richard Smithe842a472014-10-22 02:05:46 +00003389 assert(M->Name == F.ModuleName && "found module with different name");
3390
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003391 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003392 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003393 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3394 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003395 assert(ImportedBy && "top-level import should be verified");
3396 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3397 Diag(diag::err_imported_module_modmap_changed)
3398 << F.ModuleName << ImportedBy->FileName
3399 << ModMap->getName() << F.ModuleMapPath;
3400 return OutOfDate;
3401 }
3402
3403 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3404 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3405 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003406 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003407 const FileEntry *F =
3408 FileMgr.getFile(Filename, false, false);
3409 if (F == nullptr) {
3410 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3411 Error("could not find file '" + Filename +"' referenced by AST file");
3412 return OutOfDate;
3413 }
3414 AdditionalStoredMaps.insert(F);
3415 }
3416
3417 // Check any additional module map files (e.g. module.private.modulemap)
3418 // that are not in the pcm.
3419 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3420 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3421 // Remove files that match
3422 // Note: SmallPtrSet::erase is really remove
3423 if (!AdditionalStoredMaps.erase(ModMap)) {
3424 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3425 Diag(diag::err_module_different_modmap)
3426 << F.ModuleName << /*new*/0 << ModMap->getName();
3427 return OutOfDate;
3428 }
3429 }
3430 }
3431
3432 // Check any additional module map files that are in the pcm, but not
3433 // found in header search. Cases that match are already removed.
3434 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3435 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3436 Diag(diag::err_module_different_modmap)
3437 << F.ModuleName << /*not new*/1 << ModMap->getName();
3438 return OutOfDate;
3439 }
3440 }
3441
3442 if (Listener)
3443 Listener->ReadModuleMapFile(F.ModuleMapPath);
3444 return Success;
3445}
3446
3447
Douglas Gregorc1489562013-02-12 23:36:21 +00003448/// \brief Move the given method to the back of the global list of methods.
3449static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3450 // Find the entry for this selector in the method pool.
3451 Sema::GlobalMethodPool::iterator Known
3452 = S.MethodPool.find(Method->getSelector());
3453 if (Known == S.MethodPool.end())
3454 return;
3455
3456 // Retrieve the appropriate method list.
3457 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3458 : Known->second.second;
3459 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003460 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003461 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003462 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003463 Found = true;
3464 } else {
3465 // Keep searching.
3466 continue;
3467 }
3468 }
3469
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003470 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003471 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003472 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003473 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003474 }
3475}
3476
Richard Smithde711422015-04-23 21:20:19 +00003477void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003478 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003479 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003480 bool wasHidden = D->Hidden;
3481 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003482
Richard Smith49f906a2014-03-01 00:08:04 +00003483 if (wasHidden && SemaObj) {
3484 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3485 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003486 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003487 }
3488 }
3489}
3490
Richard Smith49f906a2014-03-01 00:08:04 +00003491void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003492 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003493 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003494 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003495 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003496 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003497 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003498 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003499
3500 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003501 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003502 // there is nothing more to do.
3503 continue;
3504 }
Richard Smith49f906a2014-03-01 00:08:04 +00003505
Guy Benyei11169dd2012-12-18 14:30:41 +00003506 if (!Mod->isAvailable()) {
3507 // Modules that aren't available cannot be made visible.
3508 continue;
3509 }
3510
3511 // Update the module's name visibility.
3512 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003513
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 // If we've already deserialized any names from this module,
3515 // mark them as visible.
3516 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3517 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003518 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003520 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003521 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3522 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003523 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003524
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003526 SmallVector<Module *, 16> Exports;
3527 Mod->getExportedModules(Exports);
3528 for (SmallVectorImpl<Module *>::iterator
3529 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3530 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003531 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003532 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 }
3534 }
3535}
3536
Richard Smith6561f922016-09-12 21:06:40 +00003537/// We've merged the definition \p MergedDef into the existing definition
3538/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3539/// visible.
3540void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3541 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003542 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3543 // in modules other than its owning module. We should instead give the
3544 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003545 if (Def->isHidden()) {
3546 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003547 if (!MergedDef->isHidden())
3548 Def->Hidden = false;
3549 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3550 getContext().mergeDefinitionIntoModule(
3551 Def, MergedDef->getImportedOwningModule(),
3552 /*NotifyListeners*/ false);
3553 PendingMergedDefinitionsToDeduplicate.insert(Def);
3554 } else {
3555 auto SubmoduleID = MergedDef->getOwningModuleID();
3556 assert(SubmoduleID && "hidden definition in no module");
3557 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3558 }
Richard Smith6561f922016-09-12 21:06:40 +00003559 }
3560}
3561
Douglas Gregore060e572013-01-25 01:03:03 +00003562bool ASTReader::loadGlobalIndex() {
3563 if (GlobalIndex)
3564 return false;
3565
3566 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3567 !Context.getLangOpts().Modules)
3568 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003569
Douglas Gregore060e572013-01-25 01:03:03 +00003570 // Try to load the global index.
3571 TriedLoadingGlobalIndex = true;
3572 StringRef ModuleCachePath
3573 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3574 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003575 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003576 if (!Result.first)
3577 return true;
3578
3579 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003580 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003581 return false;
3582}
3583
3584bool ASTReader::isGlobalIndexUnavailable() const {
3585 return Context.getLangOpts().Modules && UseGlobalIndex &&
3586 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3587}
3588
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003589static void updateModuleTimestamp(ModuleFile &MF) {
3590 // Overwrite the timestamp file contents so that file's mtime changes.
3591 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003592 std::error_code EC;
3593 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3594 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003595 return;
3596 OS << "Timestamp file\n";
3597}
3598
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003599/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3600/// cursor into the start of the given block ID, returning false on success and
3601/// true on failure.
3602static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003603 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003604 llvm::BitstreamEntry Entry = Cursor.advance();
3605 switch (Entry.Kind) {
3606 case llvm::BitstreamEntry::Error:
3607 case llvm::BitstreamEntry::EndBlock:
3608 return true;
3609
3610 case llvm::BitstreamEntry::Record:
3611 // Ignore top-level records.
3612 Cursor.skipRecord(Entry.ID);
3613 break;
3614
3615 case llvm::BitstreamEntry::SubBlock:
3616 if (Entry.ID == BlockID) {
3617 if (Cursor.EnterSubBlock(BlockID))
3618 return true;
3619 // Found it!
3620 return false;
3621 }
3622
3623 if (Cursor.SkipBlock())
3624 return true;
3625 }
3626 }
3627}
3628
Benjamin Kramer0772c422016-02-13 13:42:54 +00003629ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 ModuleKind Type,
3631 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003632 unsigned ClientLoadCapabilities,
3633 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003634 llvm::SaveAndRestore<SourceLocation>
3635 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3636
Richard Smithd1c46742014-04-30 02:24:17 +00003637 // Defer any pending actions until we get to the end of reading the AST file.
3638 Deserializing AnASTFile(this);
3639
Guy Benyei11169dd2012-12-18 14:30:41 +00003640 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003641 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003642
3643 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003644 SmallVector<ImportedModule, 4> Loaded;
Guy Benyei11169dd2012-12-18 14:30:41 +00003645 switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
Craig Toppera13603a2014-05-22 05:54:18 +00003646 /*ImportedBy=*/nullptr, Loaded,
Ben Langmuir487ea142014-10-23 18:05:36 +00003647 0, 0, 0,
Guy Benyei11169dd2012-12-18 14:30:41 +00003648 ClientLoadCapabilities)) {
3649 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003650 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 case OutOfDate:
3652 case VersionMismatch:
3653 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003654 case HadErrors: {
3655 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3656 for (const ImportedModule &IM : Loaded)
3657 LoadedSet.insert(IM.Mod);
3658
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003659 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003660 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003661 ? &PP.getHeaderSearchInfo().getModuleMap()
3662 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003663
3664 // If we find that any modules are unusable, the global index is going
3665 // to be out-of-date. Just remove it.
3666 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003667 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003669 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 case Success:
3671 break;
3672 }
3673
3674 // Here comes stuff that we only do once the entire chain is loaded.
3675
3676 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003677 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3678 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 M != MEnd; ++M) {
3680 ModuleFile &F = *M->Mod;
3681
3682 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003683 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3684 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003685
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003686 // Read the extension blocks.
3687 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3688 if (ASTReadResult Result = ReadExtensionBlock(F))
3689 return Result;
3690 }
3691
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003692 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 // bits of all files we've seen.
3694 F.GlobalBitOffset = TotalModulesSizeInBits;
3695 TotalModulesSizeInBits += F.SizeInBits;
3696 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003697
Guy Benyei11169dd2012-12-18 14:30:41 +00003698 // Preload SLocEntries.
3699 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3700 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3701 // Load it through the SourceManager and don't call ReadSLocEntry()
3702 // directly because the entry may have already been loaded in which case
3703 // calling ReadSLocEntry() directly would trigger an assertion in
3704 // SourceManager.
3705 SourceMgr.getLoadedSLocEntryByID(Index);
3706 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003707
3708 // Preload all the pending interesting identifiers by marking them out of
3709 // date.
3710 for (auto Offset : F.PreloadIdentifierOffsets) {
3711 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3712 F.IdentifierTableData + Offset);
3713
3714 ASTIdentifierLookupTrait Trait(*this, F);
3715 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3716 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003717 auto &II = PP.getIdentifierTable().getOwn(Key);
3718 II.setOutOfDate(true);
3719
3720 // Mark this identifier as being from an AST file so that we can track
3721 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003722 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003723
3724 // Associate the ID with the identifier so that the writer can reuse it.
3725 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3726 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003727 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003728 }
3729
Douglas Gregor603cd862013-03-22 18:50:14 +00003730 // Setup the import locations and notify the module manager that we've
3731 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003732 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3733 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003734 M != MEnd; ++M) {
3735 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003736
3737 ModuleMgr.moduleFileAccepted(&F);
3738
3739 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003740 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003741 // FIXME: We assume that locations from PCH / preamble do not need
3742 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003743 if (!M->ImportedBy)
3744 F.ImportLoc = M->ImportLoc;
3745 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003746 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003747 }
3748
Richard Smith33e0f7e2015-07-22 02:08:40 +00003749 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003750 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3751 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003752 // Mark all of the identifiers in the identifier table as being out of date,
3753 // so that various accessors know to check the loaded modules when the
3754 // identifier is used.
3755 //
3756 // For C++ modules, we don't need information on many identifiers (just
3757 // those that provide macros or are poisoned), so we mark all of
3758 // the interesting ones via PreloadIdentifierOffsets.
3759 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3760 IdEnd = PP.getIdentifierTable().end();
3761 Id != IdEnd; ++Id)
3762 Id->second->setOutOfDate(true);
3763 }
Manman Rena0f31a02016-04-29 19:04:05 +00003764 // Mark selectors as out of date.
3765 for (auto Sel : SelectorGeneration)
3766 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003767
Guy Benyei11169dd2012-12-18 14:30:41 +00003768 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003769 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3770 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3772 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003773
3774 switch (Unresolved.Kind) {
3775 case UnresolvedModuleRef::Conflict:
3776 if (ResolvedMod) {
3777 Module::Conflict Conflict;
3778 Conflict.Other = ResolvedMod;
3779 Conflict.Message = Unresolved.String.str();
3780 Unresolved.Mod->Conflicts.push_back(Conflict);
3781 }
3782 continue;
3783
3784 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003785 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003786 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003787 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003788
Douglas Gregorfb912652013-03-20 21:10:35 +00003789 case UnresolvedModuleRef::Export:
3790 if (ResolvedMod || Unresolved.IsWildcard)
3791 Unresolved.Mod->Exports.push_back(
3792 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3793 continue;
3794 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003796 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003797
Graydon Hoaree7196af2016-12-09 21:45:49 +00003798 if (Imported)
3799 Imported->append(ImportedModules.begin(),
3800 ImportedModules.end());
3801
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003802 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3803 // Might be unnecessary as use declarations are only used to build the
3804 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003805
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 InitializeContext();
3807
Richard Smith3d8e97e2013-10-18 06:54:39 +00003808 if (SemaObj)
3809 UpdateSema();
3810
Guy Benyei11169dd2012-12-18 14:30:41 +00003811 if (DeserializationListener)
3812 DeserializationListener->ReaderInitialized(this);
3813
3814 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003815 if (PrimaryModule.OriginalSourceFileID.isValid()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003816 PrimaryModule.OriginalSourceFileID
Guy Benyei11169dd2012-12-18 14:30:41 +00003817 = FileID::get(PrimaryModule.SLocEntryBaseID
3818 + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
3819
3820 // If this AST file is a precompiled preamble, then set the
3821 // preamble file ID of the source manager to the file source file
3822 // from which the preamble was built.
3823 if (Type == MK_Preamble) {
3824 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3825 } else if (Type == MK_MainFile) {
3826 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3827 }
3828 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003829
Guy Benyei11169dd2012-12-18 14:30:41 +00003830 // For any Objective-C class definitions we have already loaded, make sure
3831 // that we load any additional categories.
3832 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003833 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003834 ObjCClassesLoaded[I],
3835 PreviousGeneration);
3836 }
Douglas Gregore060e572013-01-25 01:03:03 +00003837
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003838 if (PP.getHeaderSearchInfo()
3839 .getHeaderSearchOpts()
3840 .ModulesValidateOncePerBuildSession) {
3841 // Now we are certain that the module and all modules it depends on are
3842 // up to date. Create or update timestamp files for modules that are
3843 // located in the module cache (not for PCH files that could be anywhere
3844 // in the filesystem).
3845 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3846 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003847 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003848 updateModuleTimestamp(*M.Mod);
3849 }
3850 }
3851 }
3852
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 return Success;
3854}
3855
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003856static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003857
Ben Langmuir70a1b812015-03-24 04:43:52 +00003858/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3859static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003860 return Stream.canSkipToPos(4) &&
3861 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003862 Stream.Read(8) == 'P' &&
3863 Stream.Read(8) == 'C' &&
3864 Stream.Read(8) == 'H';
3865}
3866
Richard Smith0f99d6a2015-08-09 08:48:41 +00003867static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3868 switch (Kind) {
3869 case MK_PCH:
3870 return 0; // PCH
3871 case MK_ImplicitModule:
3872 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003873 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003874 return 1; // module
3875 case MK_MainFile:
3876 case MK_Preamble:
3877 return 2; // main source file
3878 }
3879 llvm_unreachable("unknown module kind");
3880}
3881
Guy Benyei11169dd2012-12-18 14:30:41 +00003882ASTReader::ASTReadResult
3883ASTReader::ReadASTCore(StringRef FileName,
3884 ModuleKind Type,
3885 SourceLocation ImportLoc,
3886 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003887 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003888 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003889 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 unsigned ClientLoadCapabilities) {
3891 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003893 ModuleManager::AddModuleResult AddResult
3894 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00003895 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003896 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003897 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003898
Douglas Gregor7029ce12013-03-19 00:28:20 +00003899 switch (AddResult) {
3900 case ModuleManager::AlreadyLoaded:
3901 return Success;
3902
3903 case ModuleManager::NewlyLoaded:
3904 // Load module file below.
3905 break;
3906
3907 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00003908 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00003909 // it.
3910 if (ClientLoadCapabilities & ARR_Missing)
3911 return Missing;
3912
3913 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003914 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00003915 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003916 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003917 return Failure;
3918
3919 case ModuleManager::OutOfDate:
3920 // We couldn't load the module file because it is out-of-date. If the
3921 // client can handle out-of-date, return it.
3922 if (ClientLoadCapabilities & ARR_OutOfDate)
3923 return OutOfDate;
3924
3925 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00003926 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00003927 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00003928 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 return Failure;
3930 }
3931
Douglas Gregor7029ce12013-03-19 00:28:20 +00003932 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00003933
3934 // FIXME: This seems rather a hack. Should CurrentDir be part of the
3935 // module?
3936 if (FileName != "-") {
3937 CurrentDir = llvm::sys::path::parent_path(FileName);
3938 if (CurrentDir.empty()) CurrentDir = ".";
3939 }
3940
3941 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00003942 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003943 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00003944 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003945
Guy Benyei11169dd2012-12-18 14:30:41 +00003946 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00003947 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00003948 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
3949 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00003950 return Failure;
3951 }
3952
3953 // This is used for compatibility with older PCH formats.
3954 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003955 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00003956 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003957
Chris Lattnerefa77172013-01-20 00:00:22 +00003958 switch (Entry.Kind) {
3959 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00003960 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003961 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00003962 Error("invalid record at top-level of AST file");
3963 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003964
Chris Lattnerefa77172013-01-20 00:00:22 +00003965 case llvm::BitstreamEntry::SubBlock:
3966 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003967 }
3968
Chris Lattnerefa77172013-01-20 00:00:22 +00003969 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003970 case CONTROL_BLOCK_ID:
3971 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00003972 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003974 // Check that we didn't try to load a non-module AST file as a module.
3975 //
3976 // FIXME: Should we also perform the converse check? Loading a module as
3977 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00003978 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
3979 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00003980 F.ModuleName.empty()) {
3981 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
3982 if (Result != OutOfDate ||
3983 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
3984 Diag(diag::err_module_file_not_module) << FileName;
3985 return Result;
3986 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003987 break;
3988
3989 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00003990 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 case OutOfDate: return OutOfDate;
3992 case VersionMismatch: return VersionMismatch;
3993 case ConfigurationMismatch: return ConfigurationMismatch;
3994 case HadErrors: return HadErrors;
3995 }
3996 break;
Richard Smithf8c32552015-09-02 17:45:54 +00003997
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 case AST_BLOCK_ID:
3999 if (!HaveReadControlBlock) {
4000 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004001 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004002 return VersionMismatch;
4003 }
4004
4005 // Record that we've loaded this module.
4006 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4007 return Success;
4008
4009 default:
4010 if (Stream.SkipBlock()) {
4011 Error("malformed block record in AST file");
4012 return Failure;
4013 }
4014 break;
4015 }
4016 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004017
4018 return Success;
4019}
4020
4021/// Parse a record and blob containing module file extension metadata.
4022static bool parseModuleFileExtensionMetadata(
4023 const SmallVectorImpl<uint64_t> &Record,
4024 StringRef Blob,
4025 ModuleFileExtensionMetadata &Metadata) {
4026 if (Record.size() < 4) return true;
4027
4028 Metadata.MajorVersion = Record[0];
4029 Metadata.MinorVersion = Record[1];
4030
4031 unsigned BlockNameLen = Record[2];
4032 unsigned UserInfoLen = Record[3];
4033
4034 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4035
4036 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4037 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4038 Blob.data() + BlockNameLen + UserInfoLen);
4039 return false;
4040}
4041
4042ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4043 BitstreamCursor &Stream = F.Stream;
4044
4045 RecordData Record;
4046 while (true) {
4047 llvm::BitstreamEntry Entry = Stream.advance();
4048 switch (Entry.Kind) {
4049 case llvm::BitstreamEntry::SubBlock:
4050 if (Stream.SkipBlock())
4051 return Failure;
4052
4053 continue;
4054
4055 case llvm::BitstreamEntry::EndBlock:
4056 return Success;
4057
4058 case llvm::BitstreamEntry::Error:
4059 return HadErrors;
4060
4061 case llvm::BitstreamEntry::Record:
4062 break;
4063 }
4064
4065 Record.clear();
4066 StringRef Blob;
4067 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4068 switch (RecCode) {
4069 case EXTENSION_METADATA: {
4070 ModuleFileExtensionMetadata Metadata;
4071 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4072 return Failure;
4073
4074 // Find a module file extension with this block name.
4075 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4076 if (Known == ModuleFileExtensions.end()) break;
4077
4078 // Form a reader.
4079 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4080 F, Stream)) {
4081 F.ExtensionReaders.push_back(std::move(Reader));
4082 }
4083
4084 break;
4085 }
4086 }
4087 }
4088
4089 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004090}
4091
Richard Smitha7e2cc62015-05-01 01:53:09 +00004092void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004093 // If there's a listener, notify them that we "read" the translation unit.
4094 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004095 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004096 Context.getTranslationUnitDecl());
4097
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 // FIXME: Find a better way to deal with collisions between these
4099 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004100
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 // Load the special types.
4102 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4103 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4104 if (!Context.CFConstantStringTypeDecl)
4105 Context.setCFConstantStringType(GetType(String));
4106 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004107
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4109 QualType FileType = GetType(File);
4110 if (FileType.isNull()) {
4111 Error("FILE type is NULL");
4112 return;
4113 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004114
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 if (!Context.FILEDecl) {
4116 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4117 Context.setFILEDecl(Typedef->getDecl());
4118 else {
4119 const TagType *Tag = FileType->getAs<TagType>();
4120 if (!Tag) {
4121 Error("Invalid FILE type in AST file");
4122 return;
4123 }
4124 Context.setFILEDecl(Tag->getDecl());
4125 }
4126 }
4127 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004128
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4130 QualType Jmp_bufType = GetType(Jmp_buf);
4131 if (Jmp_bufType.isNull()) {
4132 Error("jmp_buf type is NULL");
4133 return;
4134 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004135
Guy Benyei11169dd2012-12-18 14:30:41 +00004136 if (!Context.jmp_bufDecl) {
4137 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4138 Context.setjmp_bufDecl(Typedef->getDecl());
4139 else {
4140 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4141 if (!Tag) {
4142 Error("Invalid jmp_buf type in AST file");
4143 return;
4144 }
4145 Context.setjmp_bufDecl(Tag->getDecl());
4146 }
4147 }
4148 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004149
Guy Benyei11169dd2012-12-18 14:30:41 +00004150 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4151 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4152 if (Sigjmp_bufType.isNull()) {
4153 Error("sigjmp_buf type is NULL");
4154 return;
4155 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004156
Guy Benyei11169dd2012-12-18 14:30:41 +00004157 if (!Context.sigjmp_bufDecl) {
4158 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4159 Context.setsigjmp_bufDecl(Typedef->getDecl());
4160 else {
4161 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4162 assert(Tag && "Invalid sigjmp_buf type in AST file");
4163 Context.setsigjmp_bufDecl(Tag->getDecl());
4164 }
4165 }
4166 }
4167
4168 if (unsigned ObjCIdRedef
4169 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4170 if (Context.ObjCIdRedefinitionType.isNull())
4171 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4172 }
4173
4174 if (unsigned ObjCClassRedef
4175 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4176 if (Context.ObjCClassRedefinitionType.isNull())
4177 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4178 }
4179
4180 if (unsigned ObjCSelRedef
4181 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4182 if (Context.ObjCSelRedefinitionType.isNull())
4183 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4184 }
4185
4186 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4187 QualType Ucontext_tType = GetType(Ucontext_t);
4188 if (Ucontext_tType.isNull()) {
4189 Error("ucontext_t type is NULL");
4190 return;
4191 }
4192
4193 if (!Context.ucontext_tDecl) {
4194 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4195 Context.setucontext_tDecl(Typedef->getDecl());
4196 else {
4197 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4198 assert(Tag && "Invalid ucontext_t type in AST file");
4199 Context.setucontext_tDecl(Tag->getDecl());
4200 }
4201 }
4202 }
4203 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004204
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4206
4207 // If there were any CUDA special declarations, deserialize them.
4208 if (!CUDASpecialDeclRefs.empty()) {
4209 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4210 Context.setcudaConfigureCallDecl(
4211 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4212 }
Richard Smith56be7542014-03-21 00:33:59 +00004213
Guy Benyei11169dd2012-12-18 14:30:41 +00004214 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004215 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004216 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004217 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004218 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004219 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004220 if (Import.ImportLoc.isValid())
4221 PP.makeModuleVisible(Imported, Import.ImportLoc);
4222 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004223 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004224 }
4225 ImportedModules.clear();
4226}
4227
4228void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004229 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004230}
4231
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004232/// \brief Reads and return the signature record from \p PCH's control block, or
4233/// else returns 0.
4234static ASTFileSignature readASTFileSignature(StringRef PCH) {
4235 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004236 if (!startsWithASTFileMagic(Stream))
Ben Langmuir487ea142014-10-23 18:05:36 +00004237 return 0;
Ben Langmuir487ea142014-10-23 18:05:36 +00004238
4239 // Scan for the CONTROL_BLOCK_ID block.
4240 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
4241 return 0;
4242
4243 // Scan for SIGNATURE inside the control block.
4244 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004245 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004246 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004247 if (Entry.Kind != llvm::BitstreamEntry::Record)
Ben Langmuir487ea142014-10-23 18:05:36 +00004248 return 0;
4249
4250 Record.clear();
4251 StringRef Blob;
4252 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
4253 return Record[0];
4254 }
4255}
4256
Guy Benyei11169dd2012-12-18 14:30:41 +00004257/// \brief Retrieve the name of the original source file name
4258/// directly from the AST file, without actually loading the AST
4259/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004260std::string ASTReader::getOriginalSourceFile(
4261 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004262 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004263 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004264 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004266 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4267 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004268 return std::string();
4269 }
4270
4271 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004272 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004273
4274 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004275 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4277 return std::string();
4278 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004279
Chris Lattnere7b154b2013-01-19 21:39:22 +00004280 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004281 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004282 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4283 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004284 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004285
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004286 // Scan for ORIGINAL_FILE inside the control block.
4287 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004288 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004289 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004290 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4291 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004292
Chris Lattnere7b154b2013-01-19 21:39:22 +00004293 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4294 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4295 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004296 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004297
Guy Benyei11169dd2012-12-18 14:30:41 +00004298 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004299 StringRef Blob;
4300 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4301 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004302 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004303}
4304
4305namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004306
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 class SimplePCHValidator : public ASTReaderListener {
4308 const LangOptions &ExistingLangOpts;
4309 const TargetOptions &ExistingTargetOpts;
4310 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004311 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004313
Guy Benyei11169dd2012-12-18 14:30:41 +00004314 public:
4315 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4316 const TargetOptions &ExistingTargetOpts,
4317 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004318 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004319 FileManager &FileMgr)
4320 : ExistingLangOpts(ExistingLangOpts),
4321 ExistingTargetOpts(ExistingTargetOpts),
4322 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004323 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004324 FileMgr(FileMgr)
4325 {
4326 }
4327
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004328 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4329 bool AllowCompatibleDifferences) override {
4330 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4331 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004333
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004334 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4335 bool AllowCompatibleDifferences) override {
4336 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4337 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004339
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004340 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4341 StringRef SpecificModuleCachePath,
4342 bool Complain) override {
4343 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4344 ExistingModuleCachePath,
4345 nullptr, ExistingLangOpts);
4346 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004347
Craig Topper3e89dfe2014-03-13 02:13:41 +00004348 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4349 bool Complain,
4350 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004351 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004352 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 }
4354 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004355
4356} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004357
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004358bool ASTReader::readASTFileControlBlock(
4359 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004360 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004361 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004362 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004364 // FIXME: This allows use of the VFS; we do not allow use of the
4365 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004366 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 if (!Buffer) {
4368 return true;
4369 }
4370
4371 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004372 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004373
4374 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004375 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004376 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004377
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004378 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004379 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004380 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004381
4382 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004383 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004384 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004385 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004386
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004388 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004389 bool DoneWithControlBlock = false;
4390 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004391 llvm::BitstreamEntry Entry = Stream.advance();
4392
4393 switch (Entry.Kind) {
4394 case llvm::BitstreamEntry::SubBlock: {
4395 switch (Entry.ID) {
4396 case OPTIONS_BLOCK_ID: {
4397 std::string IgnoredSuggestedPredefines;
4398 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4399 /*AllowCompatibleConfigurationMismatch*/ false,
Manman Ren47a44452016-07-26 17:12:17 +00004400 Listener, IgnoredSuggestedPredefines,
4401 ValidateDiagnosticOptions) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004402 return true;
4403 break;
4404 }
4405
4406 case INPUT_FILES_BLOCK_ID:
4407 InputFilesCursor = Stream;
4408 if (Stream.SkipBlock() ||
4409 (NeedsInputFiles &&
4410 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4411 return true;
4412 break;
4413
4414 default:
4415 if (Stream.SkipBlock())
4416 return true;
4417 break;
4418 }
4419
4420 continue;
4421 }
4422
4423 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004424 DoneWithControlBlock = true;
4425 break;
Richard Smith0516b182015-09-08 19:40:14 +00004426
4427 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004428 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004429
4430 case llvm::BitstreamEntry::Record:
4431 break;
4432 }
4433
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004434 if (DoneWithControlBlock) break;
4435
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004437 StringRef Blob;
4438 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004439 switch ((ControlRecordTypes)RecCode) {
4440 case METADATA: {
4441 if (Record[0] != VERSION_MAJOR)
4442 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004443
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004444 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004445 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004446
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004447 break;
4448 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004449 case MODULE_NAME:
4450 Listener.ReadModuleName(Blob);
4451 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004452 case MODULE_DIRECTORY:
4453 ModuleDir = Blob;
4454 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004455 case MODULE_MAP_FILE: {
4456 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004457 auto Path = ReadString(Record, Idx);
4458 ResolveImportedPath(Path, ModuleDir);
4459 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004460 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004461 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004462 case INPUT_FILE_OFFSETS: {
4463 if (!NeedsInputFiles)
4464 break;
4465
4466 unsigned NumInputFiles = Record[0];
4467 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004468 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004469 for (unsigned I = 0; I != NumInputFiles; ++I) {
4470 // Go find this input file.
4471 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004472
4473 if (isSystemFile && !NeedsSystemInputFiles)
4474 break; // the rest are system input files
4475
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004476 BitstreamCursor &Cursor = InputFilesCursor;
4477 SavedStreamPosition SavedPosition(Cursor);
4478 Cursor.JumpToBit(InputFileOffs[I]);
4479
4480 unsigned Code = Cursor.ReadCode();
4481 RecordData Record;
4482 StringRef Blob;
4483 bool shouldContinue = false;
4484 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4485 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004486 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004487 std::string Filename = Blob;
4488 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004489 shouldContinue = Listener.visitInputFile(
4490 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004491 break;
4492 }
4493 if (!shouldContinue)
4494 break;
4495 }
4496 break;
4497 }
4498
Richard Smithd4b230b2014-10-27 23:01:16 +00004499 case IMPORTS: {
4500 if (!NeedsImports)
4501 break;
4502
4503 unsigned Idx = 0, N = Record.size();
4504 while (Idx < N) {
4505 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004506 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004507 std::string Filename = ReadString(Record, Idx);
4508 ResolveImportedPath(Filename, ModuleDir);
4509 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004510 }
4511 break;
4512 }
4513
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004514 default:
4515 // No other validation to perform.
4516 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004517 }
4518 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004519
4520 // Look for module file extension blocks, if requested.
4521 if (FindModuleFileExtensions) {
4522 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4523 bool DoneWithExtensionBlock = false;
4524 while (!DoneWithExtensionBlock) {
4525 llvm::BitstreamEntry Entry = Stream.advance();
4526
4527 switch (Entry.Kind) {
4528 case llvm::BitstreamEntry::SubBlock:
4529 if (Stream.SkipBlock())
4530 return true;
4531
4532 continue;
4533
4534 case llvm::BitstreamEntry::EndBlock:
4535 DoneWithExtensionBlock = true;
4536 continue;
4537
4538 case llvm::BitstreamEntry::Error:
4539 return true;
4540
4541 case llvm::BitstreamEntry::Record:
4542 break;
4543 }
4544
4545 Record.clear();
4546 StringRef Blob;
4547 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4548 switch (RecCode) {
4549 case EXTENSION_METADATA: {
4550 ModuleFileExtensionMetadata Metadata;
4551 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4552 return true;
4553
4554 Listener.readModuleFileExtension(Metadata);
4555 break;
4556 }
4557 }
4558 }
4559 }
4560 }
4561
4562 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004563}
4564
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004565bool ASTReader::isAcceptableASTFile(
4566 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004567 const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004568 const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
4569 std::string ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004570 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4571 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004572 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004573 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004574 validator,
4575 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004576}
4577
Ben Langmuir2c9af442014-04-10 17:57:43 +00004578ASTReader::ASTReadResult
4579ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 // Enter the submodule block.
4581 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4582 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004583 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585
4586 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4587 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004588 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004589 RecordData Record;
4590 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004591 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004592
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004593 switch (Entry.Kind) {
4594 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4595 case llvm::BitstreamEntry::Error:
4596 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004597 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004598 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004599 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004600 case llvm::BitstreamEntry::Record:
4601 // The interesting case.
4602 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004603 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004604
Guy Benyei11169dd2012-12-18 14:30:41 +00004605 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004606 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004607 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004608 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4609
4610 if ((Kind == SUBMODULE_METADATA) != First) {
4611 Error("submodule metadata record should be at beginning of block");
4612 return Failure;
4613 }
4614 First = false;
4615
4616 // Submodule information is only valid if we have a current module.
4617 // FIXME: Should we error on these cases?
4618 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4619 Kind != SUBMODULE_DEFINITION)
4620 continue;
4621
4622 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004623 default: // Default behavior: ignore.
4624 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004625
Richard Smith03478d92014-10-23 22:12:14 +00004626 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004627 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004628 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004629 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004630 }
Richard Smith03478d92014-10-23 22:12:14 +00004631
Chris Lattner0e6c9402013-01-20 02:38:54 +00004632 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004633 unsigned Idx = 0;
4634 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4635 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4636 bool IsFramework = Record[Idx++];
4637 bool IsExplicit = Record[Idx++];
4638 bool IsSystem = Record[Idx++];
4639 bool IsExternC = Record[Idx++];
4640 bool InferSubmodules = Record[Idx++];
4641 bool InferExplicitSubmodules = Record[Idx++];
4642 bool InferExportWildcard = Record[Idx++];
4643 bool ConfigMacrosExhaustive = Record[Idx++];
David Blaikie9ffe5a32017-01-30 05:00:26 +00004644 bool WithCodegen = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004645
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004646 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004647 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004648 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004649
Guy Benyei11169dd2012-12-18 14:30:41 +00004650 // Retrieve this (sub)module from the module map, creating it if
4651 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004652 CurrentModule =
4653 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4654 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004655
4656 // FIXME: set the definition loc for CurrentModule, or call
4657 // ModMap.setInferredModuleAllowedBy()
4658
Guy Benyei11169dd2012-12-18 14:30:41 +00004659 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4660 if (GlobalIndex >= SubmodulesLoaded.size() ||
4661 SubmodulesLoaded[GlobalIndex]) {
4662 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004663 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004664 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004665
Douglas Gregor7029ce12013-03-19 00:28:20 +00004666 if (!ParentModule) {
4667 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4668 if (CurFile != F.File) {
4669 if (!Diags.isDiagnosticInFlight()) {
4670 Diag(diag::err_module_file_conflict)
4671 << CurrentModule->getTopLevelModuleName()
4672 << CurFile->getName()
4673 << F.File->getName();
4674 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004675 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004676 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004677 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004678
4679 CurrentModule->setASTFile(F.File);
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004680 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004681
Adrian Prantl15bcf702015-06-30 17:39:43 +00004682 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004683 CurrentModule->IsFromModuleFile = true;
4684 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004685 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004686 CurrentModule->InferSubmodules = InferSubmodules;
4687 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4688 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004689 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
David Blaikie9ffe5a32017-01-30 05:00:26 +00004690 CurrentModule->WithCodegen = WithCodegen;
Guy Benyei11169dd2012-12-18 14:30:41 +00004691 if (DeserializationListener)
4692 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004693
Guy Benyei11169dd2012-12-18 14:30:41 +00004694 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004695
Richard Smith8a3e39a2016-03-28 21:31:09 +00004696 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004697 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004698 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004699 CurrentModule->UnresolvedConflicts.clear();
4700 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004701
4702 // The module is available unless it's missing a requirement; relevant
4703 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4704 // Missing headers that were present when the module was built do not
4705 // make it unavailable -- if we got this far, this must be an explicitly
4706 // imported module file.
4707 CurrentModule->Requirements.clear();
4708 CurrentModule->MissingHeaders.clear();
4709 CurrentModule->IsMissingRequirement =
4710 ParentModule && ParentModule->IsMissingRequirement;
4711 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004712 break;
4713 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004714
Guy Benyei11169dd2012-12-18 14:30:41 +00004715 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004716 std::string Filename = Blob;
4717 ResolveImportedPath(F, Filename);
4718 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004719 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004720 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4721 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Ben Langmuirbc35fbe2015-02-20 21:46:39 +00004722 // This can be a spurious difference caused by changing the VFS to
4723 // point to a different copy of the file, and it is too late to
4724 // to rebuild safely.
4725 // FIXME: If we wrote the virtual paths instead of the 'real' paths,
4726 // after input file validation only real problems would remain and we
4727 // could just error. For now, assume it's okay.
4728 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004729 }
4730 }
4731 break;
4732 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004733
Richard Smith202210b2014-10-24 20:23:01 +00004734 case SUBMODULE_HEADER:
4735 case SUBMODULE_EXCLUDED_HEADER:
4736 case SUBMODULE_PRIVATE_HEADER:
4737 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004738 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4739 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004740 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004741
Richard Smith202210b2014-10-24 20:23:01 +00004742 case SUBMODULE_TEXTUAL_HEADER:
4743 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4744 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4745 // them here.
4746 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004747
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004749 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004750 break;
4751 }
4752
4753 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004754 std::string Dirname = Blob;
4755 ResolveImportedPath(F, Dirname);
4756 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004757 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004758 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4759 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004760 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4761 Error("mismatched umbrella directories in submodule");
4762 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004763 }
4764 }
4765 break;
4766 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004767
Guy Benyei11169dd2012-12-18 14:30:41 +00004768 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004769 F.BaseSubmoduleID = getTotalNumSubmodules();
4770 F.LocalNumSubmodules = Record[0];
4771 unsigned LocalBaseSubmoduleID = Record[1];
4772 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004773 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004774 // module.
4775 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004776
4777 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00004778 // module.
4779 F.SubmoduleRemap.insertOrReplace(
4780 std::make_pair(LocalBaseSubmoduleID,
4781 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00004782
Ben Langmuir52ca6782014-10-20 16:27:32 +00004783 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
4784 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004785 break;
4786 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004787
Guy Benyei11169dd2012-12-18 14:30:41 +00004788 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004789 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004790 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004791 Unresolved.File = &F;
4792 Unresolved.Mod = CurrentModule;
4793 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004794 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00004796 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004797 }
4798 break;
4799 }
4800
4801 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004802 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00004803 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00004804 Unresolved.File = &F;
4805 Unresolved.Mod = CurrentModule;
4806 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00004807 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00004809 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00004810 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004811
4812 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00004813 // the parsed, unresolved exports around.
4814 CurrentModule->UnresolvedExports.clear();
4815 break;
4816 }
4817 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00004818 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00004819 Context.getTargetInfo());
4820 break;
4821 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004822
4823 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004824 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00004825 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004826 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004827
4828 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00004829 CurrentModule->ConfigMacros.push_back(Blob.str());
4830 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00004831
4832 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00004833 UnresolvedModuleRef Unresolved;
4834 Unresolved.File = &F;
4835 Unresolved.Mod = CurrentModule;
4836 Unresolved.ID = Record[0];
4837 Unresolved.Kind = UnresolvedModuleRef::Conflict;
4838 Unresolved.IsWildcard = false;
4839 Unresolved.String = Blob;
4840 UnresolvedModuleRefs.push_back(Unresolved);
4841 break;
4842 }
Richard Smithdc1f0422016-07-20 19:10:16 +00004843
4844 case SUBMODULE_INITIALIZERS:
4845 SmallVector<uint32_t, 16> Inits;
4846 for (auto &ID : Record)
4847 Inits.push_back(getGlobalDeclID(F, ID));
4848 Context.addLazyModuleInitializers(CurrentModule, Inits);
4849 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 }
4851 }
4852}
4853
4854/// \brief Parse the record that corresponds to a LangOptions data
4855/// structure.
4856///
4857/// This routine parses the language options from the AST file and then gives
4858/// them to the AST listener if one is set.
4859///
4860/// \returns true if the listener deems the file unacceptable, false otherwise.
4861bool ASTReader::ParseLanguageOptions(const RecordData &Record,
4862 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004863 ASTReaderListener &Listener,
4864 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 LangOptions LangOpts;
4866 unsigned Idx = 0;
4867#define LANGOPT(Name, Bits, Default, Description) \
4868 LangOpts.Name = Record[Idx++];
4869#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
4870 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
4871#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004872#define SANITIZER(NAME, ID) \
4873 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00004874#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00004875
Ben Langmuircd98cb72015-06-23 18:20:18 +00004876 for (unsigned N = Record[Idx++]; N; --N)
4877 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
4878
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
4880 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
4881 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004882
Ben Langmuird4a667a2015-06-23 18:20:23 +00004883 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004884
4885 // Comment options.
4886 for (unsigned N = Record[Idx++]; N; --N) {
4887 LangOpts.CommentOpts.BlockCommandNames.push_back(
4888 ReadString(Record, Idx));
4889 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00004890 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00004891
Samuel Antaoee8fb302016-01-06 13:42:12 +00004892 // OpenMP offloading options.
4893 for (unsigned N = Record[Idx++]; N; --N) {
4894 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
4895 }
4896
4897 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
4898
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004899 return Listener.ReadLanguageOptions(LangOpts, Complain,
4900 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004901}
4902
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004903bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
4904 ASTReaderListener &Listener,
4905 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 unsigned Idx = 0;
4907 TargetOptions TargetOpts;
4908 TargetOpts.Triple = ReadString(Record, Idx);
4909 TargetOpts.CPU = ReadString(Record, Idx);
4910 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 for (unsigned N = Record[Idx++]; N; --N) {
4912 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
4913 }
4914 for (unsigned N = Record[Idx++]; N; --N) {
4915 TargetOpts.Features.push_back(ReadString(Record, Idx));
4916 }
4917
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004918 return Listener.ReadTargetOptions(TargetOpts, Complain,
4919 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004920}
4921
4922bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
4923 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00004924 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00004925 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00004926#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00004927#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00004928 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00004929#include "clang/Basic/DiagnosticOptions.def"
4930
Richard Smith3be1cb22014-08-07 00:24:21 +00004931 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00004932 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00004933 for (unsigned N = Record[Idx++]; N; --N)
4934 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00004935
4936 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
4937}
4938
4939bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
4940 ASTReaderListener &Listener) {
4941 FileSystemOptions FSOpts;
4942 unsigned Idx = 0;
4943 FSOpts.WorkingDir = ReadString(Record, Idx);
4944 return Listener.ReadFileSystemOptions(FSOpts, Complain);
4945}
4946
4947bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
4948 bool Complain,
4949 ASTReaderListener &Listener) {
4950 HeaderSearchOptions HSOpts;
4951 unsigned Idx = 0;
4952 HSOpts.Sysroot = ReadString(Record, Idx);
4953
4954 // Include entries.
4955 for (unsigned N = Record[Idx++]; N; --N) {
4956 std::string Path = ReadString(Record, Idx);
4957 frontend::IncludeDirGroup Group
4958 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00004959 bool IsFramework = Record[Idx++];
4960 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004961 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
4962 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00004963 }
4964
4965 // System header prefixes.
4966 for (unsigned N = Record[Idx++]; N; --N) {
4967 std::string Prefix = ReadString(Record, Idx);
4968 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00004969 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 }
4971
4972 HSOpts.ResourceDir = ReadString(Record, Idx);
4973 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00004974 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004975 HSOpts.DisableModuleHash = Record[Idx++];
4976 HSOpts.UseBuiltinIncludes = Record[Idx++];
4977 HSOpts.UseStandardSystemIncludes = Record[Idx++];
4978 HSOpts.UseStandardCXXIncludes = Record[Idx++];
4979 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004980 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00004981
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004982 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4983 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00004984}
4985
4986bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
4987 bool Complain,
4988 ASTReaderListener &Listener,
4989 std::string &SuggestedPredefines) {
4990 PreprocessorOptions PPOpts;
4991 unsigned Idx = 0;
4992
4993 // Macro definitions/undefs
4994 for (unsigned N = Record[Idx++]; N; --N) {
4995 std::string Macro = ReadString(Record, Idx);
4996 bool IsUndef = Record[Idx++];
4997 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
4998 }
4999
5000 // Includes
5001 for (unsigned N = Record[Idx++]; N; --N) {
5002 PPOpts.Includes.push_back(ReadString(Record, Idx));
5003 }
5004
5005 // Macro Includes
5006 for (unsigned N = Record[Idx++]; N; --N) {
5007 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5008 }
5009
5010 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005011 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5013 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5014 PPOpts.ObjCXXARCStandardLibrary =
5015 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5016 SuggestedPredefines.clear();
5017 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5018 SuggestedPredefines);
5019}
5020
5021std::pair<ModuleFile *, unsigned>
5022ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5023 GlobalPreprocessedEntityMapType::iterator
5024 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005025 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005026 "Corrupted global preprocessed entity map");
5027 ModuleFile *M = I->second;
5028 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5029 return std::make_pair(M, LocalIndex);
5030}
5031
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005032llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005033ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5034 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5035 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5036 Mod.NumPreprocessedEntities);
5037
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005038 return llvm::make_range(PreprocessingRecord::iterator(),
5039 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005040}
5041
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005042llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005043ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005044 return llvm::make_range(
5045 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5046 ModuleDeclIterator(this, &Mod,
5047 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005048}
5049
5050PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5051 PreprocessedEntityID PPID = Index+1;
5052 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5053 ModuleFile &M = *PPInfo.first;
5054 unsigned LocalIndex = PPInfo.second;
5055 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5056
Guy Benyei11169dd2012-12-18 14:30:41 +00005057 if (!PP.getPreprocessingRecord()) {
5058 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005059 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005061
5062 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005063 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5064
5065 llvm::BitstreamEntry Entry =
5066 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5067 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005068 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005069
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005071 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5072 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005074 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005075 RecordData Record;
5076 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005077 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5078 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 switch (RecType) {
5080 case PPD_MACRO_EXPANSION: {
5081 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005082 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005083 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 if (isBuiltin)
5085 Name = getLocalIdentifier(M, Record[1]);
5086 else {
Richard Smith66a81862015-05-04 02:25:31 +00005087 PreprocessedEntityID GlobalID =
5088 getGlobalPreprocessedEntityID(M, Record[1]);
5089 Def = cast<MacroDefinitionRecord>(
5090 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005091 }
5092
5093 MacroExpansion *ME;
5094 if (isBuiltin)
5095 ME = new (PPRec) MacroExpansion(Name, Range);
5096 else
5097 ME = new (PPRec) MacroExpansion(Def, Range);
5098
5099 return ME;
5100 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005101
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 case PPD_MACRO_DEFINITION: {
5103 // Decode the identifier info and then check again; if the macro is
5104 // still defined and associated with the identifier,
5105 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005106 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005107
5108 if (DeserializationListener)
5109 DeserializationListener->MacroDefinitionRead(PPID, MD);
5110
5111 return MD;
5112 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005113
Guy Benyei11169dd2012-12-18 14:30:41 +00005114 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005115 const char *FullFileNameStart = Blob.data() + Record[0];
5116 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005117 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 if (!FullFileName.empty())
5119 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005120
Guy Benyei11169dd2012-12-18 14:30:41 +00005121 // FIXME: Stable encoding
5122 InclusionDirective::InclusionKind Kind
5123 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5124 InclusionDirective *ID
5125 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005126 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005127 Record[1], Record[3],
5128 File,
5129 Range);
5130 return ID;
5131 }
5132 }
5133
5134 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5135}
5136
5137/// \brief \arg SLocMapI points at a chunk of a module that contains no
5138/// preprocessed entities or the entities it contains are not the ones we are
5139/// looking for. Find the next module that contains entities and return the ID
5140/// of the first entry.
5141PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5142 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5143 ++SLocMapI;
5144 for (GlobalSLocOffsetMapType::const_iterator
5145 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5146 ModuleFile &M = *SLocMapI->second;
5147 if (M.NumPreprocessedEntities)
5148 return M.BasePreprocessedEntityID;
5149 }
5150
5151 return getTotalNumPreprocessedEntities();
5152}
5153
5154namespace {
5155
Guy Benyei11169dd2012-12-18 14:30:41 +00005156struct PPEntityComp {
5157 const ASTReader &Reader;
5158 ModuleFile &M;
5159
5160 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5161
5162 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5163 SourceLocation LHS = getLoc(L);
5164 SourceLocation RHS = getLoc(R);
5165 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5166 }
5167
5168 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5169 SourceLocation LHS = getLoc(L);
5170 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5171 }
5172
5173 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5174 SourceLocation RHS = getLoc(R);
5175 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5176 }
5177
5178 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005179 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005180 }
5181};
5182
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005183} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005184
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005185PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5186 bool EndsAfter) const {
5187 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005188 return getTotalNumPreprocessedEntities();
5189
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005190 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5191 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005192 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5193 "Corrupted global sloc offset map");
5194
5195 if (SLocMapI->second->NumPreprocessedEntities == 0)
5196 return findNextPreprocessedEntity(SLocMapI);
5197
5198 ModuleFile &M = *SLocMapI->second;
5199 typedef const PPEntityOffset *pp_iterator;
5200 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5201 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5202
5203 size_t Count = M.NumPreprocessedEntities;
5204 size_t Half;
5205 pp_iterator First = pp_begin;
5206 pp_iterator PPI;
5207
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005208 if (EndsAfter) {
5209 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005210 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005211 } else {
5212 // Do a binary search manually instead of using std::lower_bound because
5213 // The end locations of entities may be unordered (when a macro expansion
5214 // is inside another macro argument), but for this case it is not important
5215 // whether we get the first macro expansion or its containing macro.
5216 while (Count > 0) {
5217 Half = Count / 2;
5218 PPI = First;
5219 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005220 if (SourceMgr.isBeforeInTranslationUnit(
5221 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005222 First = PPI;
5223 ++First;
5224 Count = Count - Half - 1;
5225 } else
5226 Count = Half;
5227 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005228 }
5229
5230 if (PPI == pp_end)
5231 return findNextPreprocessedEntity(SLocMapI);
5232
5233 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5234}
5235
Guy Benyei11169dd2012-12-18 14:30:41 +00005236/// \brief Returns a pair of [Begin, End) indices of preallocated
5237/// preprocessed entities that \arg Range encompasses.
5238std::pair<unsigned, unsigned>
5239 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5240 if (Range.isInvalid())
5241 return std::make_pair(0,0);
5242 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5243
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005244 PreprocessedEntityID BeginID =
5245 findPreprocessedEntity(Range.getBegin(), false);
5246 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005247 return std::make_pair(BeginID, EndID);
5248}
5249
5250/// \brief Optionally returns true or false if the preallocated preprocessed
5251/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005252Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005253 FileID FID) {
5254 if (FID.isInvalid())
5255 return false;
5256
5257 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5258 ModuleFile &M = *PPInfo.first;
5259 unsigned LocalIndex = PPInfo.second;
5260 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005261
Richard Smithcb34bd32016-03-27 07:28:06 +00005262 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005263 if (Loc.isInvalid())
5264 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005265
Guy Benyei11169dd2012-12-18 14:30:41 +00005266 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5267 return true;
5268 else
5269 return false;
5270}
5271
5272namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005273
Guy Benyei11169dd2012-12-18 14:30:41 +00005274 /// \brief Visitor used to search for information about a header file.
5275 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005276 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005277
David Blaikie05785d12013-02-20 22:23:23 +00005278 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005279
Guy Benyei11169dd2012-12-18 14:30:41 +00005280 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005281 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5282 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005283
5284 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005285 HeaderFileInfoLookupTable *Table
5286 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5287 if (!Table)
5288 return false;
5289
5290 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005291 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005292 if (Pos == Table->end())
5293 return false;
5294
Richard Smithbdf2d932015-07-30 03:37:16 +00005295 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 return true;
5297 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005298
David Blaikie05785d12013-02-20 22:23:23 +00005299 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005300 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005301
5302} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005303
5304HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005305 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005306 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005307 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005308 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005309
Guy Benyei11169dd2012-12-18 14:30:41 +00005310 return HeaderFileInfo();
5311}
5312
5313void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005314 using DiagState = DiagnosticsEngine::DiagState;
5315 SmallVector<DiagState *, 32> DiagStates;
5316
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005317 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005319 auto &Record = F.PragmaDiagMappings;
5320 if (Record.empty())
5321 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005322
Richard Smithd230de22017-01-26 01:01:01 +00005323 DiagStates.clear();
5324
5325 auto ReadDiagState =
5326 [&](const DiagState &BasedOn, SourceLocation Loc,
5327 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5328 unsigned BackrefID = Record[Idx++];
5329 if (BackrefID != 0)
5330 return DiagStates[BackrefID - 1];
5331
Guy Benyei11169dd2012-12-18 14:30:41 +00005332 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005333 Diag.DiagStates.push_back(BasedOn);
5334 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005335 DiagStates.push_back(NewState);
Richard Smithd230de22017-01-26 01:01:01 +00005336 while (Idx + 1 < Record.size() && Record[Idx] != unsigned(-1)) {
5337 unsigned DiagID = Record[Idx++];
5338 diag::Severity Map = (diag::Severity)Record[Idx++];
Alp Tokerc726c362014-06-10 09:31:37 +00005339 DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
Richard Smithd230de22017-01-26 01:01:01 +00005340 if (Mapping.isPragma() || IncludeNonPragmaStates)
5341 NewState->setMapping(DiagID, Mapping);
5342 }
5343 assert(Idx != Record.size() && Record[Idx] == unsigned(-1) &&
5344 "Invalid data, didn't find '-1' marking end of diag/map pairs");
5345 ++Idx;
5346 return NewState;
5347 };
5348
5349 auto *FirstState = ReadDiagState(
5350 F.isModule() ? DiagState() : *Diag.DiagStatesByLoc.CurDiagState,
5351 SourceLocation(), F.isModule());
5352 SourceLocation CurStateLoc =
5353 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5354 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5355
5356 if (!F.isModule()) {
5357 Diag.DiagStatesByLoc.CurDiagState = CurState;
5358 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5359
5360 // Preserve the property that the imaginary root file describes the
5361 // current state.
5362 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5363 if (T.empty())
5364 T.push_back({CurState, 0});
5365 else
5366 T[0].State = CurState;
5367 }
5368
5369 while (Idx < Record.size()) {
5370 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5371 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5372 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5373 unsigned Transitions = Record[Idx++];
5374
5375 // Note that we don't need to set up Parent/ParentOffset here, because
5376 // we won't be changing the diagnostic state within imported FileIDs
5377 // (other than perhaps appending to the main source file, which has no
5378 // parent).
5379 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5380 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5381 for (unsigned I = 0; I != Transitions; ++I) {
5382 unsigned Offset = Record[Idx++];
5383 auto *State =
5384 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5385 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005386 }
5387 }
Richard Smithd230de22017-01-26 01:01:01 +00005388
5389 // Don't try to read these mappings again.
5390 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005391 }
5392}
5393
5394/// \brief Get the correct cursor and offset for loading a type.
5395ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5396 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5397 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5398 ModuleFile *M = I->second;
5399 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5400}
5401
5402/// \brief Read and return the type with the given index..
5403///
5404/// The index is the type ID, shifted and minus the number of predefs. This
5405/// routine actually reads the record corresponding to the type at the given
5406/// location. It is a helper routine for GetType, which deals with reading type
5407/// IDs.
5408QualType ASTReader::readTypeRecord(unsigned Index) {
5409 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005410 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005411
5412 // Keep track of where we are in the stream, then jump back there
5413 // after reading this type.
5414 SavedStreamPosition SavedPosition(DeclsCursor);
5415
5416 ReadingKindTracker ReadingKind(Read_Type, *this);
5417
5418 // Note that we are loading a type record.
5419 Deserializing AType(this);
5420
5421 unsigned Idx = 0;
5422 DeclsCursor.JumpToBit(Loc.Offset);
5423 RecordData Record;
5424 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005425 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005426 case TYPE_EXT_QUAL: {
5427 if (Record.size() != 2) {
5428 Error("Incorrect encoding of extended qualifier type");
5429 return QualType();
5430 }
5431 QualType Base = readType(*Loc.F, Record, Idx);
5432 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5433 return Context.getQualifiedType(Base, Quals);
5434 }
5435
5436 case TYPE_COMPLEX: {
5437 if (Record.size() != 1) {
5438 Error("Incorrect encoding of complex type");
5439 return QualType();
5440 }
5441 QualType ElemType = readType(*Loc.F, Record, Idx);
5442 return Context.getComplexType(ElemType);
5443 }
5444
5445 case TYPE_POINTER: {
5446 if (Record.size() != 1) {
5447 Error("Incorrect encoding of pointer type");
5448 return QualType();
5449 }
5450 QualType PointeeType = readType(*Loc.F, Record, Idx);
5451 return Context.getPointerType(PointeeType);
5452 }
5453
Reid Kleckner8a365022013-06-24 17:51:48 +00005454 case TYPE_DECAYED: {
5455 if (Record.size() != 1) {
5456 Error("Incorrect encoding of decayed type");
5457 return QualType();
5458 }
5459 QualType OriginalType = readType(*Loc.F, Record, Idx);
5460 QualType DT = Context.getAdjustedParameterType(OriginalType);
5461 if (!isa<DecayedType>(DT))
5462 Error("Decayed type does not decay");
5463 return DT;
5464 }
5465
Reid Kleckner0503a872013-12-05 01:23:43 +00005466 case TYPE_ADJUSTED: {
5467 if (Record.size() != 2) {
5468 Error("Incorrect encoding of adjusted type");
5469 return QualType();
5470 }
5471 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5472 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5473 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5474 }
5475
Guy Benyei11169dd2012-12-18 14:30:41 +00005476 case TYPE_BLOCK_POINTER: {
5477 if (Record.size() != 1) {
5478 Error("Incorrect encoding of block pointer type");
5479 return QualType();
5480 }
5481 QualType PointeeType = readType(*Loc.F, Record, Idx);
5482 return Context.getBlockPointerType(PointeeType);
5483 }
5484
5485 case TYPE_LVALUE_REFERENCE: {
5486 if (Record.size() != 2) {
5487 Error("Incorrect encoding of lvalue reference type");
5488 return QualType();
5489 }
5490 QualType PointeeType = readType(*Loc.F, Record, Idx);
5491 return Context.getLValueReferenceType(PointeeType, Record[1]);
5492 }
5493
5494 case TYPE_RVALUE_REFERENCE: {
5495 if (Record.size() != 1) {
5496 Error("Incorrect encoding of rvalue reference type");
5497 return QualType();
5498 }
5499 QualType PointeeType = readType(*Loc.F, Record, Idx);
5500 return Context.getRValueReferenceType(PointeeType);
5501 }
5502
5503 case TYPE_MEMBER_POINTER: {
5504 if (Record.size() != 2) {
5505 Error("Incorrect encoding of member pointer type");
5506 return QualType();
5507 }
5508 QualType PointeeType = readType(*Loc.F, Record, Idx);
5509 QualType ClassType = readType(*Loc.F, Record, Idx);
5510 if (PointeeType.isNull() || ClassType.isNull())
5511 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005512
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5514 }
5515
5516 case TYPE_CONSTANT_ARRAY: {
5517 QualType ElementType = readType(*Loc.F, Record, Idx);
5518 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5519 unsigned IndexTypeQuals = Record[2];
5520 unsigned Idx = 3;
5521 llvm::APInt Size = ReadAPInt(Record, Idx);
5522 return Context.getConstantArrayType(ElementType, Size,
5523 ASM, IndexTypeQuals);
5524 }
5525
5526 case TYPE_INCOMPLETE_ARRAY: {
5527 QualType ElementType = readType(*Loc.F, Record, Idx);
5528 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5529 unsigned IndexTypeQuals = Record[2];
5530 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5531 }
5532
5533 case TYPE_VARIABLE_ARRAY: {
5534 QualType ElementType = readType(*Loc.F, Record, Idx);
5535 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5536 unsigned IndexTypeQuals = Record[2];
5537 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5538 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5539 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5540 ASM, IndexTypeQuals,
5541 SourceRange(LBLoc, RBLoc));
5542 }
5543
5544 case TYPE_VECTOR: {
5545 if (Record.size() != 3) {
5546 Error("incorrect encoding of vector type in AST file");
5547 return QualType();
5548 }
5549
5550 QualType ElementType = readType(*Loc.F, Record, Idx);
5551 unsigned NumElements = Record[1];
5552 unsigned VecKind = Record[2];
5553 return Context.getVectorType(ElementType, NumElements,
5554 (VectorType::VectorKind)VecKind);
5555 }
5556
5557 case TYPE_EXT_VECTOR: {
5558 if (Record.size() != 3) {
5559 Error("incorrect encoding of extended vector type in AST file");
5560 return QualType();
5561 }
5562
5563 QualType ElementType = readType(*Loc.F, Record, Idx);
5564 unsigned NumElements = Record[1];
5565 return Context.getExtVectorType(ElementType, NumElements);
5566 }
5567
5568 case TYPE_FUNCTION_NO_PROTO: {
5569 if (Record.size() != 6) {
5570 Error("incorrect encoding of no-proto function type");
5571 return QualType();
5572 }
5573 QualType ResultType = readType(*Loc.F, Record, Idx);
5574 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
5575 (CallingConv)Record[4], Record[5]);
5576 return Context.getFunctionNoProtoType(ResultType, Info);
5577 }
5578
5579 case TYPE_FUNCTION_PROTO: {
5580 QualType ResultType = readType(*Loc.F, Record, Idx);
5581
5582 FunctionProtoType::ExtProtoInfo EPI;
5583 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5584 /*hasregparm*/ Record[2],
5585 /*regparm*/ Record[3],
5586 static_cast<CallingConv>(Record[4]),
5587 /*produces*/ Record[5]);
5588
5589 unsigned Idx = 6;
Guy Benyei11169dd2012-12-18 14:30:41 +00005590
5591 EPI.Variadic = Record[Idx++];
5592 EPI.HasTrailingReturn = Record[Idx++];
5593 EPI.TypeQuals = Record[Idx++];
5594 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005595 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005596 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005597
5598 unsigned NumParams = Record[Idx++];
5599 SmallVector<QualType, 16> ParamTypes;
5600 for (unsigned I = 0; I != NumParams; ++I)
5601 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5602
John McCall18afab72016-03-01 00:49:02 +00005603 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5604 if (Idx != Record.size()) {
5605 for (unsigned I = 0; I != NumParams; ++I)
5606 ExtParameterInfos.push_back(
5607 FunctionProtoType::ExtParameterInfo
5608 ::getFromOpaqueValue(Record[Idx++]));
5609 EPI.ExtParameterInfos = ExtParameterInfos.data();
5610 }
5611
5612 assert(Idx == Record.size());
5613
Jordan Rose5c382722013-03-08 21:51:21 +00005614 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005615 }
5616
5617 case TYPE_UNRESOLVED_USING: {
5618 unsigned Idx = 0;
5619 return Context.getTypeDeclType(
5620 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5621 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005622
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 case TYPE_TYPEDEF: {
5624 if (Record.size() != 2) {
5625 Error("incorrect encoding of typedef type");
5626 return QualType();
5627 }
5628 unsigned Idx = 0;
5629 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5630 QualType Canonical = readType(*Loc.F, Record, Idx);
5631 if (!Canonical.isNull())
5632 Canonical = Context.getCanonicalType(Canonical);
5633 return Context.getTypedefType(Decl, Canonical);
5634 }
5635
5636 case TYPE_TYPEOF_EXPR:
5637 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5638
5639 case TYPE_TYPEOF: {
5640 if (Record.size() != 1) {
5641 Error("incorrect encoding of typeof(type) in AST file");
5642 return QualType();
5643 }
5644 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5645 return Context.getTypeOfType(UnderlyingType);
5646 }
5647
5648 case TYPE_DECLTYPE: {
5649 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5650 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5651 }
5652
5653 case TYPE_UNARY_TRANSFORM: {
5654 QualType BaseType = readType(*Loc.F, Record, Idx);
5655 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5656 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5657 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5658 }
5659
Richard Smith74aeef52013-04-26 16:15:35 +00005660 case TYPE_AUTO: {
5661 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005662 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005663 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005664 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005665 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005666
Richard Smith600b5262017-01-26 20:40:47 +00005667 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5668 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5669 QualType Deduced = readType(*Loc.F, Record, Idx);
5670 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5671 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5672 IsDependent);
5673 }
5674
Guy Benyei11169dd2012-12-18 14:30:41 +00005675 case TYPE_RECORD: {
5676 if (Record.size() != 2) {
5677 Error("incorrect encoding of record type");
5678 return QualType();
5679 }
5680 unsigned Idx = 0;
5681 bool IsDependent = Record[Idx++];
5682 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5683 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5684 QualType T = Context.getRecordType(RD);
5685 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5686 return T;
5687 }
5688
5689 case TYPE_ENUM: {
5690 if (Record.size() != 2) {
5691 Error("incorrect encoding of enum type");
5692 return QualType();
5693 }
5694 unsigned Idx = 0;
5695 bool IsDependent = Record[Idx++];
5696 QualType T
5697 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5698 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5699 return T;
5700 }
5701
5702 case TYPE_ATTRIBUTED: {
5703 if (Record.size() != 3) {
5704 Error("incorrect encoding of attributed type");
5705 return QualType();
5706 }
5707 QualType modifiedType = readType(*Loc.F, Record, Idx);
5708 QualType equivalentType = readType(*Loc.F, Record, Idx);
5709 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
5710 return Context.getAttributedType(kind, modifiedType, equivalentType);
5711 }
5712
5713 case TYPE_PAREN: {
5714 if (Record.size() != 1) {
5715 Error("incorrect encoding of paren type");
5716 return QualType();
5717 }
5718 QualType InnerType = readType(*Loc.F, Record, Idx);
5719 return Context.getParenType(InnerType);
5720 }
5721
5722 case TYPE_PACK_EXPANSION: {
5723 if (Record.size() != 2) {
5724 Error("incorrect encoding of pack expansion type");
5725 return QualType();
5726 }
5727 QualType Pattern = readType(*Loc.F, Record, Idx);
5728 if (Pattern.isNull())
5729 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00005730 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00005731 if (Record[1])
5732 NumExpansions = Record[1] - 1;
5733 return Context.getPackExpansionType(Pattern, NumExpansions);
5734 }
5735
5736 case TYPE_ELABORATED: {
5737 unsigned Idx = 0;
5738 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5739 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
5740 QualType NamedType = readType(*Loc.F, Record, Idx);
5741 return Context.getElaboratedType(Keyword, NNS, NamedType);
5742 }
5743
5744 case TYPE_OBJC_INTERFACE: {
5745 unsigned Idx = 0;
5746 ObjCInterfaceDecl *ItfD
5747 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
5748 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
5749 }
5750
Manman Rene6be26c2016-09-13 17:25:08 +00005751 case TYPE_OBJC_TYPE_PARAM: {
5752 unsigned Idx = 0;
5753 ObjCTypeParamDecl *Decl
5754 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
5755 unsigned NumProtos = Record[Idx++];
5756 SmallVector<ObjCProtocolDecl*, 4> Protos;
5757 for (unsigned I = 0; I != NumProtos; ++I)
5758 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
5759 return Context.getObjCTypeParamType(Decl, Protos);
5760 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 case TYPE_OBJC_OBJECT: {
5762 unsigned Idx = 0;
5763 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00005764 unsigned NumTypeArgs = Record[Idx++];
5765 SmallVector<QualType, 4> TypeArgs;
5766 for (unsigned I = 0; I != NumTypeArgs; ++I)
5767 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005768 unsigned NumProtos = Record[Idx++];
5769 SmallVector<ObjCProtocolDecl*, 4> Protos;
5770 for (unsigned I = 0; I != NumProtos; ++I)
5771 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00005772 bool IsKindOf = Record[Idx++];
5773 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00005774 }
5775
5776 case TYPE_OBJC_OBJECT_POINTER: {
5777 unsigned Idx = 0;
5778 QualType Pointee = readType(*Loc.F, Record, Idx);
5779 return Context.getObjCObjectPointerType(Pointee);
5780 }
5781
5782 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
5783 unsigned Idx = 0;
5784 QualType Parm = readType(*Loc.F, Record, Idx);
5785 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00005786 return Context.getSubstTemplateTypeParmType(
5787 cast<TemplateTypeParmType>(Parm),
5788 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00005789 }
5790
5791 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
5792 unsigned Idx = 0;
5793 QualType Parm = readType(*Loc.F, Record, Idx);
5794 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
5795 return Context.getSubstTemplateTypeParmPackType(
5796 cast<TemplateTypeParmType>(Parm),
5797 ArgPack);
5798 }
5799
5800 case TYPE_INJECTED_CLASS_NAME: {
5801 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
5802 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
5803 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
5804 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00005805 const Type *T = nullptr;
5806 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
5807 if (const Type *Existing = DI->getTypeForDecl()) {
5808 T = Existing;
5809 break;
5810 }
5811 }
5812 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00005813 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00005814 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
5815 DI->setTypeForDecl(T);
5816 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00005817 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00005818 }
5819
5820 case TYPE_TEMPLATE_TYPE_PARM: {
5821 unsigned Idx = 0;
5822 unsigned Depth = Record[Idx++];
5823 unsigned Index = Record[Idx++];
5824 bool Pack = Record[Idx++];
5825 TemplateTypeParmDecl *D
5826 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
5827 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
5828 }
5829
5830 case TYPE_DEPENDENT_NAME: {
5831 unsigned Idx = 0;
5832 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5833 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005834 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005835 QualType Canon = readType(*Loc.F, Record, Idx);
5836 if (!Canon.isNull())
5837 Canon = Context.getCanonicalType(Canon);
5838 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
5839 }
5840
5841 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
5842 unsigned Idx = 0;
5843 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
5844 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00005845 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005846 unsigned NumArgs = Record[Idx++];
5847 SmallVector<TemplateArgument, 8> Args;
5848 Args.reserve(NumArgs);
5849 while (NumArgs--)
5850 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
5851 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00005852 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005853 }
5854
5855 case TYPE_DEPENDENT_SIZED_ARRAY: {
5856 unsigned Idx = 0;
5857
5858 // ArrayType
5859 QualType ElementType = readType(*Loc.F, Record, Idx);
5860 ArrayType::ArraySizeModifier ASM
5861 = (ArrayType::ArraySizeModifier)Record[Idx++];
5862 unsigned IndexTypeQuals = Record[Idx++];
5863
5864 // DependentSizedArrayType
5865 Expr *NumElts = ReadExpr(*Loc.F);
5866 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
5867
5868 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
5869 IndexTypeQuals, Brackets);
5870 }
5871
5872 case TYPE_TEMPLATE_SPECIALIZATION: {
5873 unsigned Idx = 0;
5874 bool IsDependent = Record[Idx++];
5875 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5876 SmallVector<TemplateArgument, 8> Args;
5877 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
5878 QualType Underlying = readType(*Loc.F, Record, Idx);
5879 QualType T;
5880 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00005881 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00005882 else
David Majnemer6fbeee32016-07-07 04:43:07 +00005883 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00005884 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5885 return T;
5886 }
5887
5888 case TYPE_ATOMIC: {
5889 if (Record.size() != 1) {
5890 Error("Incorrect encoding of atomic type");
5891 return QualType();
5892 }
5893 QualType ValueType = readType(*Loc.F, Record, Idx);
5894 return Context.getAtomicType(ValueType);
5895 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00005896
Joey Goulye3c85de2016-12-01 11:30:49 +00005897 case TYPE_PIPE: {
5898 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00005899 Error("Incorrect encoding of pipe type");
5900 return QualType();
5901 }
5902
5903 // Reading the pipe element type.
5904 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00005905 unsigned ReadOnly = Record[1];
5906 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00005907 }
5908
Guy Benyei11169dd2012-12-18 14:30:41 +00005909 }
5910 llvm_unreachable("Invalid TypeCode!");
5911}
5912
Richard Smith564417a2014-03-20 21:47:22 +00005913void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
5914 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00005915 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00005916 const RecordData &Record, unsigned &Idx) {
5917 ExceptionSpecificationType EST =
5918 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00005919 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00005920 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00005921 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00005922 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00005923 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00005924 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00005925 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00005926 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005927 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
5928 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005929 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00005930 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00005931 }
5932}
5933
Guy Benyei11169dd2012-12-18 14:30:41 +00005934class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005935 ModuleFile *F;
5936 ASTReader *Reader;
5937 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00005938 unsigned &Idx;
5939
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005940 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005941 return Reader->ReadSourceLocation(*F, Record, Idx);
5942 }
5943
5944 TypeSourceInfo *GetTypeSourceInfo() {
5945 return Reader->GetTypeSourceInfo(*F, Record, Idx);
5946 }
5947
5948 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
5949 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005950 }
5951
Guy Benyei11169dd2012-12-18 14:30:41 +00005952public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00005953 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00005954 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00005955 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00005956
5957 // We want compile-time assurance that we've enumerated all of
5958 // these, so unfortunately we have to declare them first, then
5959 // define them out-of-line.
5960#define ABSTRACT_TYPELOC(CLASS, PARENT)
5961#define TYPELOC(CLASS, PARENT) \
5962 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
5963#include "clang/AST/TypeLocNodes.def"
5964
5965 void VisitFunctionTypeLoc(FunctionTypeLoc);
5966 void VisitArrayTypeLoc(ArrayTypeLoc);
5967};
5968
5969void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5970 // nothing to do
5971}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005972
Guy Benyei11169dd2012-12-18 14:30:41 +00005973void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005974 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005975 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00005976 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
5977 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
5978 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
5979 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005980 }
5981}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005982
Guy Benyei11169dd2012-12-18 14:30:41 +00005983void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005984 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005985}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005986
Guy Benyei11169dd2012-12-18 14:30:41 +00005987void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005988 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00005989}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005990
Reid Kleckner8a365022013-06-24 17:51:48 +00005991void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5992 // nothing to do
5993}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005994
Reid Kleckner0503a872013-12-05 01:23:43 +00005995void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5996 // nothing to do
5997}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005998
Guy Benyei11169dd2012-12-18 14:30:41 +00005999void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006000 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006001}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006002
Guy Benyei11169dd2012-12-18 14:30:41 +00006003void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006004 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006005}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006006
Guy Benyei11169dd2012-12-18 14:30:41 +00006007void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006008 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006009}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006010
Guy Benyei11169dd2012-12-18 14:30:41 +00006011void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006012 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006013 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006014}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006015
Guy Benyei11169dd2012-12-18 14:30:41 +00006016void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006017 TL.setLBracketLoc(ReadSourceLocation());
6018 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006019 if (Record[Idx++])
6020 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006021 else
Craig Toppera13603a2014-05-22 05:54:18 +00006022 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006023}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006024
Guy Benyei11169dd2012-12-18 14:30:41 +00006025void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6026 VisitArrayTypeLoc(TL);
6027}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006028
Guy Benyei11169dd2012-12-18 14:30:41 +00006029void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6030 VisitArrayTypeLoc(TL);
6031}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006032
Guy Benyei11169dd2012-12-18 14:30:41 +00006033void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6034 VisitArrayTypeLoc(TL);
6035}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006036
Guy Benyei11169dd2012-12-18 14:30:41 +00006037void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6038 DependentSizedArrayTypeLoc TL) {
6039 VisitArrayTypeLoc(TL);
6040}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006041
Guy Benyei11169dd2012-12-18 14:30:41 +00006042void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6043 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006044 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006045}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006046
Guy Benyei11169dd2012-12-18 14:30:41 +00006047void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006048 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006049}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006050
Guy Benyei11169dd2012-12-18 14:30:41 +00006051void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006052 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006053}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006054
Guy Benyei11169dd2012-12-18 14:30:41 +00006055void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006056 TL.setLocalRangeBegin(ReadSourceLocation());
6057 TL.setLParenLoc(ReadSourceLocation());
6058 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006059 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6060 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006061 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006062 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006063 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006064 }
6065}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006066
Guy Benyei11169dd2012-12-18 14:30:41 +00006067void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6068 VisitFunctionTypeLoc(TL);
6069}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006070
Guy Benyei11169dd2012-12-18 14:30:41 +00006071void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6072 VisitFunctionTypeLoc(TL);
6073}
6074void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006075 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006076}
6077void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006078 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006079}
6080void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006081 TL.setTypeofLoc(ReadSourceLocation());
6082 TL.setLParenLoc(ReadSourceLocation());
6083 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006084}
6085void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006086 TL.setTypeofLoc(ReadSourceLocation());
6087 TL.setLParenLoc(ReadSourceLocation());
6088 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006089 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006090}
6091void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006092 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006093}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006094
Guy Benyei11169dd2012-12-18 14:30:41 +00006095void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006096 TL.setKWLoc(ReadSourceLocation());
6097 TL.setLParenLoc(ReadSourceLocation());
6098 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006099 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006100}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006101
Guy Benyei11169dd2012-12-18 14:30:41 +00006102void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006103 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006104}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006105
Richard Smith600b5262017-01-26 20:40:47 +00006106void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6107 DeducedTemplateSpecializationTypeLoc TL) {
6108 TL.setTemplateNameLoc(ReadSourceLocation());
6109}
6110
Guy Benyei11169dd2012-12-18 14:30:41 +00006111void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006112 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006113}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006114
Guy Benyei11169dd2012-12-18 14:30:41 +00006115void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006116 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006117}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006118
Guy Benyei11169dd2012-12-18 14:30:41 +00006119void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006120 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 if (TL.hasAttrOperand()) {
6122 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006123 range.setBegin(ReadSourceLocation());
6124 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006125 TL.setAttrOperandParensRange(range);
6126 }
6127 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006128 if (Record[Idx++])
6129 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006130 else
Craig Toppera13603a2014-05-22 05:54:18 +00006131 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006132 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006133 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006134}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006135
Guy Benyei11169dd2012-12-18 14:30:41 +00006136void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006137 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006138}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006139
Guy Benyei11169dd2012-12-18 14:30:41 +00006140void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6141 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006142 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006143}
6144void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6145 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006146 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006147}
6148void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6149 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006150 TL.setTemplateKeywordLoc(ReadSourceLocation());
6151 TL.setTemplateNameLoc(ReadSourceLocation());
6152 TL.setLAngleLoc(ReadSourceLocation());
6153 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006154 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006155 TL.setArgLocInfo(
6156 i,
6157 Reader->GetTemplateArgumentLocInfo(
6158 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006159}
6160void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006161 TL.setLParenLoc(ReadSourceLocation());
6162 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006163}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006164
Guy Benyei11169dd2012-12-18 14:30:41 +00006165void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006166 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006167 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006168}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006169
Guy Benyei11169dd2012-12-18 14:30:41 +00006170void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006171 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006172}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006173
Guy Benyei11169dd2012-12-18 14:30:41 +00006174void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006175 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006176 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006177 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006178}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006179
Guy Benyei11169dd2012-12-18 14:30:41 +00006180void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6181 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006182 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006183 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006184 TL.setTemplateKeywordLoc(ReadSourceLocation());
6185 TL.setTemplateNameLoc(ReadSourceLocation());
6186 TL.setLAngleLoc(ReadSourceLocation());
6187 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006189 TL.setArgLocInfo(
6190 I,
6191 Reader->GetTemplateArgumentLocInfo(
6192 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006193}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006194
Guy Benyei11169dd2012-12-18 14:30:41 +00006195void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006196 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006197}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006198
Guy Benyei11169dd2012-12-18 14:30:41 +00006199void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006200 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006201}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006202
Manman Rene6be26c2016-09-13 17:25:08 +00006203void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6204 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006205 TL.setProtocolLAngleLoc(ReadSourceLocation());
6206 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006207 }
6208 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006209 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006210}
6211
Guy Benyei11169dd2012-12-18 14:30:41 +00006212void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006213 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006214 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6215 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006216 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006217 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006218 TL.setProtocolLAngleLoc(ReadSourceLocation());
6219 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006220 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006221 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006222}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006223
Guy Benyei11169dd2012-12-18 14:30:41 +00006224void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006225 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006226}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006227
Guy Benyei11169dd2012-12-18 14:30:41 +00006228void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006229 TL.setKWLoc(ReadSourceLocation());
6230 TL.setLParenLoc(ReadSourceLocation());
6231 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006232}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006233
Xiuli Pan9c14e282016-01-09 12:53:17 +00006234void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006235 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006236}
Guy Benyei11169dd2012-12-18 14:30:41 +00006237
David L. Jonesbe1557a2016-12-21 00:17:49 +00006238TypeSourceInfo *
6239ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6240 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006241 QualType InfoTy = readType(F, Record, Idx);
6242 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006243 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006244
6245 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006246 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6248 TLR.Visit(TL);
6249 return TInfo;
6250}
6251
6252QualType ASTReader::GetType(TypeID ID) {
6253 unsigned FastQuals = ID & Qualifiers::FastMask;
6254 unsigned Index = ID >> Qualifiers::FastWidth;
6255
6256 if (Index < NUM_PREDEF_TYPE_IDS) {
6257 QualType T;
6258 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006259 case PREDEF_TYPE_NULL_ID:
6260 return QualType();
6261 case PREDEF_TYPE_VOID_ID:
6262 T = Context.VoidTy;
6263 break;
6264 case PREDEF_TYPE_BOOL_ID:
6265 T = Context.BoolTy;
6266 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006267
6268 case PREDEF_TYPE_CHAR_U_ID:
6269 case PREDEF_TYPE_CHAR_S_ID:
6270 // FIXME: Check that the signedness of CharTy is correct!
6271 T = Context.CharTy;
6272 break;
6273
Alexey Baderbdf7c842015-09-15 12:18:29 +00006274 case PREDEF_TYPE_UCHAR_ID:
6275 T = Context.UnsignedCharTy;
6276 break;
6277 case PREDEF_TYPE_USHORT_ID:
6278 T = Context.UnsignedShortTy;
6279 break;
6280 case PREDEF_TYPE_UINT_ID:
6281 T = Context.UnsignedIntTy;
6282 break;
6283 case PREDEF_TYPE_ULONG_ID:
6284 T = Context.UnsignedLongTy;
6285 break;
6286 case PREDEF_TYPE_ULONGLONG_ID:
6287 T = Context.UnsignedLongLongTy;
6288 break;
6289 case PREDEF_TYPE_UINT128_ID:
6290 T = Context.UnsignedInt128Ty;
6291 break;
6292 case PREDEF_TYPE_SCHAR_ID:
6293 T = Context.SignedCharTy;
6294 break;
6295 case PREDEF_TYPE_WCHAR_ID:
6296 T = Context.WCharTy;
6297 break;
6298 case PREDEF_TYPE_SHORT_ID:
6299 T = Context.ShortTy;
6300 break;
6301 case PREDEF_TYPE_INT_ID:
6302 T = Context.IntTy;
6303 break;
6304 case PREDEF_TYPE_LONG_ID:
6305 T = Context.LongTy;
6306 break;
6307 case PREDEF_TYPE_LONGLONG_ID:
6308 T = Context.LongLongTy;
6309 break;
6310 case PREDEF_TYPE_INT128_ID:
6311 T = Context.Int128Ty;
6312 break;
6313 case PREDEF_TYPE_HALF_ID:
6314 T = Context.HalfTy;
6315 break;
6316 case PREDEF_TYPE_FLOAT_ID:
6317 T = Context.FloatTy;
6318 break;
6319 case PREDEF_TYPE_DOUBLE_ID:
6320 T = Context.DoubleTy;
6321 break;
6322 case PREDEF_TYPE_LONGDOUBLE_ID:
6323 T = Context.LongDoubleTy;
6324 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006325 case PREDEF_TYPE_FLOAT128_ID:
6326 T = Context.Float128Ty;
6327 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006328 case PREDEF_TYPE_OVERLOAD_ID:
6329 T = Context.OverloadTy;
6330 break;
6331 case PREDEF_TYPE_BOUND_MEMBER:
6332 T = Context.BoundMemberTy;
6333 break;
6334 case PREDEF_TYPE_PSEUDO_OBJECT:
6335 T = Context.PseudoObjectTy;
6336 break;
6337 case PREDEF_TYPE_DEPENDENT_ID:
6338 T = Context.DependentTy;
6339 break;
6340 case PREDEF_TYPE_UNKNOWN_ANY:
6341 T = Context.UnknownAnyTy;
6342 break;
6343 case PREDEF_TYPE_NULLPTR_ID:
6344 T = Context.NullPtrTy;
6345 break;
6346 case PREDEF_TYPE_CHAR16_ID:
6347 T = Context.Char16Ty;
6348 break;
6349 case PREDEF_TYPE_CHAR32_ID:
6350 T = Context.Char32Ty;
6351 break;
6352 case PREDEF_TYPE_OBJC_ID:
6353 T = Context.ObjCBuiltinIdTy;
6354 break;
6355 case PREDEF_TYPE_OBJC_CLASS:
6356 T = Context.ObjCBuiltinClassTy;
6357 break;
6358 case PREDEF_TYPE_OBJC_SEL:
6359 T = Context.ObjCBuiltinSelTy;
6360 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006361#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6362 case PREDEF_TYPE_##Id##_ID: \
6363 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006364 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006365#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006366 case PREDEF_TYPE_SAMPLER_ID:
6367 T = Context.OCLSamplerTy;
6368 break;
6369 case PREDEF_TYPE_EVENT_ID:
6370 T = Context.OCLEventTy;
6371 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006372 case PREDEF_TYPE_CLK_EVENT_ID:
6373 T = Context.OCLClkEventTy;
6374 break;
6375 case PREDEF_TYPE_QUEUE_ID:
6376 T = Context.OCLQueueTy;
6377 break;
6378 case PREDEF_TYPE_NDRANGE_ID:
6379 T = Context.OCLNDRangeTy;
6380 break;
6381 case PREDEF_TYPE_RESERVE_ID_ID:
6382 T = Context.OCLReserveIDTy;
6383 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006384 case PREDEF_TYPE_AUTO_DEDUCT:
6385 T = Context.getAutoDeductType();
6386 break;
6387
6388 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6389 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006390 break;
6391
6392 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6393 T = Context.ARCUnbridgedCastTy;
6394 break;
6395
Guy Benyei11169dd2012-12-18 14:30:41 +00006396 case PREDEF_TYPE_BUILTIN_FN:
6397 T = Context.BuiltinFnTy;
6398 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006399
6400 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6401 T = Context.OMPArraySectionTy;
6402 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006403 }
6404
6405 assert(!T.isNull() && "Unknown predefined type");
6406 return T.withFastQualifiers(FastQuals);
6407 }
6408
6409 Index -= NUM_PREDEF_TYPE_IDS;
6410 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6411 if (TypesLoaded[Index].isNull()) {
6412 TypesLoaded[Index] = readTypeRecord(Index);
6413 if (TypesLoaded[Index].isNull())
6414 return QualType();
6415
6416 TypesLoaded[Index]->setFromAST();
6417 if (DeserializationListener)
6418 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6419 TypesLoaded[Index]);
6420 }
6421
6422 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6423}
6424
6425QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6426 return GetType(getGlobalTypeID(F, LocalID));
6427}
6428
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006429serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006430ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6431 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6432 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006433
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6435 return LocalID;
6436
6437 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6438 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6439 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006440
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 unsigned GlobalIndex = LocalIndex + I->second;
6442 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6443}
6444
6445TemplateArgumentLocInfo
6446ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6447 TemplateArgument::ArgKind Kind,
6448 const RecordData &Record,
6449 unsigned &Index) {
6450 switch (Kind) {
6451 case TemplateArgument::Expression:
6452 return ReadExpr(F);
6453 case TemplateArgument::Type:
6454 return GetTypeSourceInfo(F, Record, Index);
6455 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006456 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006457 Index);
6458 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6459 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6460 SourceLocation());
6461 }
6462 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006463 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006464 Index);
6465 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6466 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006467 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006468 EllipsisLoc);
6469 }
6470 case TemplateArgument::Null:
6471 case TemplateArgument::Integral:
6472 case TemplateArgument::Declaration:
6473 case TemplateArgument::NullPtr:
6474 case TemplateArgument::Pack:
6475 // FIXME: Is this right?
6476 return TemplateArgumentLocInfo();
6477 }
6478 llvm_unreachable("unexpected template argument loc");
6479}
6480
6481TemplateArgumentLoc
6482ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6483 const RecordData &Record, unsigned &Index) {
6484 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6485
6486 if (Arg.getKind() == TemplateArgument::Expression) {
6487 if (Record[Index++]) // bool InfoHasSameExpr.
6488 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6489 }
6490 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6491 Record, Index));
6492}
6493
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006494const ASTTemplateArgumentListInfo*
6495ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6496 const RecordData &Record,
6497 unsigned &Index) {
6498 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6499 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6500 unsigned NumArgsAsWritten = Record[Index++];
6501 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6502 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6503 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6504 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6505}
6506
Guy Benyei11169dd2012-12-18 14:30:41 +00006507Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6508 return GetDecl(ID);
6509}
6510
Richard Smith50895422015-01-31 03:04:55 +00006511template<typename TemplateSpecializationDecl>
6512static void completeRedeclChainForTemplateSpecialization(Decl *D) {
6513 if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
6514 TSD->getSpecializedTemplate()->LoadLazySpecializations();
6515}
6516
Richard Smith053f6c62014-05-16 23:01:30 +00006517void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006518 if (NumCurrentElementsDeserializing) {
6519 // We arrange to not care about the complete redeclaration chain while we're
6520 // deserializing. Just remember that the AST has marked this one as complete
6521 // but that it's not actually complete yet, so we know we still need to
6522 // complete it later.
6523 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6524 return;
6525 }
6526
Richard Smith053f6c62014-05-16 23:01:30 +00006527 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6528
Richard Smith053f6c62014-05-16 23:01:30 +00006529 // If this is a named declaration, complete it by looking it up
6530 // within its context.
6531 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006532 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006533 // all mergeable entities within it.
6534 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6535 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6536 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006537 if (!getContext().getLangOpts().CPlusPlus &&
6538 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006539 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006540 // the identifier instead. (For C++ modules, we don't store decls
6541 // in the serialized identifier table, so we do the lookup in the TU.)
6542 auto *II = Name.getAsIdentifierInfo();
6543 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006544 if (II->isOutOfDate())
6545 updateOutOfDateIdentifier(*II);
6546 } else
6547 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006548 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006549 // Find all declarations of this kind from the relevant context.
6550 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6551 auto *DC = cast<DeclContext>(DCDecl);
6552 SmallVector<Decl*, 8> Decls;
6553 FindExternalLexicalDecls(
6554 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6555 }
Richard Smith053f6c62014-05-16 23:01:30 +00006556 }
6557 }
Richard Smith50895422015-01-31 03:04:55 +00006558
6559 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6560 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6561 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6562 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6563 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6564 if (auto *Template = FD->getPrimaryTemplate())
6565 Template->LoadLazySpecializations();
6566 }
Richard Smith053f6c62014-05-16 23:01:30 +00006567}
6568
Richard Smithc2bb8182015-03-24 06:36:48 +00006569CXXCtorInitializer **
6570ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6571 RecordLocation Loc = getLocalBitOffset(Offset);
6572 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6573 SavedStreamPosition SavedPosition(Cursor);
6574 Cursor.JumpToBit(Loc.Offset);
6575 ReadingKindTracker ReadingKind(Read_Decl, *this);
6576
6577 RecordData Record;
6578 unsigned Code = Cursor.ReadCode();
6579 unsigned RecCode = Cursor.readRecord(Code, Record);
6580 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6581 Error("malformed AST file: missing C++ ctor initializers");
6582 return nullptr;
6583 }
6584
6585 unsigned Idx = 0;
6586 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6587}
6588
Guy Benyei11169dd2012-12-18 14:30:41 +00006589CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6590 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006591 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006592 SavedStreamPosition SavedPosition(Cursor);
6593 Cursor.JumpToBit(Loc.Offset);
6594 ReadingKindTracker ReadingKind(Read_Decl, *this);
6595 RecordData Record;
6596 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006597 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006598 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006599 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006600 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006601 }
6602
6603 unsigned Idx = 0;
6604 unsigned NumBases = Record[Idx++];
6605 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6606 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6607 for (unsigned I = 0; I != NumBases; ++I)
6608 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6609 return Bases;
6610}
6611
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006612serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006613ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6614 if (LocalID < NUM_PREDEF_DECL_IDS)
6615 return LocalID;
6616
6617 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6618 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6619 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006620
Guy Benyei11169dd2012-12-18 14:30:41 +00006621 return LocalID + I->second;
6622}
6623
6624bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6625 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006626 // Predefined decls aren't from any module.
6627 if (ID < NUM_PREDEF_DECL_IDS)
6628 return false;
6629
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006630 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006631 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006632}
6633
Douglas Gregor9f782892013-01-21 15:25:38 +00006634ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006635 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006636 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006637 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6638 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6639 return I->second;
6640}
6641
6642SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6643 if (ID < NUM_PREDEF_DECL_IDS)
6644 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006645
Guy Benyei11169dd2012-12-18 14:30:41 +00006646 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6647
6648 if (Index > DeclsLoaded.size()) {
6649 Error("declaration ID out-of-range for AST file");
6650 return SourceLocation();
6651 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006652
Guy Benyei11169dd2012-12-18 14:30:41 +00006653 if (Decl *D = DeclsLoaded[Index])
6654 return D->getLocation();
6655
Richard Smithcb34bd32016-03-27 07:28:06 +00006656 SourceLocation Loc;
6657 DeclCursorForID(ID, Loc);
6658 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006659}
6660
Richard Smithfe620d22015-03-05 23:24:12 +00006661static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6662 switch (ID) {
6663 case PREDEF_DECL_NULL_ID:
6664 return nullptr;
6665
6666 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6667 return Context.getTranslationUnitDecl();
6668
6669 case PREDEF_DECL_OBJC_ID_ID:
6670 return Context.getObjCIdDecl();
6671
6672 case PREDEF_DECL_OBJC_SEL_ID:
6673 return Context.getObjCSelDecl();
6674
6675 case PREDEF_DECL_OBJC_CLASS_ID:
6676 return Context.getObjCClassDecl();
6677
6678 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6679 return Context.getObjCProtocolDecl();
6680
6681 case PREDEF_DECL_INT_128_ID:
6682 return Context.getInt128Decl();
6683
6684 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6685 return Context.getUInt128Decl();
6686
6687 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6688 return Context.getObjCInstanceTypeDecl();
6689
6690 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6691 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006692
Richard Smith9b88a4c2015-07-27 05:40:23 +00006693 case PREDEF_DECL_VA_LIST_TAG:
6694 return Context.getVaListTagDecl();
6695
Charles Davisc7d5c942015-09-17 20:55:33 +00006696 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
6697 return Context.getBuiltinMSVaListDecl();
6698
Richard Smithf19e1272015-03-07 00:04:49 +00006699 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
6700 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00006701
6702 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
6703 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00006704
6705 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
6706 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00006707
6708 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
6709 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00006710
6711 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
6712 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00006713 }
Yaron Keren322bdad2015-03-06 07:49:14 +00006714 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00006715}
6716
Richard Smithcd45dbc2014-04-19 03:48:30 +00006717Decl *ASTReader::GetExistingDecl(DeclID ID) {
6718 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00006719 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
6720 if (D) {
6721 // Track that we have merged the declaration with ID \p ID into the
6722 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00006723 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00006724 if (Merged.empty())
6725 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00006726 }
Richard Smithfe620d22015-03-05 23:24:12 +00006727 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00006728 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006729
Guy Benyei11169dd2012-12-18 14:30:41 +00006730 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6731
6732 if (Index >= DeclsLoaded.size()) {
6733 assert(0 && "declaration ID out-of-range for AST file");
6734 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006735 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006736 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006737
6738 return DeclsLoaded[Index];
6739}
6740
6741Decl *ASTReader::GetDecl(DeclID ID) {
6742 if (ID < NUM_PREDEF_DECL_IDS)
6743 return GetExistingDecl(ID);
6744
6745 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6746
6747 if (Index >= DeclsLoaded.size()) {
6748 assert(0 && "declaration ID out-of-range for AST file");
6749 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00006750 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00006751 }
6752
Guy Benyei11169dd2012-12-18 14:30:41 +00006753 if (!DeclsLoaded[Index]) {
6754 ReadDeclRecord(ID);
6755 if (DeserializationListener)
6756 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
6757 }
6758
6759 return DeclsLoaded[Index];
6760}
6761
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006762DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00006763 DeclID GlobalID) {
6764 if (GlobalID < NUM_PREDEF_DECL_IDS)
6765 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006766
Guy Benyei11169dd2012-12-18 14:30:41 +00006767 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
6768 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6769 ModuleFile *Owner = I->second;
6770
6771 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
6772 = M.GlobalToLocalDeclIDs.find(Owner);
6773 if (Pos == M.GlobalToLocalDeclIDs.end())
6774 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006775
Guy Benyei11169dd2012-12-18 14:30:41 +00006776 return GlobalID - Owner->BaseDeclID + Pos->second;
6777}
6778
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006779serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 const RecordData &Record,
6781 unsigned &Idx) {
6782 if (Idx >= Record.size()) {
6783 Error("Corrupted AST file");
6784 return 0;
6785 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006786
Guy Benyei11169dd2012-12-18 14:30:41 +00006787 return getGlobalDeclID(F, Record[Idx++]);
6788}
6789
6790/// \brief Resolve the offset of a statement into a statement.
6791///
6792/// This operation will read a new statement from the external
6793/// source each time it is called, and is meant to be used via a
6794/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
6795Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
6796 // Switch case IDs are per Decl.
6797 ClearSwitchCaseIDs();
6798
6799 // Offset here is a global offset across the entire chain.
6800 RecordLocation Loc = getLocalBitOffset(Offset);
6801 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
6802 return ReadStmtFromStream(*Loc.F);
6803}
6804
Richard Smith3cb15722015-08-05 22:41:45 +00006805void ASTReader::FindExternalLexicalDecls(
6806 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
6807 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006808 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
6809
Richard Smith9ccdd932015-08-06 22:14:12 +00006810 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00006811 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
6812 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
6813 auto K = (Decl::Kind)+LexicalDecls[I];
6814 if (!IsKindWeWant(K))
6815 continue;
6816
6817 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
6818
6819 // Don't add predefined declarations to the lexical context more
6820 // than once.
6821 if (ID < NUM_PREDEF_DECL_IDS) {
6822 if (PredefsVisited[ID])
6823 continue;
6824
6825 PredefsVisited[ID] = true;
6826 }
6827
6828 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00006829 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00006830 if (!DC->isDeclInLexicalTraversal(D))
6831 Decls.push_back(D);
6832 }
6833 }
6834 };
6835
6836 if (isa<TranslationUnitDecl>(DC)) {
6837 for (auto Lexical : TULexicalDecls)
6838 Visit(Lexical.first, Lexical.second);
6839 } else {
6840 auto I = LexicalDecls.find(DC);
6841 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00006842 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00006843 }
6844
Guy Benyei11169dd2012-12-18 14:30:41 +00006845 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00006846}
6847
6848namespace {
6849
6850class DeclIDComp {
6851 ASTReader &Reader;
6852 ModuleFile &Mod;
6853
6854public:
6855 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
6856
6857 bool operator()(LocalDeclID L, LocalDeclID R) const {
6858 SourceLocation LHS = getLocation(L);
6859 SourceLocation RHS = getLocation(R);
6860 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6861 }
6862
6863 bool operator()(SourceLocation LHS, LocalDeclID R) const {
6864 SourceLocation RHS = getLocation(R);
6865 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6866 }
6867
6868 bool operator()(LocalDeclID L, SourceLocation RHS) const {
6869 SourceLocation LHS = getLocation(L);
6870 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
6871 }
6872
6873 SourceLocation getLocation(LocalDeclID ID) const {
6874 return Reader.getSourceManager().getFileLoc(
6875 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
6876 }
6877};
6878
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006879} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00006880
6881void ASTReader::FindFileRegionDecls(FileID File,
6882 unsigned Offset, unsigned Length,
6883 SmallVectorImpl<Decl *> &Decls) {
6884 SourceManager &SM = getSourceManager();
6885
6886 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
6887 if (I == FileDeclIDs.end())
6888 return;
6889
6890 FileDeclsInfo &DInfo = I->second;
6891 if (DInfo.Decls.empty())
6892 return;
6893
6894 SourceLocation
6895 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
6896 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
6897
6898 DeclIDComp DIDComp(*this, *DInfo.Mod);
6899 ArrayRef<serialization::LocalDeclID>::iterator
6900 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6901 BeginLoc, DIDComp);
6902 if (BeginIt != DInfo.Decls.begin())
6903 --BeginIt;
6904
6905 // If we are pointing at a top-level decl inside an objc container, we need
6906 // to backtrack until we find it otherwise we will fail to report that the
6907 // region overlaps with an objc container.
6908 while (BeginIt != DInfo.Decls.begin() &&
6909 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
6910 ->isTopLevelDeclInObjCContainer())
6911 --BeginIt;
6912
6913 ArrayRef<serialization::LocalDeclID>::iterator
6914 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
6915 EndLoc, DIDComp);
6916 if (EndIt != DInfo.Decls.end())
6917 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006918
Guy Benyei11169dd2012-12-18 14:30:41 +00006919 for (ArrayRef<serialization::LocalDeclID>::iterator
6920 DIt = BeginIt; DIt != EndIt; ++DIt)
6921 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
6922}
6923
Richard Smith9ce12e32013-02-07 03:30:24 +00006924bool
Guy Benyei11169dd2012-12-18 14:30:41 +00006925ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
6926 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00006927 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00006928 "DeclContext has no visible decls in storage");
6929 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00006930 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00006931
Richard Smithd88a7f12015-09-01 20:35:42 +00006932 auto It = Lookups.find(DC);
6933 if (It == Lookups.end())
6934 return false;
6935
Richard Smith8c913ec2014-08-14 02:21:01 +00006936 Deserializing LookupResults(this);
6937
Richard Smithd88a7f12015-09-01 20:35:42 +00006938 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00006939 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00006940 for (DeclID ID : It->second.Table.find(Name)) {
6941 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6942 if (ND->getDeclName() == Name)
6943 Decls.push_back(ND);
6944 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006945
Guy Benyei11169dd2012-12-18 14:30:41 +00006946 ++NumVisibleDeclContextsRead;
6947 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00006948 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00006949}
6950
Guy Benyei11169dd2012-12-18 14:30:41 +00006951void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
6952 if (!DC->hasExternalVisibleStorage())
6953 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00006954
6955 auto It = Lookups.find(DC);
6956 assert(It != Lookups.end() &&
6957 "have external visible storage but no lookup tables");
6958
Craig Topper79be4cd2013-07-05 04:33:53 +00006959 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006960
Richard Smithd88a7f12015-09-01 20:35:42 +00006961 for (DeclID ID : It->second.Table.findAll()) {
6962 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
6963 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00006964 }
6965
Guy Benyei11169dd2012-12-18 14:30:41 +00006966 ++NumVisibleDeclContextsRead;
6967
Craig Topper79be4cd2013-07-05 04:33:53 +00006968 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006969 SetExternalVisibleDeclsForName(DC, I->first, I->second);
6970 }
6971 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
6972}
6973
Richard Smithd88a7f12015-09-01 20:35:42 +00006974const serialization::reader::DeclContextLookupTable *
6975ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
6976 auto I = Lookups.find(Primary);
6977 return I == Lookups.end() ? nullptr : &I->second;
6978}
6979
Guy Benyei11169dd2012-12-18 14:30:41 +00006980/// \brief Under non-PCH compilation the consumer receives the objc methods
6981/// before receiving the implementation, and codegen depends on this.
6982/// We simulate this by deserializing and passing to consumer the methods of the
6983/// implementation before passing the deserialized implementation decl.
6984static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
6985 ASTConsumer *Consumer) {
6986 assert(ImplD && Consumer);
6987
Aaron Ballmanaff18c02014-03-13 19:03:34 +00006988 for (auto *I : ImplD->methods())
6989 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00006990
6991 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
6992}
6993
6994void ASTReader::PassInterestingDeclsToConsumer() {
6995 assert(Consumer);
Richard Smith04d05b52014-03-23 00:27:18 +00006996
6997 if (PassingDeclsToConsumer)
6998 return;
6999
7000 // Guard variable to avoid recursively redoing the process of passing
7001 // decls to consumer.
7002 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
7003 true);
7004
Richard Smith9e2341d2015-03-23 03:25:59 +00007005 // Ensure that we've loaded all potentially-interesting declarations
7006 // that need to be eagerly loaded.
7007 for (auto ID : EagerlyDeserializedDecls)
7008 GetDecl(ID);
7009 EagerlyDeserializedDecls.clear();
7010
Guy Benyei11169dd2012-12-18 14:30:41 +00007011 while (!InterestingDecls.empty()) {
7012 Decl *D = InterestingDecls.front();
7013 InterestingDecls.pop_front();
7014
7015 PassInterestingDeclToConsumer(D);
7016 }
7017}
7018
7019void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7020 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7021 PassObjCImplDeclToConsumer(ImplD, Consumer);
7022 else
7023 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7024}
7025
7026void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7027 this->Consumer = Consumer;
7028
Richard Smith9e2341d2015-03-23 03:25:59 +00007029 if (Consumer)
7030 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007031
7032 if (DeserializationListener)
7033 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007034}
7035
7036void ASTReader::PrintStats() {
7037 std::fprintf(stderr, "*** AST File Statistics:\n");
7038
7039 unsigned NumTypesLoaded
7040 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7041 QualType());
7042 unsigned NumDeclsLoaded
7043 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007044 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007045 unsigned NumIdentifiersLoaded
7046 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7047 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007048 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007049 unsigned NumMacrosLoaded
7050 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7051 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007052 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007053 unsigned NumSelectorsLoaded
7054 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7055 SelectorsLoaded.end(),
7056 Selector());
7057
7058 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7059 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7060 NumSLocEntriesRead, TotalNumSLocEntries,
7061 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7062 if (!TypesLoaded.empty())
7063 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7064 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7065 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7066 if (!DeclsLoaded.empty())
7067 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7068 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7069 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7070 if (!IdentifiersLoaded.empty())
7071 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7072 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7073 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7074 if (!MacrosLoaded.empty())
7075 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7076 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7077 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7078 if (!SelectorsLoaded.empty())
7079 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7080 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7081 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7082 if (TotalNumStatements)
7083 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7084 NumStatementsRead, TotalNumStatements,
7085 ((float)NumStatementsRead/TotalNumStatements * 100));
7086 if (TotalNumMacros)
7087 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7088 NumMacrosRead, TotalNumMacros,
7089 ((float)NumMacrosRead/TotalNumMacros * 100));
7090 if (TotalLexicalDeclContexts)
7091 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7092 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7093 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7094 * 100));
7095 if (TotalVisibleDeclContexts)
7096 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7097 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7098 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7099 * 100));
7100 if (TotalNumMethodPoolEntries) {
7101 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7102 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7103 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7104 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007105 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007106 if (NumMethodPoolLookups) {
7107 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7108 NumMethodPoolHits, NumMethodPoolLookups,
7109 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7110 }
7111 if (NumMethodPoolTableLookups) {
7112 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7113 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7114 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7115 * 100.0));
7116 }
7117
Douglas Gregor00a50f72013-01-25 00:38:33 +00007118 if (NumIdentifierLookupHits) {
7119 std::fprintf(stderr,
7120 " %u / %u identifier table lookups succeeded (%f%%)\n",
7121 NumIdentifierLookupHits, NumIdentifierLookups,
7122 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7123 }
7124
Douglas Gregore060e572013-01-25 01:03:03 +00007125 if (GlobalIndex) {
7126 std::fprintf(stderr, "\n");
7127 GlobalIndex->printStats();
7128 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007129
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 std::fprintf(stderr, "\n");
7131 dump();
7132 std::fprintf(stderr, "\n");
7133}
7134
7135template<typename Key, typename ModuleFile, unsigned InitialCapacity>
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007136static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007137dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007138 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007139 InitialCapacity> &Map) {
7140 if (Map.begin() == Map.end())
7141 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007142
Guy Benyei11169dd2012-12-18 14:30:41 +00007143 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7144 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007145 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007146 I != IEnd; ++I) {
7147 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7148 << "\n";
7149 }
7150}
7151
Yaron Kerencdae9412016-01-29 19:38:18 +00007152LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007153 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7154 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7155 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7156 dumpModuleIDMap("Global type map", GlobalTypeMap);
7157 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7158 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7159 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7160 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7161 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007162 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007163 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007164
Guy Benyei11169dd2012-12-18 14:30:41 +00007165 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007166 for (ModuleFile &M : ModuleMgr)
7167 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007168}
7169
7170/// Return the amount of memory used by memory buffers, breaking down
7171/// by heap-backed versus mmap'ed memory.
7172void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007173 for (ModuleFile &I : ModuleMgr) {
7174 if (llvm::MemoryBuffer *buf = I.Buffer.get()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007175 size_t bytes = buf->getBufferSize();
7176 switch (buf->getBufferKind()) {
7177 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7178 sizes.malloc_bytes += bytes;
7179 break;
7180 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7181 sizes.mmap_bytes += bytes;
7182 break;
7183 }
7184 }
7185 }
7186}
7187
7188void ASTReader::InitializeSema(Sema &S) {
7189 SemaObj = &S;
7190 S.addExternalSource(this);
7191
7192 // Makes sure any declarations that were deserialized "too early"
7193 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007194 for (uint64_t ID : PreloadedDeclIDs) {
7195 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7196 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007197 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007198 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007199
Richard Smith3d8e97e2013-10-18 06:54:39 +00007200 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007201 if (!FPPragmaOptions.empty()) {
7202 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
7203 SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
7204 }
7205
Yaxun Liu5b746652016-12-18 05:18:55 +00007206 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7207 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7208 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007209
7210 UpdateSema();
7211}
7212
7213void ASTReader::UpdateSema() {
7214 assert(SemaObj && "no Sema to update");
7215
7216 // Load the offsets of the declarations that Sema references.
7217 // They will be lazily deserialized when needed.
7218 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007219 assert(SemaDeclRefs.size() % 3 == 0);
7220 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007221 if (!SemaObj->StdNamespace)
7222 SemaObj->StdNamespace = SemaDeclRefs[I];
7223 if (!SemaObj->StdBadAlloc)
7224 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007225 if (!SemaObj->StdAlignValT)
7226 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007227 }
7228 SemaDeclRefs.clear();
7229 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007230
Nico Weber779355f2016-03-02 23:22:00 +00007231 // Update the state of pragmas. Use the same API as if we had encountered the
7232 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007233 if(OptimizeOffPragmaLocation.isValid())
7234 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007235 if (PragmaMSStructState != -1)
7236 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007237 if (PointersToMembersPragmaLocation.isValid()) {
7238 SemaObj->ActOnPragmaMSPointersToMembers(
7239 (LangOptions::PragmaMSPointersToMembersKind)
7240 PragmaMSPointersToMembersState,
7241 PointersToMembersPragmaLocation);
7242 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007243 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Guy Benyei11169dd2012-12-18 14:30:41 +00007244}
7245
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007246IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007247 // Note that we are loading an identifier.
7248 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007249
Douglas Gregor7211ac12013-01-25 23:32:03 +00007250 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007251 NumIdentifierLookups,
7252 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007253
7254 // We don't need to do identifier table lookups in C++ modules (we preload
7255 // all interesting declarations, and don't need to use the scope for name
7256 // lookups). Perform the lookup in PCH files, though, since we don't build
7257 // a complete initial identifier table if we're carrying on from a PCH.
7258 if (Context.getLangOpts().CPlusPlus) {
7259 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007260 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007261 break;
7262 } else {
7263 // If there is a global index, look there first to determine which modules
7264 // provably do not have any results for this identifier.
7265 GlobalModuleIndex::HitSet Hits;
7266 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7267 if (!loadGlobalIndex()) {
7268 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7269 HitsPtr = &Hits;
7270 }
7271 }
7272
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007273 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007274 }
7275
Guy Benyei11169dd2012-12-18 14:30:41 +00007276 IdentifierInfo *II = Visitor.getIdentifierInfo();
7277 markIdentifierUpToDate(II);
7278 return II;
7279}
7280
7281namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007282
Guy Benyei11169dd2012-12-18 14:30:41 +00007283 /// \brief An identifier-lookup iterator that enumerates all of the
7284 /// identifiers stored within a set of AST files.
7285 class ASTIdentifierIterator : public IdentifierIterator {
7286 /// \brief The AST reader whose identifiers are being enumerated.
7287 const ASTReader &Reader;
7288
7289 /// \brief The current index into the chain of AST files stored in
7290 /// the AST reader.
7291 unsigned Index;
7292
7293 /// \brief The current position within the identifier lookup table
7294 /// of the current AST file.
7295 ASTIdentifierLookupTable::key_iterator Current;
7296
7297 /// \brief The end position within the identifier lookup table of
7298 /// the current AST file.
7299 ASTIdentifierLookupTable::key_iterator End;
7300
Ben Langmuir537c5b52016-05-04 00:53:13 +00007301 /// \brief Whether to skip any modules in the ASTReader.
7302 bool SkipModules;
7303
Guy Benyei11169dd2012-12-18 14:30:41 +00007304 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007305 explicit ASTIdentifierIterator(const ASTReader &Reader,
7306 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007307
Craig Topper3e89dfe2014-03-13 02:13:41 +00007308 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007309 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007310
7311} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007312
Ben Langmuir537c5b52016-05-04 00:53:13 +00007313ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7314 bool SkipModules)
7315 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007316}
7317
7318StringRef ASTIdentifierIterator::Next() {
7319 while (Current == End) {
7320 // If we have exhausted all of our AST files, we're done.
7321 if (Index == 0)
7322 return StringRef();
7323
7324 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007325 ModuleFile &F = Reader.ModuleMgr[Index];
7326 if (SkipModules && F.isModule())
7327 continue;
7328
7329 ASTIdentifierLookupTable *IdTable =
7330 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007331 Current = IdTable->key_begin();
7332 End = IdTable->key_end();
7333 }
7334
7335 // We have any identifiers remaining in the current AST file; return
7336 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007337 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007338 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007339 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007340}
7341
Ben Langmuir537c5b52016-05-04 00:53:13 +00007342namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007343
Ben Langmuir537c5b52016-05-04 00:53:13 +00007344/// A utility for appending two IdentifierIterators.
7345class ChainedIdentifierIterator : public IdentifierIterator {
7346 std::unique_ptr<IdentifierIterator> Current;
7347 std::unique_ptr<IdentifierIterator> Queued;
7348
7349public:
7350 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7351 std::unique_ptr<IdentifierIterator> Second)
7352 : Current(std::move(First)), Queued(std::move(Second)) {}
7353
7354 StringRef Next() override {
7355 if (!Current)
7356 return StringRef();
7357
7358 StringRef result = Current->Next();
7359 if (!result.empty())
7360 return result;
7361
7362 // Try the queued iterator, which may itself be empty.
7363 Current.reset();
7364 std::swap(Current, Queued);
7365 return Next();
7366 }
7367};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007368
Ben Langmuir537c5b52016-05-04 00:53:13 +00007369} // end anonymous namespace.
7370
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007371IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007372 if (!loadGlobalIndex()) {
7373 std::unique_ptr<IdentifierIterator> ReaderIter(
7374 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7375 std::unique_ptr<IdentifierIterator> ModulesIter(
7376 GlobalIndex->createIdentifierIterator());
7377 return new ChainedIdentifierIterator(std::move(ReaderIter),
7378 std::move(ModulesIter));
7379 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007380
Guy Benyei11169dd2012-12-18 14:30:41 +00007381 return new ASTIdentifierIterator(*this);
7382}
7383
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007384namespace clang {
7385namespace serialization {
7386
Guy Benyei11169dd2012-12-18 14:30:41 +00007387 class ReadMethodPoolVisitor {
7388 ASTReader &Reader;
7389 Selector Sel;
7390 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007391 unsigned InstanceBits;
7392 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007393 bool InstanceHasMoreThanOneDecl;
7394 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007395 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7396 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007397
7398 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007399 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007400 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007401 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007402 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7403 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007404
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007405 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007406 if (!M.SelectorLookupTable)
7407 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007408
Guy Benyei11169dd2012-12-18 14:30:41 +00007409 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007410 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007411 return true;
7412
Richard Smithbdf2d932015-07-30 03:37:16 +00007413 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 ASTSelectorLookupTable *PoolTable
7415 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007416 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 if (Pos == PoolTable->end())
7418 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007419
Richard Smithbdf2d932015-07-30 03:37:16 +00007420 ++Reader.NumMethodPoolTableHits;
7421 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007422 // FIXME: Not quite happy with the statistics here. We probably should
7423 // disable this tracking when called via LoadSelector.
7424 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007425 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007426 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007427 if (Reader.DeserializationListener)
7428 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007429
Richard Smithbdf2d932015-07-30 03:37:16 +00007430 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7431 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7432 InstanceBits = Data.InstanceBits;
7433 FactoryBits = Data.FactoryBits;
7434 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7435 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007436 return true;
7437 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007438
Guy Benyei11169dd2012-12-18 14:30:41 +00007439 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007440 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7441 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007442 }
7443
7444 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007445 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007446 return FactoryMethods;
7447 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007448
7449 unsigned getInstanceBits() const { return InstanceBits; }
7450 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007451 bool instanceHasMoreThanOneDecl() const {
7452 return InstanceHasMoreThanOneDecl;
7453 }
7454 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007455 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007456
7457} // end namespace serialization
7458} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007459
7460/// \brief Add the given set of methods to the method list.
7461static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7462 ObjCMethodList &List) {
7463 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7464 S.addMethodToGlobalList(&List, Methods[I]);
7465 }
7466}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007467
Guy Benyei11169dd2012-12-18 14:30:41 +00007468void ASTReader::ReadMethodPool(Selector Sel) {
7469 // Get the selector generation and update it to the current generation.
7470 unsigned &Generation = SelectorGeneration[Sel];
7471 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007472 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007473 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007474
Guy Benyei11169dd2012-12-18 14:30:41 +00007475 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007476 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007478 ModuleMgr.visit(Visitor);
7479
Guy Benyei11169dd2012-12-18 14:30:41 +00007480 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007481 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007482 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007483
7484 ++NumMethodPoolHits;
7485
Guy Benyei11169dd2012-12-18 14:30:41 +00007486 if (!getSema())
7487 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007488
Guy Benyei11169dd2012-12-18 14:30:41 +00007489 Sema &S = *getSema();
7490 Sema::GlobalMethodPool::iterator Pos
7491 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007492
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007493 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007494 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007495 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007496 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007497
7498 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7499 // when building a module we keep every method individually and may need to
7500 // update hasMoreThanOneDecl as we add the methods.
7501 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7502 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007503}
7504
Manman Rena0f31a02016-04-29 19:04:05 +00007505void ASTReader::updateOutOfDateSelector(Selector Sel) {
7506 if (SelectorOutOfDate[Sel])
7507 ReadMethodPool(Sel);
7508}
7509
Guy Benyei11169dd2012-12-18 14:30:41 +00007510void ASTReader::ReadKnownNamespaces(
7511 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7512 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007513
Guy Benyei11169dd2012-12-18 14:30:41 +00007514 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007515 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007516 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7517 Namespaces.push_back(Namespace);
7518 }
7519}
7520
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007521void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007522 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007523 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7524 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007525 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007526 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007527 Undefined.insert(std::make_pair(D, Loc));
7528 }
7529}
Nick Lewycky8334af82013-01-26 00:35:08 +00007530
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007531void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7532 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7533 Exprs) {
7534 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7535 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7536 uint64_t Count = DelayedDeleteExprs[Idx++];
7537 for (uint64_t C = 0; C < Count; ++C) {
7538 SourceLocation DeleteLoc =
7539 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7540 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7541 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7542 }
7543 }
7544}
7545
Guy Benyei11169dd2012-12-18 14:30:41 +00007546void ASTReader::ReadTentativeDefinitions(
7547 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7548 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7549 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7550 if (Var)
7551 TentativeDefs.push_back(Var);
7552 }
7553 TentativeDefinitions.clear();
7554}
7555
7556void ASTReader::ReadUnusedFileScopedDecls(
7557 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7558 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7559 DeclaratorDecl *D
7560 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7561 if (D)
7562 Decls.push_back(D);
7563 }
7564 UnusedFileScopedDecls.clear();
7565}
7566
7567void ASTReader::ReadDelegatingConstructors(
7568 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7569 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7570 CXXConstructorDecl *D
7571 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7572 if (D)
7573 Decls.push_back(D);
7574 }
7575 DelegatingCtorDecls.clear();
7576}
7577
7578void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7579 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7580 TypedefNameDecl *D
7581 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7582 if (D)
7583 Decls.push_back(D);
7584 }
7585 ExtVectorDecls.clear();
7586}
7587
Nico Weber72889432014-09-06 01:25:55 +00007588void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7589 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7590 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7591 ++I) {
7592 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7593 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7594 if (D)
7595 Decls.insert(D);
7596 }
7597 UnusedLocalTypedefNameCandidates.clear();
7598}
7599
Guy Benyei11169dd2012-12-18 14:30:41 +00007600void ASTReader::ReadReferencedSelectors(
7601 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7602 if (ReferencedSelectorsData.empty())
7603 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007604
Guy Benyei11169dd2012-12-18 14:30:41 +00007605 // If there are @selector references added them to its pool. This is for
7606 // implementation of -Wselector.
7607 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7608 unsigned I = 0;
7609 while (I < DataSize) {
7610 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7611 SourceLocation SelLoc
7612 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7613 Sels.push_back(std::make_pair(Sel, SelLoc));
7614 }
7615 ReferencedSelectorsData.clear();
7616}
7617
7618void ASTReader::ReadWeakUndeclaredIdentifiers(
7619 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7620 if (WeakUndeclaredIdentifiers.empty())
7621 return;
7622
7623 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007624 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007625 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007626 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007627 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7628 SourceLocation Loc
7629 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7630 bool Used = WeakUndeclaredIdentifiers[I++];
7631 WeakInfo WI(AliasId, Loc);
7632 WI.setUsed(Used);
7633 WeakIDs.push_back(std::make_pair(WeakId, WI));
7634 }
7635 WeakUndeclaredIdentifiers.clear();
7636}
7637
7638void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7639 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7640 ExternalVTableUse VT;
7641 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7642 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7643 VT.DefinitionRequired = VTableUses[Idx++];
7644 VTables.push_back(VT);
7645 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007646
Guy Benyei11169dd2012-12-18 14:30:41 +00007647 VTableUses.clear();
7648}
7649
7650void ASTReader::ReadPendingInstantiations(
7651 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7652 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7653 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7654 SourceLocation Loc
7655 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7656
7657 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007658 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007659 PendingInstantiations.clear();
7660}
7661
Richard Smithe40f2ba2013-08-07 21:41:30 +00007662void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007663 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7664 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007665 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7666 /* In loop */) {
7667 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7668
Justin Lebar28f09c52016-10-10 16:26:08 +00007669 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007670 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7671
7672 ModuleFile *F = getOwningModuleFile(LT->D);
7673 assert(F && "No module");
7674
7675 unsigned TokN = LateParsedTemplates[Idx++];
7676 LT->Toks.reserve(TokN);
7677 for (unsigned T = 0; T < TokN; ++T)
7678 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7679
Justin Lebar28f09c52016-10-10 16:26:08 +00007680 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007681 }
7682
7683 LateParsedTemplates.clear();
7684}
7685
Guy Benyei11169dd2012-12-18 14:30:41 +00007686void ASTReader::LoadSelector(Selector Sel) {
7687 // It would be complicated to avoid reading the methods anyway. So don't.
7688 ReadMethodPool(Sel);
7689}
7690
7691void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
7692 assert(ID && "Non-zero identifier ID required");
7693 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
7694 IdentifiersLoaded[ID - 1] = II;
7695 if (DeserializationListener)
7696 DeserializationListener->IdentifierRead(ID, II);
7697}
7698
7699/// \brief Set the globally-visible declarations associated with the given
7700/// identifier.
7701///
7702/// If the AST reader is currently in a state where the given declaration IDs
7703/// cannot safely be resolved, they are queued until it is safe to resolve
7704/// them.
7705///
7706/// \param II an IdentifierInfo that refers to one or more globally-visible
7707/// declarations.
7708///
7709/// \param DeclIDs the set of declaration IDs with the name @p II that are
7710/// visible at global scope.
7711///
Douglas Gregor6168bd22013-02-18 15:53:43 +00007712/// \param Decls if non-null, this vector will be populated with the set of
7713/// deserialized declarations. These declarations will not be pushed into
7714/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00007715void
7716ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
7717 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00007718 SmallVectorImpl<Decl *> *Decls) {
7719 if (NumCurrentElementsDeserializing && !Decls) {
7720 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 return;
7722 }
7723
7724 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00007725 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 // Queue this declaration so that it will be added to the
7727 // translation unit scope and identifier's declaration chain
7728 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00007729 PreloadedDeclIDs.push_back(DeclIDs[I]);
7730 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00007731 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007732
7733 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
7734
7735 // If we're simply supposed to record the declarations, do so now.
7736 if (Decls) {
7737 Decls->push_back(D);
7738 continue;
7739 }
7740
7741 // Introduce this declaration into the translation-unit scope
7742 // and add it to the declaration chain for this identifier, so
7743 // that (unqualified) name lookup will find it.
7744 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007745 }
7746}
7747
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007748IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007749 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007750 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007751
7752 if (IdentifiersLoaded.empty()) {
7753 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007754 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007755 }
7756
7757 ID -= 1;
7758 if (!IdentifiersLoaded[ID]) {
7759 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
7760 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
7761 ModuleFile *M = I->second;
7762 unsigned Index = ID - M->BaseIdentifierID;
7763 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
7764
7765 // All of the strings in the AST file are preceded by a 16-bit length.
7766 // Extract that 16-bit length to avoid having to execute strlen().
7767 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
7768 // unsigned integers. This is important to avoid integer overflow when
7769 // we cast them to 'unsigned'.
7770 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
7771 unsigned StrLen = (((unsigned) StrLenPtr[0])
7772 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00007773 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
7774 IdentifiersLoaded[ID] = &II;
7775 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007776 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00007777 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00007778 }
7779
7780 return IdentifiersLoaded[ID];
7781}
7782
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007783IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
7784 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00007785}
7786
7787IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
7788 if (LocalID < NUM_PREDEF_IDENT_IDS)
7789 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007790
Guy Benyei11169dd2012-12-18 14:30:41 +00007791 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7792 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007793 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007795
Guy Benyei11169dd2012-12-18 14:30:41 +00007796 return LocalID + I->second;
7797}
7798
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007799MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007800 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00007801 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007802
7803 if (MacrosLoaded.empty()) {
7804 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007805 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007806 }
7807
7808 ID -= NUM_PREDEF_MACRO_IDS;
7809 if (!MacrosLoaded[ID]) {
7810 GlobalMacroMapType::iterator I
7811 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
7812 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
7813 ModuleFile *M = I->second;
7814 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007815 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007816
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00007817 if (DeserializationListener)
7818 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
7819 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007820 }
7821
7822 return MacrosLoaded[ID];
7823}
7824
7825MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
7826 if (LocalID < NUM_PREDEF_MACRO_IDS)
7827 return LocalID;
7828
7829 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7830 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
7831 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
7832
7833 return LocalID + I->second;
7834}
7835
7836serialization::SubmoduleID
7837ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
7838 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
7839 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007840
Guy Benyei11169dd2012-12-18 14:30:41 +00007841 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7842 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007843 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007844 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007845
Guy Benyei11169dd2012-12-18 14:30:41 +00007846 return LocalID + I->second;
7847}
7848
7849Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
7850 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
7851 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00007852 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007853 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007854
Guy Benyei11169dd2012-12-18 14:30:41 +00007855 if (GlobalID > SubmodulesLoaded.size()) {
7856 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007857 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007858 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007859
Guy Benyei11169dd2012-12-18 14:30:41 +00007860 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
7861}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00007862
7863Module *ASTReader::getModule(unsigned ID) {
7864 return getSubmodule(ID);
7865}
7866
Richard Smithd88a7f12015-09-01 20:35:42 +00007867ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
7868 if (ID & 1) {
7869 // It's a module, look it up by submodule ID.
7870 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
7871 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
7872 } else {
7873 // It's a prefix (preamble, PCH, ...). Look it up by index.
7874 unsigned IndexFromEnd = ID >> 1;
7875 assert(IndexFromEnd && "got reference to unknown module file");
7876 return getModuleManager().pch_modules().end()[-IndexFromEnd];
7877 }
7878}
7879
7880unsigned ASTReader::getModuleFileID(ModuleFile *F) {
7881 if (!F)
7882 return 1;
7883
7884 // For a file representing a module, use the submodule ID of the top-level
7885 // module as the file ID. For any other kind of file, the number of such
7886 // files loaded beforehand will be the same on reload.
7887 // FIXME: Is this true even if we have an explicit module file and a PCH?
7888 if (F->isModule())
7889 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
7890
7891 auto PCHModules = getModuleManager().pch_modules();
7892 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
7893 assert(I != PCHModules.end() && "emitting reference to unknown file");
7894 return (I - PCHModules.end()) << 1;
7895}
7896
Adrian Prantl15bcf702015-06-30 17:39:43 +00007897llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
7898ASTReader::getSourceDescriptor(unsigned ID) {
7899 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00007900 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007901
7902 // If there is only a single PCH, return it instead.
7903 // Chained PCH are not suported.
7904 if (ModuleMgr.size() == 1) {
7905 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00007906 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00007907 StringRef FileName = llvm::sys::path::filename(MF.FileName);
7908 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
7909 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00007910 }
7911 return None;
7912}
7913
David Blaikie9ffe5a32017-01-30 05:00:26 +00007914ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(unsigned ID) {
7915 const Module *M = getSubmodule(ID);
7916 if (!M || !M->WithCodegen)
7917 return EK_ReplyHazy;
7918
7919 ModuleFile *MF = ModuleMgr.lookup(M->getASTFile());
7920 assert(MF); // ?
7921 if (MF->Kind == ModuleKind::MK_MainFile)
7922 return EK_Never;
7923 return EK_Always;
7924}
7925
Guy Benyei11169dd2012-12-18 14:30:41 +00007926Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
7927 return DecodeSelector(getGlobalSelectorID(M, LocalID));
7928}
7929
7930Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
7931 if (ID == 0)
7932 return Selector();
7933
7934 if (ID > SelectorsLoaded.size()) {
7935 Error("selector ID out of range in AST file");
7936 return Selector();
7937 }
7938
Craig Toppera13603a2014-05-22 05:54:18 +00007939 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007940 // Load this selector from the selector table.
7941 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
7942 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
7943 ModuleFile &M = *I->second;
7944 ASTSelectorLookupTrait Trait(*this, M);
7945 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
7946 SelectorsLoaded[ID - 1] =
7947 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
7948 if (DeserializationListener)
7949 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
7950 }
7951
7952 return SelectorsLoaded[ID - 1];
7953}
7954
7955Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
7956 return DecodeSelector(ID);
7957}
7958
7959uint32_t ASTReader::GetNumExternalSelectors() {
7960 // ID 0 (the null selector) is considered an external selector.
7961 return getTotalNumSelectors() + 1;
7962}
7963
7964serialization::SelectorID
7965ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
7966 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
7967 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007968
Guy Benyei11169dd2012-12-18 14:30:41 +00007969 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7970 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007971 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00007972 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007973
Guy Benyei11169dd2012-12-18 14:30:41 +00007974 return LocalID + I->second;
7975}
7976
7977DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007978ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007979 const RecordData &Record, unsigned &Idx) {
7980 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
7981 switch (Kind) {
7982 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00007983 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00007984
7985 case DeclarationName::ObjCZeroArgSelector:
7986 case DeclarationName::ObjCOneArgSelector:
7987 case DeclarationName::ObjCMultiArgSelector:
7988 return DeclarationName(ReadSelector(F, Record, Idx));
7989
7990 case DeclarationName::CXXConstructorName:
7991 return Context.DeclarationNames.getCXXConstructorName(
7992 Context.getCanonicalType(readType(F, Record, Idx)));
7993
7994 case DeclarationName::CXXDestructorName:
7995 return Context.DeclarationNames.getCXXDestructorName(
7996 Context.getCanonicalType(readType(F, Record, Idx)));
7997
Richard Smith35845152017-02-07 01:37:30 +00007998 case DeclarationName::CXXDeductionGuideName:
7999 return Context.DeclarationNames.getCXXDeductionGuideName(
8000 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8001
Guy Benyei11169dd2012-12-18 14:30:41 +00008002 case DeclarationName::CXXConversionFunctionName:
8003 return Context.DeclarationNames.getCXXConversionFunctionName(
8004 Context.getCanonicalType(readType(F, Record, Idx)));
8005
8006 case DeclarationName::CXXOperatorName:
8007 return Context.DeclarationNames.getCXXOperatorName(
8008 (OverloadedOperatorKind)Record[Idx++]);
8009
8010 case DeclarationName::CXXLiteralOperatorName:
8011 return Context.DeclarationNames.getCXXLiteralOperatorName(
8012 GetIdentifierInfo(F, Record, Idx));
8013
8014 case DeclarationName::CXXUsingDirective:
8015 return DeclarationName::getUsingDirectiveName();
8016 }
8017
8018 llvm_unreachable("Invalid NameKind!");
8019}
8020
8021void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8022 DeclarationNameLoc &DNLoc,
8023 DeclarationName Name,
8024 const RecordData &Record, unsigned &Idx) {
8025 switch (Name.getNameKind()) {
8026 case DeclarationName::CXXConstructorName:
8027 case DeclarationName::CXXDestructorName:
8028 case DeclarationName::CXXConversionFunctionName:
8029 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8030 break;
8031
8032 case DeclarationName::CXXOperatorName:
8033 DNLoc.CXXOperatorName.BeginOpNameLoc
8034 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8035 DNLoc.CXXOperatorName.EndOpNameLoc
8036 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8037 break;
8038
8039 case DeclarationName::CXXLiteralOperatorName:
8040 DNLoc.CXXLiteralOperatorName.OpNameLoc
8041 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8042 break;
8043
8044 case DeclarationName::Identifier:
8045 case DeclarationName::ObjCZeroArgSelector:
8046 case DeclarationName::ObjCOneArgSelector:
8047 case DeclarationName::ObjCMultiArgSelector:
8048 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008049 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008050 break;
8051 }
8052}
8053
8054void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8055 DeclarationNameInfo &NameInfo,
8056 const RecordData &Record, unsigned &Idx) {
8057 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8058 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8059 DeclarationNameLoc DNLoc;
8060 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8061 NameInfo.setInfo(DNLoc);
8062}
8063
8064void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8065 const RecordData &Record, unsigned &Idx) {
8066 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8067 unsigned NumTPLists = Record[Idx++];
8068 Info.NumTemplParamLists = NumTPLists;
8069 if (NumTPLists) {
8070 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008071 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008072 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8073 }
8074}
8075
8076TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008077ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008078 unsigned &Idx) {
8079 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8080 switch (Kind) {
8081 case TemplateName::Template:
8082 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8083
8084 case TemplateName::OverloadedTemplate: {
8085 unsigned size = Record[Idx++];
8086 UnresolvedSet<8> Decls;
8087 while (size--)
8088 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8089
8090 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8091 }
8092
8093 case TemplateName::QualifiedTemplate: {
8094 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8095 bool hasTemplKeyword = Record[Idx++];
8096 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8097 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8098 }
8099
8100 case TemplateName::DependentTemplate: {
8101 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8102 if (Record[Idx++]) // isIdentifier
8103 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008104 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008105 Idx));
8106 return Context.getDependentTemplateName(NNS,
8107 (OverloadedOperatorKind)Record[Idx++]);
8108 }
8109
8110 case TemplateName::SubstTemplateTemplateParm: {
8111 TemplateTemplateParmDecl *param
8112 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8113 if (!param) return TemplateName();
8114 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8115 return Context.getSubstTemplateTemplateParm(param, replacement);
8116 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008117
Guy Benyei11169dd2012-12-18 14:30:41 +00008118 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008119 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008120 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8121 if (!Param)
8122 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008123
Guy Benyei11169dd2012-12-18 14:30:41 +00008124 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8125 if (ArgPack.getKind() != TemplateArgument::Pack)
8126 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008127
Guy Benyei11169dd2012-12-18 14:30:41 +00008128 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8129 }
8130 }
8131
8132 llvm_unreachable("Unhandled template name kind!");
8133}
8134
Richard Smith2bb3c342015-08-09 01:05:31 +00008135TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8136 const RecordData &Record,
8137 unsigned &Idx,
8138 bool Canonicalize) {
8139 if (Canonicalize) {
8140 // The caller wants a canonical template argument. Sometimes the AST only
8141 // wants template arguments in canonical form (particularly as the template
8142 // argument lists of template specializations) so ensure we preserve that
8143 // canonical form across serialization.
8144 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8145 return Context.getCanonicalTemplateArgument(Arg);
8146 }
8147
Guy Benyei11169dd2012-12-18 14:30:41 +00008148 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8149 switch (Kind) {
8150 case TemplateArgument::Null:
8151 return TemplateArgument();
8152 case TemplateArgument::Type:
8153 return TemplateArgument(readType(F, Record, Idx));
8154 case TemplateArgument::Declaration: {
8155 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008156 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008157 }
8158 case TemplateArgument::NullPtr:
8159 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8160 case TemplateArgument::Integral: {
8161 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8162 QualType T = readType(F, Record, Idx);
8163 return TemplateArgument(Context, Value, T);
8164 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008165 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008166 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8167 case TemplateArgument::TemplateExpansion: {
8168 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008169 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008170 if (unsigned NumExpansions = Record[Idx++])
8171 NumTemplateExpansions = NumExpansions - 1;
8172 return TemplateArgument(Name, NumTemplateExpansions);
8173 }
8174 case TemplateArgument::Expression:
8175 return TemplateArgument(ReadExpr(F));
8176 case TemplateArgument::Pack: {
8177 unsigned NumArgs = Record[Idx++];
8178 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8179 for (unsigned I = 0; I != NumArgs; ++I)
8180 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008181 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008182 }
8183 }
8184
8185 llvm_unreachable("Unhandled template argument kind!");
8186}
8187
8188TemplateParameterList *
8189ASTReader::ReadTemplateParameterList(ModuleFile &F,
8190 const RecordData &Record, unsigned &Idx) {
8191 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8192 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8193 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8194
8195 unsigned NumParams = Record[Idx++];
8196 SmallVector<NamedDecl *, 16> Params;
8197 Params.reserve(NumParams);
8198 while (NumParams--)
8199 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8200
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008201 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008202 TemplateParameterList* TemplateParams =
8203 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008204 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008205 return TemplateParams;
8206}
8207
8208void
8209ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008210ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008211 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008212 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008213 unsigned NumTemplateArgs = Record[Idx++];
8214 TemplArgs.reserve(NumTemplateArgs);
8215 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008216 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008217}
8218
8219/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008220void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008221 const RecordData &Record, unsigned &Idx) {
8222 unsigned NumDecls = Record[Idx++];
8223 Set.reserve(Context, NumDecls);
8224 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008225 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008226 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008227 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008228 }
8229}
8230
8231CXXBaseSpecifier
8232ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8233 const RecordData &Record, unsigned &Idx) {
8234 bool isVirtual = static_cast<bool>(Record[Idx++]);
8235 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8236 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8237 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8238 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8239 SourceRange Range = ReadSourceRange(F, Record, Idx);
8240 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008241 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008242 EllipsisLoc);
8243 Result.setInheritConstructors(inheritConstructors);
8244 return Result;
8245}
8246
Richard Smithc2bb8182015-03-24 06:36:48 +00008247CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008248ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8249 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008250 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008251 assert(NumInitializers && "wrote ctor initializers but have no inits");
8252 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8253 for (unsigned i = 0; i != NumInitializers; ++i) {
8254 TypeSourceInfo *TInfo = nullptr;
8255 bool IsBaseVirtual = false;
8256 FieldDecl *Member = nullptr;
8257 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008258
Richard Smithc2bb8182015-03-24 06:36:48 +00008259 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8260 switch (Type) {
8261 case CTOR_INITIALIZER_BASE:
8262 TInfo = GetTypeSourceInfo(F, Record, Idx);
8263 IsBaseVirtual = Record[Idx++];
8264 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008265
Richard Smithc2bb8182015-03-24 06:36:48 +00008266 case CTOR_INITIALIZER_DELEGATING:
8267 TInfo = GetTypeSourceInfo(F, Record, Idx);
8268 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008269
Richard Smithc2bb8182015-03-24 06:36:48 +00008270 case CTOR_INITIALIZER_MEMBER:
8271 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8272 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008273
Richard Smithc2bb8182015-03-24 06:36:48 +00008274 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8275 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8276 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008277 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008278
8279 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8280 Expr *Init = ReadExpr(F);
8281 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8282 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008283
8284 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008285 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008286 BOMInit = new (Context)
8287 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8288 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008289 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008290 BOMInit = new (Context)
8291 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008292 else if (Member)
8293 BOMInit = new (Context)
8294 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8295 Init, RParenLoc);
8296 else
8297 BOMInit = new (Context)
8298 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8299 LParenLoc, Init, RParenLoc);
8300
Richard Smith418ed822016-12-14 19:45:03 +00008301 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008302 unsigned SourceOrder = Record[Idx++];
8303 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008304 }
8305
Richard Smithc2bb8182015-03-24 06:36:48 +00008306 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008307 }
8308
Richard Smithc2bb8182015-03-24 06:36:48 +00008309 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008310}
8311
8312NestedNameSpecifier *
8313ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8314 const RecordData &Record, unsigned &Idx) {
8315 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008316 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008317 for (unsigned I = 0; I != N; ++I) {
8318 NestedNameSpecifier::SpecifierKind Kind
8319 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8320 switch (Kind) {
8321 case NestedNameSpecifier::Identifier: {
8322 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8323 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8324 break;
8325 }
8326
8327 case NestedNameSpecifier::Namespace: {
8328 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8329 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8330 break;
8331 }
8332
8333 case NestedNameSpecifier::NamespaceAlias: {
8334 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8335 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8336 break;
8337 }
8338
8339 case NestedNameSpecifier::TypeSpec:
8340 case NestedNameSpecifier::TypeSpecWithTemplate: {
8341 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8342 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008343 return nullptr;
8344
Guy Benyei11169dd2012-12-18 14:30:41 +00008345 bool Template = Record[Idx++];
8346 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8347 break;
8348 }
8349
8350 case NestedNameSpecifier::Global: {
8351 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8352 // No associated value, and there can't be a prefix.
8353 break;
8354 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008355
8356 case NestedNameSpecifier::Super: {
8357 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8358 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8359 break;
8360 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008361 }
8362 Prev = NNS;
8363 }
8364 return NNS;
8365}
8366
8367NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008368ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008369 unsigned &Idx) {
8370 unsigned N = Record[Idx++];
8371 NestedNameSpecifierLocBuilder Builder;
8372 for (unsigned I = 0; I != N; ++I) {
8373 NestedNameSpecifier::SpecifierKind Kind
8374 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8375 switch (Kind) {
8376 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008377 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 SourceRange Range = ReadSourceRange(F, Record, Idx);
8379 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8380 break;
8381 }
8382
8383 case NestedNameSpecifier::Namespace: {
8384 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8385 SourceRange Range = ReadSourceRange(F, Record, Idx);
8386 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8387 break;
8388 }
8389
8390 case NestedNameSpecifier::NamespaceAlias: {
8391 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8392 SourceRange Range = ReadSourceRange(F, Record, Idx);
8393 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8394 break;
8395 }
8396
8397 case NestedNameSpecifier::TypeSpec:
8398 case NestedNameSpecifier::TypeSpecWithTemplate: {
8399 bool Template = Record[Idx++];
8400 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8401 if (!T)
8402 return NestedNameSpecifierLoc();
8403 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8404
8405 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008406 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008407 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8408 T->getTypeLoc(), ColonColonLoc);
8409 break;
8410 }
8411
8412 case NestedNameSpecifier::Global: {
8413 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8414 Builder.MakeGlobal(Context, ColonColonLoc);
8415 break;
8416 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008417
8418 case NestedNameSpecifier::Super: {
8419 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8420 SourceRange Range = ReadSourceRange(F, Record, Idx);
8421 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8422 break;
8423 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008424 }
8425 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008426
Guy Benyei11169dd2012-12-18 14:30:41 +00008427 return Builder.getWithLocInContext(Context);
8428}
8429
8430SourceRange
8431ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8432 unsigned &Idx) {
8433 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8434 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8435 return SourceRange(beg, end);
8436}
8437
8438/// \brief Read an integral value
8439llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8440 unsigned BitWidth = Record[Idx++];
8441 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8442 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8443 Idx += NumWords;
8444 return Result;
8445}
8446
8447/// \brief Read a signed integral value
8448llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8449 bool isUnsigned = Record[Idx++];
8450 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8451}
8452
8453/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008454llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8455 const llvm::fltSemantics &Sem,
8456 unsigned &Idx) {
8457 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008458}
8459
8460// \brief Read a string
8461std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8462 unsigned Len = Record[Idx++];
8463 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8464 Idx += Len;
8465 return Result;
8466}
8467
Richard Smith7ed1bc92014-12-05 22:42:13 +00008468std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8469 unsigned &Idx) {
8470 std::string Filename = ReadString(Record, Idx);
8471 ResolveImportedPath(F, Filename);
8472 return Filename;
8473}
8474
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008475VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008476 unsigned &Idx) {
8477 unsigned Major = Record[Idx++];
8478 unsigned Minor = Record[Idx++];
8479 unsigned Subminor = Record[Idx++];
8480 if (Minor == 0)
8481 return VersionTuple(Major);
8482 if (Subminor == 0)
8483 return VersionTuple(Major, Minor - 1);
8484 return VersionTuple(Major, Minor - 1, Subminor - 1);
8485}
8486
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008487CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008488 const RecordData &Record,
8489 unsigned &Idx) {
8490 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8491 return CXXTemporary::Create(Context, Decl);
8492}
8493
8494DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008495 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008496}
8497
8498DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
8499 return Diags.Report(Loc, DiagID);
8500}
8501
8502/// \brief Retrieve the identifier table associated with the
8503/// preprocessor.
8504IdentifierTable &ASTReader::getIdentifierTable() {
8505 return PP.getIdentifierTable();
8506}
8507
8508/// \brief Record that the given ID maps to the given switch-case
8509/// statement.
8510void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008511 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008512 "Already have a SwitchCase with this ID");
8513 (*CurrSwitchCaseStmts)[ID] = SC;
8514}
8515
8516/// \brief Retrieve the switch-case statement with the given ID.
8517SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008518 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008519 return (*CurrSwitchCaseStmts)[ID];
8520}
8521
8522void ASTReader::ClearSwitchCaseIDs() {
8523 CurrSwitchCaseStmts->clear();
8524}
8525
8526void ASTReader::ReadComments() {
8527 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008528 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008529 serialization::ModuleFile *> >::iterator
8530 I = CommentsCursors.begin(),
8531 E = CommentsCursors.end();
8532 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008533 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008534 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008535 serialization::ModuleFile &F = *I->second;
8536 SavedStreamPosition SavedPosition(Cursor);
8537
8538 RecordData Record;
8539 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008540 llvm::BitstreamEntry Entry =
8541 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008542
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008543 switch (Entry.Kind) {
8544 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8545 case llvm::BitstreamEntry::Error:
8546 Error("malformed block record in AST file");
8547 return;
8548 case llvm::BitstreamEntry::EndBlock:
8549 goto NextCursor;
8550 case llvm::BitstreamEntry::Record:
8551 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008552 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008553 }
8554
8555 // Read a record.
8556 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008557 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008558 case COMMENTS_RAW_COMMENT: {
8559 unsigned Idx = 0;
8560 SourceRange SR = ReadSourceRange(F, Record, Idx);
8561 RawComment::CommentKind Kind =
8562 (RawComment::CommentKind) Record[Idx++];
8563 bool IsTrailingComment = Record[Idx++];
8564 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008565 Comments.push_back(new (Context) RawComment(
8566 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8567 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008568 break;
8569 }
8570 }
8571 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008572 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008573 // De-serialized SourceLocations get negative FileIDs for other modules,
8574 // potentially invalidating the original order. Sort it again.
8575 std::sort(Comments.begin(), Comments.end(),
8576 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008577 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008578 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008579}
8580
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008581void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8582 bool IncludeSystem, bool Complain,
8583 llvm::function_ref<void(const serialization::InputFile &IF,
8584 bool isSystem)> Visitor) {
8585 unsigned NumUserInputs = MF.NumUserInputFiles;
8586 unsigned NumInputs = MF.InputFilesLoaded.size();
8587 assert(NumUserInputs <= NumInputs);
8588 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8589 for (unsigned I = 0; I < N; ++I) {
8590 bool IsSystem = I >= NumUserInputs;
8591 InputFile IF = getInputFile(MF, I+1, Complain);
8592 Visitor(IF, IsSystem);
8593 }
8594}
8595
Richard Smithcd45dbc2014-04-19 03:48:30 +00008596std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8597 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008598 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008599 return M->getFullModuleName();
8600
8601 // Otherwise, use the name of the top-level module the decl is within.
8602 if (ModuleFile *M = getOwningModuleFile(D))
8603 return M->ModuleName;
8604
8605 // Not from a module.
8606 return "";
8607}
8608
Guy Benyei11169dd2012-12-18 14:30:41 +00008609void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008610 while (!PendingIdentifierInfos.empty() ||
8611 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008612 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008613 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008614 // If any identifiers with corresponding top-level declarations have
8615 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008616 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8617 TopLevelDeclsMap;
8618 TopLevelDeclsMap TopLevelDecls;
8619
Guy Benyei11169dd2012-12-18 14:30:41 +00008620 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008621 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008622 SmallVector<uint32_t, 4> DeclIDs =
8623 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008624 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008625
8626 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008628
Richard Smith851072e2014-05-19 20:59:20 +00008629 // For each decl chain that we wanted to complete while deserializing, mark
8630 // it as "still needs to be completed".
8631 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8632 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8633 }
8634 PendingIncompleteDeclChains.clear();
8635
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008637 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008638 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008639 PendingDeclChains.clear();
8640
Douglas Gregor6168bd22013-02-18 15:53:43 +00008641 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008642 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8643 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008644 IdentifierInfo *II = TLD->first;
8645 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008646 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008647 }
8648 }
8649
Guy Benyei11169dd2012-12-18 14:30:41 +00008650 // Load any pending macro definitions.
8651 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008652 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8653 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8654 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8655 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008656 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008657 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008658 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008659 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008660 resolvePendingMacro(II, Info);
8661 }
8662 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008663 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008664 ++IDIdx) {
8665 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008666 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008667 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008668 }
8669 }
8670 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008671
8672 // Wire up the DeclContexts for Decls that we delayed setting until
8673 // recursive loading is completed.
8674 while (!PendingDeclContextInfos.empty()) {
8675 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8676 PendingDeclContextInfos.pop_front();
8677 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8678 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8679 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
8680 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00008681
Richard Smithd1c46742014-04-30 02:24:17 +00008682 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00008683 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00008684 auto Update = PendingUpdateRecords.pop_back_val();
8685 ReadingKindTracker ReadingKind(Read_Decl, *this);
8686 loadDeclUpdateRecords(Update.first, Update.second);
8687 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008688 }
Richard Smith8a639892015-01-24 01:07:20 +00008689
8690 // At this point, all update records for loaded decls are in place, so any
8691 // fake class definitions should have become real.
8692 assert(PendingFakeDefinitionData.empty() &&
8693 "faked up a class definition but never saw the real one");
8694
Guy Benyei11169dd2012-12-18 14:30:41 +00008695 // If we deserialized any C++ or Objective-C class definitions, any
8696 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008697 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00008698 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00008699 for (Decl *D : PendingDefinitions) {
8700 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00008701 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008702 // Make sure that the TagType points at the definition.
8703 const_cast<TagType*>(TagT)->decl = TD;
8704 }
Richard Smith8ce51082015-03-11 01:44:51 +00008705
Craig Topperc6914d02014-08-25 04:15:02 +00008706 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008707 for (auto *R = getMostRecentExistingDecl(RD); R;
8708 R = R->getPreviousDecl()) {
8709 assert((R == D) ==
8710 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00008711 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00008712 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00008713 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008714 }
8715
8716 continue;
8717 }
Richard Smith8ce51082015-03-11 01:44:51 +00008718
Craig Topperc6914d02014-08-25 04:15:02 +00008719 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 // Make sure that the ObjCInterfaceType points at the definition.
8721 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
8722 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00008723
8724 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
8725 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
8726
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 continue;
8728 }
Richard Smith8ce51082015-03-11 01:44:51 +00008729
Craig Topperc6914d02014-08-25 04:15:02 +00008730 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00008731 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
8732 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
8733
Guy Benyei11169dd2012-12-18 14:30:41 +00008734 continue;
8735 }
Richard Smith8ce51082015-03-11 01:44:51 +00008736
Craig Topperc6914d02014-08-25 04:15:02 +00008737 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00008738 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
8739 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00008740 }
8741 PendingDefinitions.clear();
8742
8743 // Load the bodies of any functions or methods we've encountered. We do
8744 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00008745 // have been fully wired up (hasBody relies on this).
8746 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00008747 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
8748 PBEnd = PendingBodies.end();
8749 PB != PBEnd; ++PB) {
8750 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
8751 // FIXME: Check for =delete/=default?
8752 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00008753 const FunctionDecl *Defn = nullptr;
8754 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn))
Guy Benyei11169dd2012-12-18 14:30:41 +00008755 FD->setLazyBody(PB->second);
Benjamin Kramera72a70a2016-10-17 13:00:44 +00008756 else
Richard Smith6561f922016-09-12 21:06:40 +00008757 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00008758 continue;
8759 }
8760
8761 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
8762 if (!getContext().getLangOpts().Modules || !MD->hasBody())
8763 MD->setLazyBody(PB->second);
8764 }
8765 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00008766
8767 // Do some cleanup.
8768 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
8769 getContext().deduplicateMergedDefinitonsFor(ND);
8770 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008771}
8772
8773void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00008774 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
8775 return;
8776
Richard Smitha0ce9c42014-07-29 23:23:27 +00008777 // Trigger the import of the full definition of each class that had any
8778 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00008779 // These updates may in turn find and diagnose some ODR failures, so take
8780 // ownership of the set first.
8781 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
8782 PendingOdrMergeFailures.clear();
8783 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008784 Merge.first->buildLookup();
8785 Merge.first->decls_begin();
8786 Merge.first->bases_begin();
8787 Merge.first->vbases_begin();
8788 for (auto *RD : Merge.second) {
8789 RD->decls_begin();
8790 RD->bases_begin();
8791 RD->vbases_begin();
8792 }
8793 }
8794
8795 // For each declaration from a merged context, check that the canonical
8796 // definition of that context also contains a declaration of the same
8797 // entity.
8798 //
8799 // Caution: this loop does things that might invalidate iterators into
8800 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
8801 while (!PendingOdrMergeChecks.empty()) {
8802 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
8803
8804 // FIXME: Skip over implicit declarations for now. This matters for things
8805 // like implicitly-declared special member functions. This isn't entirely
8806 // correct; we can end up with multiple unmerged declarations of the same
8807 // implicit entity.
8808 if (D->isImplicit())
8809 continue;
8810
8811 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00008812
8813 bool Found = false;
8814 const Decl *DCanon = D->getCanonicalDecl();
8815
Richard Smith01bdb7a2014-08-28 05:44:07 +00008816 for (auto RI : D->redecls()) {
8817 if (RI->getLexicalDeclContext() == CanonDef) {
8818 Found = true;
8819 break;
8820 }
8821 }
8822 if (Found)
8823 continue;
8824
Richard Smith0f4e2c42015-08-06 04:23:48 +00008825 // Quick check failed, time to do the slow thing. Note, we can't just
8826 // look up the name of D in CanonDef here, because the member that is
8827 // in CanonDef might not be found by name lookup (it might have been
8828 // replaced by a more recent declaration in the lookup table), and we
8829 // can't necessarily find it in the redeclaration chain because it might
8830 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008831 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00008832 for (auto *CanonMember : CanonDef->decls()) {
8833 if (CanonMember->getCanonicalDecl() == DCanon) {
8834 // This can happen if the declaration is merely mergeable and not
8835 // actually redeclarable (we looked for redeclarations earlier).
8836 //
8837 // FIXME: We should be able to detect this more efficiently, without
8838 // pulling in all of the members of CanonDef.
8839 Found = true;
8840 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00008841 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00008842 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
8843 if (ND->getDeclName() == D->getDeclName())
8844 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008845 }
8846
8847 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00008848 // The AST doesn't like TagDecls becoming invalid after they've been
8849 // completed. We only really need to mark FieldDecls as invalid here.
8850 if (!isa<TagDecl>(D))
8851 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008852
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008853 // Ensure we don't accidentally recursively enter deserialization while
8854 // we're producing our diagnostic.
8855 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00008856
8857 std::string CanonDefModule =
8858 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
8859 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
8860 << D << getOwningModuleNameForDiagnostic(D)
8861 << CanonDef << CanonDefModule.empty() << CanonDefModule;
8862
8863 if (Candidates.empty())
8864 Diag(cast<Decl>(CanonDef)->getLocation(),
8865 diag::note_module_odr_violation_no_possible_decls) << D;
8866 else {
8867 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
8868 Diag(Candidates[I]->getLocation(),
8869 diag::note_module_odr_violation_possible_decl)
8870 << Candidates[I];
8871 }
8872
8873 DiagnosedOdrMergeFailures.insert(CanonDef);
8874 }
8875 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008876
Richard Smith4ab3dbd2015-02-13 22:43:51 +00008877 if (OdrMergeFailures.empty())
8878 return;
8879
8880 // Ensure we don't accidentally recursively enter deserialization while
8881 // we're producing our diagnostics.
8882 Deserializing RecursionGuard(this);
8883
Richard Smithcd45dbc2014-04-19 03:48:30 +00008884 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00008885 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00008886 // If we've already pointed out a specific problem with this class, don't
8887 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00008888 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00008889 continue;
8890
8891 bool Diagnosed = false;
8892 for (auto *RD : Merge.second) {
8893 // Multiple different declarations got merged together; tell the user
8894 // where they came from.
Sam McCall61e29aa2017-01-31 08:24:40 +00008895 if (Merge.first != RD) {
8896 // FIXME: Walk the definition, figure out what's different,
8897 // and diagnose that.
8898 if (!Diagnosed) {
8899 std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
8900 Diag(Merge.first->getLocation(),
8901 diag::err_module_odr_violation_different_definitions)
Richard Trieufa3d93a2017-01-31 01:44:15 +00008902 << Merge.first << Module.empty() << Module;
Sam McCall61e29aa2017-01-31 08:24:40 +00008903 Diagnosed = true;
8904 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00008905
8906 Diag(RD->getLocation(),
8907 diag::note_module_odr_violation_different_definitions)
Sam McCall61e29aa2017-01-31 08:24:40 +00008908 << getOwningModuleNameForDiagnostic(RD);
Richard Smithcd45dbc2014-04-19 03:48:30 +00008909 }
8910 }
8911
8912 if (!Diagnosed) {
8913 // All definitions are updates to the same declaration. This happens if a
8914 // module instantiates the declaration of a class template specialization
8915 // and two or more other modules instantiate its definition.
8916 //
8917 // FIXME: Indicate which modules had instantiations of this definition.
8918 // FIXME: How can this even happen?
8919 Diag(Merge.first->getLocation(),
8920 diag::err_module_odr_violation_different_instantiations)
8921 << Merge.first;
8922 }
8923 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008924}
8925
Richard Smithce18a182015-07-14 00:26:00 +00008926void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008927 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00008928 ReadTimer->startTimer();
8929}
8930
Guy Benyei11169dd2012-12-18 14:30:41 +00008931void ASTReader::FinishedDeserializing() {
8932 assert(NumCurrentElementsDeserializing &&
8933 "FinishedDeserializing not paired with StartedDeserializing");
8934 if (NumCurrentElementsDeserializing == 1) {
8935 // We decrease NumCurrentElementsDeserializing only after pending actions
8936 // are finished, to avoid recursively re-calling finishPendingActions().
8937 finishPendingActions();
8938 }
8939 --NumCurrentElementsDeserializing;
8940
Richard Smitha0ce9c42014-07-29 23:23:27 +00008941 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008942 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00008943 while (!PendingExceptionSpecUpdates.empty()) {
8944 auto Updates = std::move(PendingExceptionSpecUpdates);
8945 PendingExceptionSpecUpdates.clear();
8946 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00008947 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00008948 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00008949 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00008950 if (auto *Listener = Context.getASTMutationListener())
8951 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00008952 for (auto *Redecl : Update.second->redecls())
8953 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00008954 }
Richard Smith9e2341d2015-03-23 03:25:59 +00008955 }
8956
Richard Smithce18a182015-07-14 00:26:00 +00008957 if (ReadTimer)
8958 ReadTimer->stopTimer();
8959
Richard Smith0f4e2c42015-08-06 04:23:48 +00008960 diagnoseOdrViolations();
8961
Richard Smith04d05b52014-03-23 00:27:18 +00008962 // We are not in recursive loading, so it's safe to pass the "interesting"
8963 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00008964 if (Consumer)
8965 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00008966 }
8967}
8968
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008969void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00008970 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
8971 // Remove any fake results before adding any real ones.
8972 auto It = PendingFakeLookupResults.find(II);
8973 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00008974 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00008975 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00008976 // FIXME: this works around module+PCH performance issue.
8977 // Rather than erase the result from the map, which is O(n), just clear
8978 // the vector of NamedDecls.
8979 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00008980 }
8981 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008982
8983 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
8984 SemaObj->TUScope->AddDecl(D);
8985 } else if (SemaObj->TUScope) {
8986 // Adding the decl to IdResolver may have failed because it was already in
8987 // (even though it was not added in scope). If it is already in, make sure
8988 // it gets in the scope as well.
8989 if (std::find(SemaObj->IdResolver.begin(Name),
8990 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
8991 SemaObj->TUScope->AddDecl(D);
8992 }
8993}
8994
David Blaikie61137e12017-01-05 18:23:18 +00008995ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
8996 const PCHContainerReader &PCHContainerRdr,
8997 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
8998 StringRef isysroot, bool DisableValidation,
8999 bool AllowASTWithCompilerErrors,
9000 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9001 bool UseGlobalIndex,
9002 std::unique_ptr<llvm::Timer> ReadTimer)
9003 : Listener(DisableValidation
9004 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9005 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009006 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009007 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
9008 Context(Context), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
9009 DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009010 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009011 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9012 AllowConfigurationMismatch(AllowConfigurationMismatch),
9013 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009014 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009015 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009016
9017 for (const auto &Ext : Extensions) {
9018 auto BlockName = Ext->getExtensionMetadata().BlockName;
9019 auto Known = ModuleFileExtensions.find(BlockName);
9020 if (Known != ModuleFileExtensions.end()) {
9021 Diags.Report(diag::warn_duplicate_module_file_extension)
9022 << BlockName;
9023 continue;
9024 }
9025
9026 ModuleFileExtensions.insert({BlockName, Ext});
9027 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009028}
9029
9030ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009031 if (OwnsDeserializationListener)
9032 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009033}
Richard Smith10379092016-05-06 23:14:07 +00009034
9035IdentifierResolver &ASTReader::getIdResolver() {
9036 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9037}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009038
9039unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9040 unsigned AbbrevID) {
9041 Idx = 0;
9042 Record.clear();
9043 return Cursor.readRecord(AbbrevID, Record);
9044}