blob: c1c625a74327bb18cadab74ec55edd543d97a545 [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"
Richard Trieue7f7ed22017-02-22 01:11:25 +000029#include "clang/AST/ODRHash.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/AST/RawCommentList.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000031#include "clang/AST/Type.h"
32#include "clang/AST/TypeLocVisitor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/AST/UnresolvedSet.h"
34#include "clang/Basic/CommentOptions.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000035#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000036#include "clang/Basic/ExceptionSpecificationType.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "clang/Basic/FileSystemOptions.h"
39#include "clang/Basic/LangOptions.h"
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000040#include "clang/Basic/MemoryBufferCache.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000041#include "clang/Basic/ObjCRuntime.h"
42#include "clang/Basic/OperatorKinds.h"
43#include "clang/Basic/Sanitizers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000044#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/SourceManagerInternals.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "clang/Basic/Specifiers.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000047#include "clang/Basic/TargetInfo.h"
48#include "clang/Basic/TargetOptions.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include "clang/Basic/TokenKinds.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000050#include "clang/Basic/Version.h"
51#include "clang/Basic/VersionTuple.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include "clang/Frontend/PCHContainerOperations.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000053#include "clang/Lex/HeaderSearch.h"
54#include "clang/Lex/HeaderSearchOptions.h"
55#include "clang/Lex/MacroInfo.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "clang/Lex/ModuleMap.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000057#include "clang/Lex/PreprocessingRecord.h"
58#include "clang/Lex/Preprocessor.h"
59#include "clang/Lex/PreprocessorOptions.h"
60#include "clang/Sema/Scope.h"
61#include "clang/Sema/Sema.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include "clang/Sema/Weak.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000063#include "clang/Serialization/ASTDeserializationListener.h"
Douglas Gregore060e572013-01-25 01:03:03 +000064#include "clang/Serialization/GlobalModuleIndex.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000065#include "clang/Serialization/ModuleManager.h"
66#include "clang/Serialization/SerializationDiagnostic.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000067#include "llvm/ADT/APFloat.h"
68#include "llvm/ADT/APInt.h"
69#include "llvm/ADT/APSInt.h"
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +000070#include "llvm/ADT/Hashing.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include "llvm/ADT/SmallString.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000072#include "llvm/ADT/StringExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include "llvm/ADT/Triple.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000074#include "llvm/Bitcode/BitstreamReader.h"
Richard Smithaada85c2016-02-06 02:06:43 +000075#include "llvm/Support/Compression.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000076#include "llvm/Support/Compiler.h"
George Rimarc39f5492017-01-17 15:45:31 +000077#include "llvm/Support/Error.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000078#include "llvm/Support/ErrorHandling.h"
79#include "llvm/Support/FileSystem.h"
80#include "llvm/Support/MemoryBuffer.h"
81#include "llvm/Support/Path.h"
82#include "llvm/Support/SaveAndRestore.h"
Dmitri Gribenkof430da42014-02-12 10:33:14 +000083#include "llvm/Support/raw_ostream.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000084#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000085#include <cassert>
86#include <cstdint>
Chris Lattner91f373e2013-01-20 00:57:52 +000087#include <cstdio>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000088#include <cstring>
89#include <ctime>
Guy Benyei11169dd2012-12-18 14:30:41 +000090#include <iterator>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000091#include <limits>
92#include <map>
93#include <memory>
94#include <new>
95#include <string>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000096#include <system_error>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000097#include <tuple>
98#include <utility>
99#include <vector>
Guy Benyei11169dd2012-12-18 14:30:41 +0000100
101using namespace clang;
102using namespace clang::serialization;
103using namespace clang::serialization::reader;
Chris Lattner7fb3bef2013-01-20 00:56:42 +0000104using llvm::BitstreamCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +0000105
Ben Langmuircb69b572014-03-07 06:40:32 +0000106//===----------------------------------------------------------------------===//
107// ChainedASTReaderListener implementation
108//===----------------------------------------------------------------------===//
109
110bool
111ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
112 return First->ReadFullVersionInformation(FullVersion) ||
113 Second->ReadFullVersionInformation(FullVersion);
114}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000115
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000116void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
117 First->ReadModuleName(ModuleName);
118 Second->ReadModuleName(ModuleName);
119}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000120
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000121void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
122 First->ReadModuleMapFile(ModuleMapPath);
123 Second->ReadModuleMapFile(ModuleMapPath);
124}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000125
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000126bool
127ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
128 bool Complain,
129 bool AllowCompatibleDifferences) {
130 return First->ReadLanguageOptions(LangOpts, Complain,
131 AllowCompatibleDifferences) ||
132 Second->ReadLanguageOptions(LangOpts, Complain,
133 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000134}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000135
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000136bool ChainedASTReaderListener::ReadTargetOptions(
137 const TargetOptions &TargetOpts, bool Complain,
138 bool AllowCompatibleDifferences) {
139 return First->ReadTargetOptions(TargetOpts, Complain,
140 AllowCompatibleDifferences) ||
141 Second->ReadTargetOptions(TargetOpts, Complain,
142 AllowCompatibleDifferences);
Ben Langmuircb69b572014-03-07 06:40:32 +0000143}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000144
Ben Langmuircb69b572014-03-07 06:40:32 +0000145bool ChainedASTReaderListener::ReadDiagnosticOptions(
Ben Langmuirb92de022014-04-29 16:25:26 +0000146 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
Ben Langmuircb69b572014-03-07 06:40:32 +0000147 return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
148 Second->ReadDiagnosticOptions(DiagOpts, Complain);
149}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000150
Ben Langmuircb69b572014-03-07 06:40:32 +0000151bool
152ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
153 bool Complain) {
154 return First->ReadFileSystemOptions(FSOpts, Complain) ||
155 Second->ReadFileSystemOptions(FSOpts, Complain);
156}
157
158bool ChainedASTReaderListener::ReadHeaderSearchOptions(
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000159 const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
160 bool Complain) {
161 return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
162 Complain) ||
163 Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
164 Complain);
Ben Langmuircb69b572014-03-07 06:40:32 +0000165}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000166
Ben Langmuircb69b572014-03-07 06:40:32 +0000167bool ChainedASTReaderListener::ReadPreprocessorOptions(
168 const PreprocessorOptions &PPOpts, bool Complain,
169 std::string &SuggestedPredefines) {
170 return First->ReadPreprocessorOptions(PPOpts, Complain,
171 SuggestedPredefines) ||
172 Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
173}
174void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
175 unsigned Value) {
176 First->ReadCounter(M, Value);
177 Second->ReadCounter(M, Value);
178}
179bool ChainedASTReaderListener::needsInputFileVisitation() {
180 return First->needsInputFileVisitation() ||
181 Second->needsInputFileVisitation();
182}
183bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
184 return First->needsSystemInputFileVisitation() ||
185 Second->needsSystemInputFileVisitation();
186}
Richard Smith216a3bd2015-08-13 17:57:10 +0000187void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
188 ModuleKind Kind) {
189 First->visitModuleFile(Filename, Kind);
190 Second->visitModuleFile(Filename, Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +0000191}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000192
Ben Langmuircb69b572014-03-07 06:40:32 +0000193bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +0000194 bool isSystem,
Richard Smith216a3bd2015-08-13 17:57:10 +0000195 bool isOverridden,
196 bool isExplicitModule) {
Justin Bognerc65a66d2014-05-22 06:04:59 +0000197 bool Continue = false;
198 if (First->needsInputFileVisitation() &&
199 (!isSystem || First->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000200 Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
201 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000202 if (Second->needsInputFileVisitation() &&
203 (!isSystem || Second->needsSystemInputFileVisitation()))
Richard Smith216a3bd2015-08-13 17:57:10 +0000204 Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
205 isExplicitModule);
Justin Bognerc65a66d2014-05-22 06:04:59 +0000206 return Continue;
Ben Langmuircb69b572014-03-07 06:40:32 +0000207}
208
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000209void ChainedASTReaderListener::readModuleFileExtension(
210 const ModuleFileExtensionMetadata &Metadata) {
211 First->readModuleFileExtension(Metadata);
212 Second->readModuleFileExtension(Metadata);
213}
214
Guy Benyei11169dd2012-12-18 14:30:41 +0000215//===----------------------------------------------------------------------===//
216// PCH validator implementation
217//===----------------------------------------------------------------------===//
218
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000219ASTReaderListener::~ASTReaderListener() {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000220
221/// \brief Compare the given set of language options against an existing set of
222/// language options.
223///
224/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000225/// \param AllowCompatibleDifferences If true, differences between compatible
226/// language options will be permitted.
Guy Benyei11169dd2012-12-18 14:30:41 +0000227///
228/// \returns true if the languagae options mis-match, false otherwise.
229static bool checkLanguageOptions(const LangOptions &LangOpts,
230 const LangOptions &ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000231 DiagnosticsEngine *Diags,
232 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000233#define LANGOPT(Name, Bits, Default, Description) \
234 if (ExistingLangOpts.Name != LangOpts.Name) { \
235 if (Diags) \
236 Diags->Report(diag::err_pch_langopt_mismatch) \
237 << Description << LangOpts.Name << ExistingLangOpts.Name; \
238 return true; \
239 }
240
241#define VALUE_LANGOPT(Name, Bits, Default, Description) \
242 if (ExistingLangOpts.Name != LangOpts.Name) { \
243 if (Diags) \
244 Diags->Report(diag::err_pch_langopt_value_mismatch) \
245 << Description; \
246 return true; \
247 }
248
249#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
250 if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
251 if (Diags) \
252 Diags->Report(diag::err_pch_langopt_value_mismatch) \
253 << Description; \
254 return true; \
255 }
256
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000257#define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
258 if (!AllowCompatibleDifferences) \
259 LANGOPT(Name, Bits, Default, Description)
260
261#define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
262 if (!AllowCompatibleDifferences) \
263 ENUM_LANGOPT(Name, Bits, Default, Description)
264
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000265#define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
266 if (!AllowCompatibleDifferences) \
267 VALUE_LANGOPT(Name, Bits, Default, Description)
268
Guy Benyei11169dd2012-12-18 14:30:41 +0000269#define BENIGN_LANGOPT(Name, Bits, Default, Description)
270#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
Richard Smitha1ddf5e2016-04-07 20:47:37 +0000271#define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
Guy Benyei11169dd2012-12-18 14:30:41 +0000272#include "clang/Basic/LangOptions.def"
273
Ben Langmuircd98cb72015-06-23 18:20:18 +0000274 if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
275 if (Diags)
276 Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
277 return true;
278 }
279
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
281 if (Diags)
282 Diags->Report(diag::err_pch_langopt_value_mismatch)
283 << "target Objective-C runtime";
284 return true;
285 }
286
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +0000287 if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
288 LangOpts.CommentOpts.BlockCommandNames) {
289 if (Diags)
290 Diags->Report(diag::err_pch_langopt_value_mismatch)
291 << "block command names";
292 return true;
293 }
294
Vedant Kumar85a83c22017-06-01 20:01:01 +0000295 // Sanitizer feature mismatches are treated as compatible differences. If
296 // compatible differences aren't allowed, we still only want to check for
297 // mismatches of non-modular sanitizers (the only ones which can affect AST
298 // generation).
299 if (!AllowCompatibleDifferences) {
300 SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
301 SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
302 SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
303 ExistingSanitizers.clear(ModularSanitizers);
304 ImportedSanitizers.clear(ModularSanitizers);
305 if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
306 const std::string Flag = "-fsanitize=";
307 if (Diags) {
308#define SANITIZER(NAME, ID) \
309 { \
310 bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
311 bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
312 if (InExistingModule != InImportedModule) \
313 Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
314 << InExistingModule << (Flag + NAME); \
315 }
316#include "clang/Basic/Sanitizers.def"
317 }
318 return true;
319 }
320 }
321
Guy Benyei11169dd2012-12-18 14:30:41 +0000322 return false;
323}
324
325/// \brief Compare the given set of target options against an existing set of
326/// target options.
327///
328/// \param Diags If non-NULL, diagnostics will be emitted via this engine.
329///
330/// \returns true if the target options mis-match, false otherwise.
331static bool checkTargetOptions(const TargetOptions &TargetOpts,
332 const TargetOptions &ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000333 DiagnosticsEngine *Diags,
334 bool AllowCompatibleDifferences = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000335#define CHECK_TARGET_OPT(Field, Name) \
336 if (TargetOpts.Field != ExistingTargetOpts.Field) { \
337 if (Diags) \
338 Diags->Report(diag::err_pch_targetopt_mismatch) \
339 << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
340 return true; \
341 }
342
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000343 // The triple and ABI must match exactly.
Guy Benyei11169dd2012-12-18 14:30:41 +0000344 CHECK_TARGET_OPT(Triple, "target");
Guy Benyei11169dd2012-12-18 14:30:41 +0000345 CHECK_TARGET_OPT(ABI, "target ABI");
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000346
347 // We can tolerate different CPUs in many cases, notably when one CPU
348 // supports a strict superset of another. When allowing compatible
349 // differences skip this check.
350 if (!AllowCompatibleDifferences)
351 CHECK_TARGET_OPT(CPU, "target CPU");
352
Guy Benyei11169dd2012-12-18 14:30:41 +0000353#undef CHECK_TARGET_OPT
354
355 // Compare feature sets.
356 SmallVector<StringRef, 4> ExistingFeatures(
357 ExistingTargetOpts.FeaturesAsWritten.begin(),
358 ExistingTargetOpts.FeaturesAsWritten.end());
359 SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
360 TargetOpts.FeaturesAsWritten.end());
361 std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
362 std::sort(ReadFeatures.begin(), ReadFeatures.end());
363
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000364 // We compute the set difference in both directions explicitly so that we can
365 // diagnose the differences differently.
366 SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
367 std::set_difference(
368 ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
369 ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
370 std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
371 ExistingFeatures.begin(), ExistingFeatures.end(),
372 std::back_inserter(UnmatchedReadFeatures));
Guy Benyei11169dd2012-12-18 14:30:41 +0000373
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000374 // If we are allowing compatible differences and the read feature set is
375 // a strict subset of the existing feature set, there is nothing to diagnose.
376 if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
377 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000378
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000379 if (Diags) {
380 for (StringRef Feature : UnmatchedReadFeatures)
Guy Benyei11169dd2012-12-18 14:30:41 +0000381 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000382 << /* is-existing-feature */ false << Feature;
383 for (StringRef Feature : UnmatchedExistingFeatures)
384 Diags->Report(diag::err_pch_targetopt_feature_mismatch)
385 << /* is-existing-feature */ true << Feature;
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 }
387
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000388 return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +0000389}
390
391bool
392PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000393 bool Complain,
394 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000395 const LangOptions &ExistingLangOpts = PP.getLangOpts();
396 return checkLanguageOptions(LangOpts, ExistingLangOpts,
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000397 Complain ? &Reader.Diags : nullptr,
398 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000399}
400
401bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000402 bool Complain,
403 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000404 const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
405 return checkTargetOptions(TargetOpts, ExistingTargetOpts,
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000406 Complain ? &Reader.Diags : nullptr,
407 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +0000408}
409
410namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000411
Guy Benyei11169dd2012-12-18 14:30:41 +0000412 typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
413 MacroDefinitionsMap;
Craig Topper3598eb72013-07-05 04:43:31 +0000414 typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
415 DeclsMap;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000416
417} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +0000418
Ben Langmuirb92de022014-04-29 16:25:26 +0000419static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
420 DiagnosticsEngine &Diags,
421 bool Complain) {
422 typedef DiagnosticsEngine::Level Level;
423
424 // Check current mappings for new -Werror mappings, and the stored mappings
425 // for cases that were explicitly mapped to *not* be errors that are now
426 // errors because of options like -Werror.
427 DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
428
429 for (DiagnosticsEngine *MappingSource : MappingSources) {
430 for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
431 diag::kind DiagID = DiagIDMappingPair.first;
432 Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
433 if (CurLevel < DiagnosticsEngine::Error)
434 continue; // not significant
435 Level StoredLevel =
436 StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
437 if (StoredLevel < DiagnosticsEngine::Error) {
438 if (Complain)
439 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
440 Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
441 return true;
442 }
443 }
444 }
445
446 return false;
447}
448
Alp Tokerac4e8e52014-06-22 21:58:33 +0000449static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
450 diag::Severity Ext = Diags.getExtensionHandlingBehavior();
451 if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
452 return true;
453 return Ext >= diag::Severity::Error;
Ben Langmuirb92de022014-04-29 16:25:26 +0000454}
455
456static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
457 DiagnosticsEngine &Diags,
458 bool IsSystem, bool Complain) {
459 // Top-level options
460 if (IsSystem) {
461 if (Diags.getSuppressSystemWarnings())
462 return false;
463 // If -Wsystem-headers was not enabled before, be conservative
464 if (StoredDiags.getSuppressSystemWarnings()) {
465 if (Complain)
466 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
467 return true;
468 }
469 }
470
471 if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
472 if (Complain)
473 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
474 return true;
475 }
476
477 if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
478 !StoredDiags.getEnableAllWarnings()) {
479 if (Complain)
480 Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
481 return true;
482 }
483
484 if (isExtHandlingFromDiagsError(Diags) &&
485 !isExtHandlingFromDiagsError(StoredDiags)) {
486 if (Complain)
487 Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
488 return true;
489 }
490
491 return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
492}
493
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000494/// Return the top import module if it is implicit, nullptr otherwise.
495static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
496 Preprocessor &PP) {
497 // If the original import came from a file explicitly generated by the user,
498 // don't check the diagnostic mappings.
499 // FIXME: currently this is approximated by checking whether this is not a
500 // module import of an implicitly-loaded module file.
501 // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
502 // the transitive closure of its imports, since unrelated modules cannot be
503 // imported until after this module finishes validation.
504 ModuleFile *TopImport = &*ModuleMgr.rbegin();
505 while (!TopImport->ImportedBy.empty())
506 TopImport = TopImport->ImportedBy[0];
507 if (TopImport->Kind != MK_ImplicitModule)
508 return nullptr;
509
510 StringRef ModuleName = TopImport->ModuleName;
511 assert(!ModuleName.empty() && "diagnostic options read before module name");
512
513 Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
514 assert(M && "missing module");
515 return M;
516}
517
Ben Langmuirb92de022014-04-29 16:25:26 +0000518bool PCHValidator::ReadDiagnosticOptions(
519 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
520 DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
521 IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
522 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Alp Tokerf994cef2014-07-05 03:08:06 +0000523 new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
Ben Langmuirb92de022014-04-29 16:25:26 +0000524 // This should never fail, because we would have processed these options
525 // before writing them to an ASTFile.
526 ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
527
528 ModuleManager &ModuleMgr = Reader.getModuleManager();
529 assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
530
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000531 Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
532 if (!TopM)
Ben Langmuirb92de022014-04-29 16:25:26 +0000533 return false;
534
Ben Langmuirb92de022014-04-29 16:25:26 +0000535 // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
536 // contains the union of their flags.
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +0000537 return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
538 Complain);
Ben Langmuirb92de022014-04-29 16:25:26 +0000539}
540
Guy Benyei11169dd2012-12-18 14:30:41 +0000541/// \brief Collect the macro definitions provided by the given preprocessor
542/// options.
Craig Toppera13603a2014-05-22 05:54:18 +0000543static void
544collectMacroDefinitions(const PreprocessorOptions &PPOpts,
545 MacroDefinitionsMap &Macros,
546 SmallVectorImpl<StringRef> *MacroNames = nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000547 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
548 StringRef Macro = PPOpts.Macros[I].first;
549 bool IsUndef = PPOpts.Macros[I].second;
550
551 std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
552 StringRef MacroName = MacroPair.first;
553 StringRef MacroBody = MacroPair.second;
554
555 // For an #undef'd macro, we only care about the name.
556 if (IsUndef) {
557 if (MacroNames && !Macros.count(MacroName))
558 MacroNames->push_back(MacroName);
559
560 Macros[MacroName] = std::make_pair("", true);
561 continue;
562 }
563
564 // For a #define'd macro, figure out the actual definition.
565 if (MacroName.size() == Macro.size())
566 MacroBody = "1";
567 else {
568 // Note: GCC drops anything following an end-of-line character.
569 StringRef::size_type End = MacroBody.find_first_of("\n\r");
570 MacroBody = MacroBody.substr(0, End);
571 }
572
573 if (MacroNames && !Macros.count(MacroName))
574 MacroNames->push_back(MacroName);
575 Macros[MacroName] = std::make_pair(MacroBody, false);
576 }
577}
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579/// \brief Check the preprocessor options deserialized from the control block
580/// against the preprocessor options in an existing preprocessor.
581///
582/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
Yaxun Liu43712e02016-09-07 18:40:20 +0000583/// \param Validate If true, validate preprocessor options. If false, allow
584/// macros defined by \p ExistingPPOpts to override those defined by
585/// \p PPOpts in SuggestedPredefines.
Guy Benyei11169dd2012-12-18 14:30:41 +0000586static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
587 const PreprocessorOptions &ExistingPPOpts,
588 DiagnosticsEngine *Diags,
589 FileManager &FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000590 std::string &SuggestedPredefines,
Yaxun Liu43712e02016-09-07 18:40:20 +0000591 const LangOptions &LangOpts,
592 bool Validate = true) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000593 // Check macro definitions.
594 MacroDefinitionsMap ASTFileMacros;
595 collectMacroDefinitions(PPOpts, ASTFileMacros);
596 MacroDefinitionsMap ExistingMacros;
597 SmallVector<StringRef, 4> ExistingMacroNames;
598 collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
599
600 for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
601 // Dig out the macro definition in the existing preprocessor options.
602 StringRef MacroName = ExistingMacroNames[I];
603 std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
604
605 // Check whether we know anything about this macro name or not.
606 llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
607 = ASTFileMacros.find(MacroName);
Yaxun Liu43712e02016-09-07 18:40:20 +0000608 if (!Validate || Known == ASTFileMacros.end()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000609 // FIXME: Check whether this identifier was referenced anywhere in the
610 // AST file. If so, we should reject the AST file. Unfortunately, this
611 // information isn't in the control block. What shall we do about it?
612
613 if (Existing.second) {
614 SuggestedPredefines += "#undef ";
615 SuggestedPredefines += MacroName.str();
616 SuggestedPredefines += '\n';
617 } else {
618 SuggestedPredefines += "#define ";
619 SuggestedPredefines += MacroName.str();
620 SuggestedPredefines += ' ';
621 SuggestedPredefines += Existing.first.str();
622 SuggestedPredefines += '\n';
623 }
624 continue;
625 }
626
627 // If the macro was defined in one but undef'd in the other, we have a
628 // conflict.
629 if (Existing.second != Known->second.second) {
630 if (Diags) {
631 Diags->Report(diag::err_pch_macro_def_undef)
632 << MacroName << Known->second.second;
633 }
634 return true;
635 }
636
637 // If the macro was #undef'd in both, or if the macro bodies are identical,
638 // it's fine.
639 if (Existing.second || Existing.first == Known->second.first)
640 continue;
641
642 // The macro bodies differ; complain.
643 if (Diags) {
644 Diags->Report(diag::err_pch_macro_def_conflict)
645 << MacroName << Known->second.first << Existing.first;
646 }
647 return true;
648 }
649
650 // Check whether we're using predefines.
Yaxun Liu43712e02016-09-07 18:40:20 +0000651 if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000652 if (Diags) {
653 Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
654 }
655 return true;
656 }
657
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000658 // Detailed record is important since it is used for the module cache hash.
659 if (LangOpts.Modules &&
Yaxun Liu43712e02016-09-07 18:40:20 +0000660 PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000661 if (Diags) {
662 Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
663 }
664 return true;
665 }
666
Guy Benyei11169dd2012-12-18 14:30:41 +0000667 // Compute the #include and #include_macros lines we need.
668 for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
669 StringRef File = ExistingPPOpts.Includes[I];
670 if (File == ExistingPPOpts.ImplicitPCHInclude)
671 continue;
672
673 if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
674 != PPOpts.Includes.end())
675 continue;
676
677 SuggestedPredefines += "#include \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000678 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000679 SuggestedPredefines += "\"\n";
680 }
681
682 for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
683 StringRef File = ExistingPPOpts.MacroIncludes[I];
684 if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
685 File)
686 != PPOpts.MacroIncludes.end())
687 continue;
688
689 SuggestedPredefines += "#__include_macros \"";
Manuel Klimek9af34ae2014-08-12 08:25:57 +0000690 SuggestedPredefines += File;
Guy Benyei11169dd2012-12-18 14:30:41 +0000691 SuggestedPredefines += "\"\n##\n";
692 }
693
694 return false;
695}
696
697bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
698 bool Complain,
699 std::string &SuggestedPredefines) {
700 const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
701
702 return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
Craig Toppera13603a2014-05-22 05:54:18 +0000703 Complain? &Reader.Diags : nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +0000704 PP.getFileManager(),
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +0000705 SuggestedPredefines,
706 PP.getLangOpts());
Guy Benyei11169dd2012-12-18 14:30:41 +0000707}
708
Yaxun Liu43712e02016-09-07 18:40:20 +0000709bool SimpleASTReaderListener::ReadPreprocessorOptions(
710 const PreprocessorOptions &PPOpts,
711 bool Complain,
712 std::string &SuggestedPredefines) {
713 return checkPreprocessorOptions(PPOpts,
714 PP.getPreprocessorOpts(),
715 nullptr,
716 PP.getFileManager(),
717 SuggestedPredefines,
718 PP.getLangOpts(),
719 false);
720}
721
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000722/// Check the header search options deserialized from the control block
723/// against the header search options in an existing preprocessor.
724///
725/// \param Diags If non-null, produce diagnostics for any mismatches incurred.
726static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
727 StringRef SpecificModuleCachePath,
728 StringRef ExistingModuleCachePath,
729 DiagnosticsEngine *Diags,
730 const LangOptions &LangOpts) {
731 if (LangOpts.Modules) {
732 if (SpecificModuleCachePath != ExistingModuleCachePath) {
733 if (Diags)
734 Diags->Report(diag::err_pch_modulecache_mismatch)
735 << SpecificModuleCachePath << ExistingModuleCachePath;
736 return true;
737 }
738 }
739
740 return false;
741}
742
743bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
744 StringRef SpecificModuleCachePath,
745 bool Complain) {
746 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
747 PP.getHeaderSearchInfo().getModuleCachePath(),
748 Complain ? &Reader.Diags : nullptr,
749 PP.getLangOpts());
750}
751
Guy Benyei11169dd2012-12-18 14:30:41 +0000752void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
753 PP.setCounterValue(Value);
754}
755
756//===----------------------------------------------------------------------===//
757// AST reader implementation
758//===----------------------------------------------------------------------===//
759
Nico Weber824285e2014-05-08 04:26:47 +0000760void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
761 bool TakeOwnership) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 DeserializationListener = Listener;
Nico Weber824285e2014-05-08 04:26:47 +0000763 OwnsDeserializationListener = TakeOwnership;
Guy Benyei11169dd2012-12-18 14:30:41 +0000764}
765
Guy Benyei11169dd2012-12-18 14:30:41 +0000766unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
767 return serialization::ComputeHash(Sel);
768}
769
Guy Benyei11169dd2012-12-18 14:30:41 +0000770std::pair<unsigned, unsigned>
771ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000772 using namespace llvm::support;
773 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
774 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000775 return std::make_pair(KeyLen, DataLen);
776}
777
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000778ASTSelectorLookupTrait::internal_key_type
Guy Benyei11169dd2012-12-18 14:30:41 +0000779ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000780 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 SelectorTable &SelTable = Reader.getContext().Selectors;
Justin Bogner57ba0b22014-03-28 22:03:24 +0000782 unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
783 IdentifierInfo *FirstII = Reader.getLocalIdentifier(
784 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +0000785 if (N == 0)
786 return SelTable.getNullarySelector(FirstII);
787 else if (N == 1)
788 return SelTable.getUnarySelector(FirstII);
789
790 SmallVector<IdentifierInfo *, 16> Args;
791 Args.push_back(FirstII);
792 for (unsigned I = 1; I != N; ++I)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000793 Args.push_back(Reader.getLocalIdentifier(
794 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000795
796 return SelTable.getSelector(N, Args.data());
797}
798
David L. Jonesc4808b9e2016-12-15 20:53:26 +0000799ASTSelectorLookupTrait::data_type
800ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000802 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +0000803
804 data_type Result;
805
Justin Bogner57ba0b22014-03-28 22:03:24 +0000806 Result.ID = Reader.getGlobalSelectorID(
807 F, endian::readNext<uint32_t, little, unaligned>(d));
Nico Weberff4b35e2014-12-27 22:14:15 +0000808 unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
809 unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
810 Result.InstanceBits = FullInstanceBits & 0x3;
811 Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
812 Result.FactoryBits = FullFactoryBits & 0x3;
813 Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
814 unsigned NumInstanceMethods = FullInstanceBits >> 3;
815 unsigned NumFactoryMethods = FullFactoryBits >> 3;
Guy Benyei11169dd2012-12-18 14:30:41 +0000816
817 // Load instance methods
818 for (unsigned I = 0; I != NumInstanceMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000819 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
820 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000821 Result.Instance.push_back(Method);
822 }
823
824 // Load factory methods
825 for (unsigned I = 0; I != NumFactoryMethods; ++I) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000826 if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
827 F, endian::readNext<uint32_t, little, unaligned>(d)))
Guy Benyei11169dd2012-12-18 14:30:41 +0000828 Result.Factory.push_back(Method);
829 }
830
831 return Result;
832}
833
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000834unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
835 return llvm::HashString(a);
Guy Benyei11169dd2012-12-18 14:30:41 +0000836}
837
838std::pair<unsigned, unsigned>
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000839ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000840 using namespace llvm::support;
841 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
842 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000843 return std::make_pair(KeyLen, DataLen);
844}
845
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000846ASTIdentifierLookupTraitBase::internal_key_type
847ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 assert(n >= 2 && d[n-1] == '\0');
Douglas Gregorbfd73d72013-01-23 18:53:14 +0000849 return StringRef((const char*) d, n-1);
Guy Benyei11169dd2012-12-18 14:30:41 +0000850}
851
Douglas Gregordcf25082013-02-11 18:16:18 +0000852/// \brief Whether the given identifier is "interesting".
Richard Smitha534a312015-07-21 23:54:07 +0000853static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
854 bool IsModule) {
Richard Smithcab89802015-07-17 20:19:56 +0000855 return II.hadMacroDefinition() ||
856 II.isPoisoned() ||
Richard Smith9c254182015-07-19 21:41:12 +0000857 (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
Douglas Gregordcf25082013-02-11 18:16:18 +0000858 II.hasRevertedTokenIDToIdentifier() ||
Richard Smitha534a312015-07-21 23:54:07 +0000859 (!(IsModule && Reader.getContext().getLangOpts().CPlusPlus) &&
860 II.getFETokenInfo<void>());
Douglas Gregordcf25082013-02-11 18:16:18 +0000861}
862
Richard Smith76c2f2c2015-07-17 20:09:43 +0000863static bool readBit(unsigned &Bits) {
864 bool Value = Bits & 0x1;
865 Bits >>= 1;
866 return Value;
867}
868
Richard Smith79bf9202015-08-24 03:33:22 +0000869IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
870 using namespace llvm::support;
871 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
872 return Reader.getGlobalIdentifierID(F, RawID >> 1);
873}
874
Richard Smitheb4b58f62016-02-05 01:40:54 +0000875static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
876 if (!II.isFromAST()) {
877 II.setIsFromAST();
878 bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
879 if (isInterestingIdentifier(Reader, II, IsModule))
880 II.setChangedSinceDeserialization();
881 }
882}
883
Guy Benyei11169dd2012-12-18 14:30:41 +0000884IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
885 const unsigned char* d,
886 unsigned DataLen) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000887 using namespace llvm::support;
888 unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +0000889 bool IsInteresting = RawID & 0x01;
890
891 // Wipe out the "is interesting" bit.
892 RawID = RawID >> 1;
893
Richard Smith76c2f2c2015-07-17 20:09:43 +0000894 // Build the IdentifierInfo and link the identifier ID with it.
895 IdentifierInfo *II = KnownII;
896 if (!II) {
897 II = &Reader.getIdentifierTable().getOwn(k);
898 KnownII = II;
899 }
Richard Smitheb4b58f62016-02-05 01:40:54 +0000900 markIdentifierFromAST(Reader, *II);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000901 Reader.markIdentifierUpToDate(II);
902
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
904 if (!IsInteresting) {
Richard Smith76c2f2c2015-07-17 20:09:43 +0000905 // For uninteresting identifiers, there's nothing else to do. Just notify
906 // the reader that we've finished loading this identifier.
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 Reader.SetIdentifierInfo(ID, II);
Guy Benyei11169dd2012-12-18 14:30:41 +0000908 return II;
909 }
910
Justin Bogner57ba0b22014-03-28 22:03:24 +0000911 unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
912 unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000913 bool CPlusPlusOperatorKeyword = readBit(Bits);
914 bool HasRevertedTokenIDToIdentifier = readBit(Bits);
Richard Smith9c254182015-07-19 21:41:12 +0000915 bool HasRevertedBuiltin = readBit(Bits);
Richard Smith76c2f2c2015-07-17 20:09:43 +0000916 bool Poisoned = readBit(Bits);
917 bool ExtensionToken = readBit(Bits);
918 bool HadMacroDefinition = readBit(Bits);
Guy Benyei11169dd2012-12-18 14:30:41 +0000919
920 assert(Bits == 0 && "Extra bits in the identifier?");
921 DataLen -= 8;
922
Guy Benyei11169dd2012-12-18 14:30:41 +0000923 // Set or check the various bits in the IdentifierInfo structure.
924 // Token IDs are read-only.
Argyrios Kyrtzidisddee8c92013-02-27 01:13:51 +0000925 if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
Richard Smith9c254182015-07-19 21:41:12 +0000926 II->revertTokenIDToIdentifier();
927 if (!F.isModule())
928 II->setObjCOrBuiltinID(ObjCOrBuiltinID);
929 else if (HasRevertedBuiltin && II->getBuiltinID()) {
930 II->revertBuiltin();
931 assert((II->hasRevertedBuiltin() ||
932 II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
933 "Incorrect ObjC keyword or builtin ID");
934 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 assert(II->isExtensionToken() == ExtensionToken &&
936 "Incorrect extension token flag");
937 (void)ExtensionToken;
938 if (Poisoned)
939 II->setIsPoisoned(true);
940 assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
941 "Incorrect C++ operator keyword flag");
942 (void)CPlusPlusOperatorKeyword;
943
944 // If this identifier is a macro, deserialize the macro
945 // definition.
Richard Smith76c2f2c2015-07-17 20:09:43 +0000946 if (HadMacroDefinition) {
Justin Bogner57ba0b22014-03-28 22:03:24 +0000947 uint32_t MacroDirectivesOffset =
948 endian::readNext<uint32_t, little, unaligned>(d);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000949 DataLen -= 4;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000950
Richard Smithd7329392015-04-21 21:46:32 +0000951 Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 }
953
954 Reader.SetIdentifierInfo(ID, II);
955
956 // Read all of the declarations visible at global scope with this
957 // name.
958 if (DataLen > 0) {
959 SmallVector<uint32_t, 4> DeclIDs;
960 for (; DataLen > 0; DataLen -= 4)
Justin Bogner57ba0b22014-03-28 22:03:24 +0000961 DeclIDs.push_back(Reader.getGlobalDeclID(
962 F, endian::readNext<uint32_t, little, unaligned>(d)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 Reader.SetGloballyVisibleDecls(II, DeclIDs);
964 }
965
966 return II;
967}
968
Richard Smitha06c7e62015-08-26 23:55:49 +0000969DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
970 : Kind(Name.getNameKind()) {
971 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 case DeclarationName::Identifier:
Richard Smitha06c7e62015-08-26 23:55:49 +0000973 Data = (uint64_t)Name.getAsIdentifierInfo();
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 break;
975 case DeclarationName::ObjCZeroArgSelector:
976 case DeclarationName::ObjCOneArgSelector:
977 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +0000978 Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +0000979 break;
980 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +0000981 Data = Name.getCXXOverloadedOperator();
982 break;
983 case DeclarationName::CXXLiteralOperatorName:
984 Data = (uint64_t)Name.getCXXLiteralIdentifier();
985 break;
Richard Smith35845152017-02-07 01:37:30 +0000986 case DeclarationName::CXXDeductionGuideName:
987 Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
988 ->getDeclName().getAsIdentifierInfo();
989 break;
Richard Smitha06c7e62015-08-26 23:55:49 +0000990 case DeclarationName::CXXConstructorName:
991 case DeclarationName::CXXDestructorName:
992 case DeclarationName::CXXConversionFunctionName:
993 case DeclarationName::CXXUsingDirective:
994 Data = 0;
995 break;
996 }
997}
998
999unsigned DeclarationNameKey::getHash() const {
1000 llvm::FoldingSetNodeID ID;
1001 ID.AddInteger(Kind);
1002
1003 switch (Kind) {
1004 case DeclarationName::Identifier:
1005 case DeclarationName::CXXLiteralOperatorName:
Richard Smith35845152017-02-07 01:37:30 +00001006 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001007 ID.AddString(((IdentifierInfo*)Data)->getName());
1008 break;
1009 case DeclarationName::ObjCZeroArgSelector:
1010 case DeclarationName::ObjCOneArgSelector:
1011 case DeclarationName::ObjCMultiArgSelector:
1012 ID.AddInteger(serialization::ComputeHash(Selector(Data)));
1013 break;
1014 case DeclarationName::CXXOperatorName:
1015 ID.AddInteger((OverloadedOperatorKind)Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001016 break;
1017 case DeclarationName::CXXConstructorName:
1018 case DeclarationName::CXXDestructorName:
1019 case DeclarationName::CXXConversionFunctionName:
1020 case DeclarationName::CXXUsingDirective:
1021 break;
1022 }
1023
1024 return ID.ComputeHash();
1025}
1026
Richard Smithd88a7f12015-09-01 20:35:42 +00001027ModuleFile *
1028ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
1029 using namespace llvm::support;
1030 uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
1031 return Reader.getLocalModuleFile(F, ModuleFileID);
1032}
1033
Guy Benyei11169dd2012-12-18 14:30:41 +00001034std::pair<unsigned, unsigned>
Richard Smitha06c7e62015-08-26 23:55:49 +00001035ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001036 using namespace llvm::support;
1037 unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
1038 unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 return std::make_pair(KeyLen, DataLen);
1040}
1041
Richard Smitha06c7e62015-08-26 23:55:49 +00001042ASTDeclContextNameLookupTrait::internal_key_type
1043ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001044 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001045
Richard Smitha06c7e62015-08-26 23:55:49 +00001046 auto Kind = (DeclarationName::NameKind)*d++;
1047 uint64_t Data;
1048 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 case DeclarationName::Identifier:
Richard Smith35845152017-02-07 01:37:30 +00001050 case DeclarationName::CXXLiteralOperatorName:
1051 case DeclarationName::CXXDeductionGuideName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001052 Data = (uint64_t)Reader.getLocalIdentifier(
Justin Bogner57ba0b22014-03-28 22:03:24 +00001053 F, endian::readNext<uint32_t, little, unaligned>(d));
Guy Benyei11169dd2012-12-18 14:30:41 +00001054 break;
1055 case DeclarationName::ObjCZeroArgSelector:
1056 case DeclarationName::ObjCOneArgSelector:
1057 case DeclarationName::ObjCMultiArgSelector:
Richard Smitha06c7e62015-08-26 23:55:49 +00001058 Data =
Justin Bogner57ba0b22014-03-28 22:03:24 +00001059 (uint64_t)Reader.getLocalSelector(
1060 F, endian::readNext<uint32_t, little, unaligned>(
1061 d)).getAsOpaquePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001062 break;
1063 case DeclarationName::CXXOperatorName:
Richard Smitha06c7e62015-08-26 23:55:49 +00001064 Data = *d++; // OverloadedOperatorKind
Guy Benyei11169dd2012-12-18 14:30:41 +00001065 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001066 case DeclarationName::CXXConstructorName:
1067 case DeclarationName::CXXDestructorName:
1068 case DeclarationName::CXXConversionFunctionName:
1069 case DeclarationName::CXXUsingDirective:
Richard Smitha06c7e62015-08-26 23:55:49 +00001070 Data = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 break;
1072 }
1073
Richard Smitha06c7e62015-08-26 23:55:49 +00001074 return DeclarationNameKey(Kind, Data);
Guy Benyei11169dd2012-12-18 14:30:41 +00001075}
1076
Richard Smithd88a7f12015-09-01 20:35:42 +00001077void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
1078 const unsigned char *d,
1079 unsigned DataLen,
1080 data_type_builder &Val) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001081 using namespace llvm::support;
Richard Smithd88a7f12015-09-01 20:35:42 +00001082 for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
1083 uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
1084 Val.insert(Reader.getGlobalDeclID(F, LocalID));
1085 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001086}
1087
Richard Smith0f4e2c42015-08-06 04:23:48 +00001088bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
1089 BitstreamCursor &Cursor,
1090 uint64_t Offset,
1091 DeclContext *DC) {
1092 assert(Offset != 0);
1093
Guy Benyei11169dd2012-12-18 14:30:41 +00001094 SavedStreamPosition SavedPosition(Cursor);
Richard Smith0f4e2c42015-08-06 04:23:48 +00001095 Cursor.JumpToBit(Offset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001096
Richard Smith0f4e2c42015-08-06 04:23:48 +00001097 RecordData Record;
1098 StringRef Blob;
1099 unsigned Code = Cursor.ReadCode();
1100 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1101 if (RecCode != DECL_CONTEXT_LEXICAL) {
1102 Error("Expected lexical block");
1103 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 }
1105
Richard Smith82f8fcd2015-08-06 22:07:25 +00001106 assert(!isa<TranslationUnitDecl>(DC) &&
1107 "expected a TU_UPDATE_LEXICAL record for TU");
Richard Smith9c9173d2015-08-11 22:00:24 +00001108 // If we are handling a C++ class template instantiation, we can see multiple
1109 // lexical updates for the same record. It's important that we select only one
1110 // of them, so that field numbering works properly. Just pick the first one we
1111 // see.
1112 auto &Lex = LexicalDecls[DC];
1113 if (!Lex.first) {
1114 Lex = std::make_pair(
1115 &M, llvm::makeArrayRef(
1116 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
1117 Blob.data()),
1118 Blob.size() / 4));
1119 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00001120 DC->setHasExternalLexicalStorage(true);
1121 return false;
1122}
Guy Benyei11169dd2012-12-18 14:30:41 +00001123
Richard Smith0f4e2c42015-08-06 04:23:48 +00001124bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
1125 BitstreamCursor &Cursor,
1126 uint64_t Offset,
1127 DeclID ID) {
1128 assert(Offset != 0);
1129
1130 SavedStreamPosition SavedPosition(Cursor);
1131 Cursor.JumpToBit(Offset);
1132
1133 RecordData Record;
1134 StringRef Blob;
1135 unsigned Code = Cursor.ReadCode();
1136 unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
1137 if (RecCode != DECL_CONTEXT_VISIBLE) {
1138 Error("Expected visible lookup table block");
1139 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001140 }
1141
Richard Smith0f4e2c42015-08-06 04:23:48 +00001142 // We can't safely determine the primary context yet, so delay attaching the
1143 // lookup table until we're done with recursive deserialization.
Richard Smithd88a7f12015-09-01 20:35:42 +00001144 auto *Data = (const unsigned char*)Blob.data();
1145 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
Guy Benyei11169dd2012-12-18 14:30:41 +00001146 return false;
1147}
1148
Richard Smith37a93df2017-02-18 00:32:02 +00001149void ASTReader::Error(StringRef Msg) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001150 Error(diag::err_fe_pch_malformed, Msg);
Richard Smithfb1e7f72015-08-14 05:02:58 +00001151 if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
1152 !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
Douglas Gregor940e8052013-05-10 22:15:13 +00001153 Diag(diag::note_module_cache_path)
1154 << PP.getHeaderSearchInfo().getModuleCachePath();
1155 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001156}
1157
1158void ASTReader::Error(unsigned DiagID,
Richard Smith37a93df2017-02-18 00:32:02 +00001159 StringRef Arg1, StringRef Arg2) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 if (Diags.isDiagnosticInFlight())
1161 Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
1162 else
1163 Diag(DiagID) << Arg1 << Arg2;
1164}
1165
1166//===----------------------------------------------------------------------===//
1167// Source Manager Deserialization
1168//===----------------------------------------------------------------------===//
1169
1170/// \brief Read the line table in the source manager block.
1171/// \returns true if there was an error.
1172bool ASTReader::ParseLineTable(ModuleFile &F,
Richard Smith7ed1bc92014-12-05 22:42:13 +00001173 const RecordData &Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 unsigned Idx = 0;
1175 LineTableInfo &LineTable = SourceMgr.getLineTable();
1176
1177 // Parse the file names
1178 std::map<int, int> FileIDs;
Richard Smith63078492015-09-01 07:41:55 +00001179 for (unsigned I = 0; Record[Idx]; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 // Extract the file name
Richard Smith7ed1bc92014-12-05 22:42:13 +00001181 auto Filename = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
1183 }
Richard Smith63078492015-09-01 07:41:55 +00001184 ++Idx;
Guy Benyei11169dd2012-12-18 14:30:41 +00001185
1186 // Parse the line entries
1187 std::vector<LineEntry> Entries;
1188 while (Idx < Record.size()) {
1189 int FID = Record[Idx++];
1190 assert(FID >= 0 && "Serialized line entries for non-local file.");
1191 // Remap FileID from 1-based old view.
1192 FID += F.SLocEntryBaseID - 1;
1193
1194 // Extract the line entries
1195 unsigned NumEntries = Record[Idx++];
Richard Smith63078492015-09-01 07:41:55 +00001196 assert(NumEntries && "no line entries for file ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 Entries.clear();
1198 Entries.reserve(NumEntries);
1199 for (unsigned I = 0; I != NumEntries; ++I) {
1200 unsigned FileOffset = Record[Idx++];
1201 unsigned LineNo = Record[Idx++];
1202 int FilenameID = FileIDs[Record[Idx++]];
1203 SrcMgr::CharacteristicKind FileKind
1204 = (SrcMgr::CharacteristicKind)Record[Idx++];
1205 unsigned IncludeOffset = Record[Idx++];
1206 Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
1207 FileKind, IncludeOffset));
1208 }
1209 LineTable.AddEntry(FileID::get(FID), Entries);
1210 }
1211
1212 return false;
1213}
1214
1215/// \brief Read a source manager block
1216bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
1217 using namespace SrcMgr;
1218
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001219 BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001220
1221 // Set the source-location entry cursor to the current position in
1222 // the stream. This cursor will be used to read the contents of the
1223 // source manager block initially, and then lazily read
1224 // source-location entries as needed.
1225 SLocEntryCursor = F.Stream;
1226
1227 // The stream itself is going to skip over the source manager block.
1228 if (F.Stream.SkipBlock()) {
1229 Error("malformed block record in AST file");
1230 return true;
1231 }
1232
1233 // Enter the source manager block.
1234 if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
1235 Error("malformed source manager block record in AST file");
1236 return true;
1237 }
1238
1239 RecordData Record;
1240 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001241 llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001242
Chris Lattnere7b154b2013-01-19 21:39:22 +00001243 switch (E.Kind) {
1244 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1245 case llvm::BitstreamEntry::Error:
1246 Error("malformed block record in AST file");
1247 return true;
1248 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00001249 return false;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001250 case llvm::BitstreamEntry::Record:
1251 // The interesting case.
1252 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001253 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001254
Guy Benyei11169dd2012-12-18 14:30:41 +00001255 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001256 Record.clear();
Chris Lattner15c3e7d2013-01-21 18:28:26 +00001257 StringRef Blob;
1258 switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001259 default: // Default behavior: ignore.
1260 break;
1261
1262 case SM_SLOC_FILE_ENTRY:
1263 case SM_SLOC_BUFFER_ENTRY:
1264 case SM_SLOC_EXPANSION_ENTRY:
1265 // Once we hit one of the source location entries, we're done.
1266 return false;
1267 }
1268 }
1269}
1270
1271/// \brief If a header file is not found at the path that we expect it to be
1272/// and the PCH file was moved from its original location, try to resolve the
1273/// file by assuming that header+PCH were moved together and the header is in
1274/// the same place relative to the PCH.
1275static std::string
1276resolveFileRelativeToOriginalDir(const std::string &Filename,
1277 const std::string &OriginalDir,
1278 const std::string &CurrDir) {
1279 assert(OriginalDir != CurrDir &&
1280 "No point trying to resolve the file if the PCH dir didn't change");
1281 using namespace llvm::sys;
1282 SmallString<128> filePath(Filename);
1283 fs::make_absolute(filePath);
1284 assert(path::is_absolute(OriginalDir));
1285 SmallString<128> currPCHPath(CurrDir);
1286
1287 path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
1288 fileDirE = path::end(path::parent_path(filePath));
1289 path::const_iterator origDirI = path::begin(OriginalDir),
1290 origDirE = path::end(OriginalDir);
1291 // Skip the common path components from filePath and OriginalDir.
1292 while (fileDirI != fileDirE && origDirI != origDirE &&
1293 *fileDirI == *origDirI) {
1294 ++fileDirI;
1295 ++origDirI;
1296 }
1297 for (; origDirI != origDirE; ++origDirI)
1298 path::append(currPCHPath, "..");
1299 path::append(currPCHPath, fileDirI, fileDirE);
1300 path::append(currPCHPath, path::filename(Filename));
1301 return currPCHPath.str();
1302}
1303
1304bool ASTReader::ReadSLocEntry(int ID) {
1305 if (ID == 0)
1306 return false;
1307
1308 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1309 Error("source location entry ID out-of-range for AST file");
1310 return true;
1311 }
1312
Richard Smithaada85c2016-02-06 02:06:43 +00001313 // Local helper to read the (possibly-compressed) buffer data following the
1314 // entry record.
1315 auto ReadBuffer = [this](
1316 BitstreamCursor &SLocEntryCursor,
1317 StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
1318 RecordData Record;
1319 StringRef Blob;
1320 unsigned Code = SLocEntryCursor.ReadCode();
1321 unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
1322
1323 if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
George Rimarc39f5492017-01-17 15:45:31 +00001324 if (!llvm::zlib::isAvailable()) {
1325 Error("zlib is not available");
1326 return nullptr;
1327 }
Richard Smithaada85c2016-02-06 02:06:43 +00001328 SmallString<0> Uncompressed;
George Rimarc39f5492017-01-17 15:45:31 +00001329 if (llvm::Error E =
1330 llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
1331 Error("could not decompress embedded file contents: " +
1332 llvm::toString(std::move(E)));
Richard Smithaada85c2016-02-06 02:06:43 +00001333 return nullptr;
1334 }
1335 return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
1336 } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
1337 return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
1338 } else {
1339 Error("AST record has invalid code");
1340 return nullptr;
1341 }
1342 };
1343
Guy Benyei11169dd2012-12-18 14:30:41 +00001344 ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
1345 F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001346 BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001347 unsigned BaseOffset = F->SLocEntryBaseOffset;
1348
1349 ++NumSLocEntriesRead;
Chris Lattnere7b154b2013-01-19 21:39:22 +00001350 llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
1351 if (Entry.Kind != llvm::BitstreamEntry::Record) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 Error("incorrectly-formatted source location entry in AST file");
1353 return true;
1354 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001355
Guy Benyei11169dd2012-12-18 14:30:41 +00001356 RecordData Record;
Chris Lattner0e6c9402013-01-20 02:38:54 +00001357 StringRef Blob;
1358 switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001359 default:
1360 Error("incorrectly-formatted source location entry in AST file");
1361 return true;
1362
1363 case SM_SLOC_FILE_ENTRY: {
1364 // We will detect whether a file changed and return 'Failure' for it, but
1365 // we will also try to fail gracefully by setting up the SLocEntry.
1366 unsigned InputID = Record[4];
1367 InputFile IF = getInputFile(*F, InputID);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001368 const FileEntry *File = IF.getFile();
1369 bool OverriddenBuffer = IF.isOverridden();
Guy Benyei11169dd2012-12-18 14:30:41 +00001370
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00001371 // Note that we only check if a File was returned. If it was out-of-date
1372 // we have complained but we will continue creating a FileID to recover
1373 // gracefully.
1374 if (!File)
Guy Benyei11169dd2012-12-18 14:30:41 +00001375 return true;
1376
1377 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
1378 if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
1379 // This is the module's main file.
1380 IncludeLoc = getImportLocation(F);
1381 }
1382 SrcMgr::CharacteristicKind
1383 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1384 FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
1385 ID, BaseOffset + Record[0]);
1386 SrcMgr::FileInfo &FileInfo =
1387 const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
1388 FileInfo.NumCreatedFIDs = Record[5];
1389 if (Record[3])
1390 FileInfo.setHasLineDirectives();
1391
1392 const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
1393 unsigned NumFileDecls = Record[7];
1394 if (NumFileDecls) {
1395 assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
1396 FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
1397 NumFileDecls));
1398 }
Richard Smithaada85c2016-02-06 02:06:43 +00001399
Guy Benyei11169dd2012-12-18 14:30:41 +00001400 const SrcMgr::ContentCache *ContentCache
1401 = SourceMgr.getOrCreateContentCache(File,
1402 /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
1403 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001404 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1405 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001406 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1407 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001409 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 }
1411
1412 break;
1413 }
1414
1415 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001416 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001417 unsigned Offset = Record[0];
1418 SrcMgr::CharacteristicKind
1419 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1420 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001421 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 IncludeLoc = getImportLocation(F);
1423 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001424
Richard Smithaada85c2016-02-06 02:06:43 +00001425 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1426 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001428 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001429 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001430 break;
1431 }
1432
1433 case SM_SLOC_EXPANSION_ENTRY: {
1434 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1435 SourceMgr.createExpansionLoc(SpellingLoc,
1436 ReadSourceLocation(*F, Record[2]),
1437 ReadSourceLocation(*F, Record[3]),
1438 Record[4],
1439 ID,
1440 BaseOffset + Record[0]);
1441 break;
1442 }
1443 }
1444
1445 return false;
1446}
1447
1448std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1449 if (ID == 0)
1450 return std::make_pair(SourceLocation(), "");
1451
1452 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1453 Error("source location entry ID out-of-range for AST file");
1454 return std::make_pair(SourceLocation(), "");
1455 }
1456
1457 // Find which module file this entry lands in.
1458 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001459 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 return std::make_pair(SourceLocation(), "");
1461
1462 // FIXME: Can we map this down to a particular submodule? That would be
1463 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001464 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001465}
1466
1467/// \brief Find the location where the module F is imported.
1468SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1469 if (F->ImportLoc.isValid())
1470 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001471
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 // Otherwise we have a PCH. It's considered to be "imported" at the first
1473 // location of its includer.
1474 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001475 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001476 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001477 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 return F->ImportedBy[0]->FirstLoc;
1480}
1481
1482/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1483/// specified cursor. Read the abbreviations that are at the top of the block
1484/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001485bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001486 if (Cursor.EnterSubBlock(BlockID))
1487 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001488
1489 while (true) {
1490 uint64_t Offset = Cursor.GetCurrentBitNo();
1491 unsigned Code = Cursor.ReadCode();
1492
1493 // We expect all abbrevs to be at the start of the block.
1494 if (Code != llvm::bitc::DEFINE_ABBREV) {
1495 Cursor.JumpToBit(Offset);
1496 return false;
1497 }
1498 Cursor.ReadAbbrevRecord();
1499 }
1500}
1501
Richard Smithe40f2ba2013-08-07 21:41:30 +00001502Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001503 unsigned &Idx) {
1504 Token Tok;
1505 Tok.startToken();
1506 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1507 Tok.setLength(Record[Idx++]);
1508 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1509 Tok.setIdentifierInfo(II);
1510 Tok.setKind((tok::TokenKind)Record[Idx++]);
1511 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1512 return Tok;
1513}
1514
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001515MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001516 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001517
1518 // Keep track of where we are in the stream, then jump back there
1519 // after reading this macro.
1520 SavedStreamPosition SavedPosition(Stream);
1521
1522 Stream.JumpToBit(Offset);
1523 RecordData Record;
1524 SmallVector<IdentifierInfo*, 16> MacroArgs;
Craig Toppera13603a2014-05-22 05:54:18 +00001525 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001526
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001528 // Advance to the next record, but if we get to the end of the block, don't
1529 // pop it (removing all the abbreviations from the cursor) since we want to
1530 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001531 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001532 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001533
Chris Lattnerefa77172013-01-20 00:00:22 +00001534 switch (Entry.Kind) {
1535 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1536 case llvm::BitstreamEntry::Error:
1537 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001538 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001539 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001540 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001541 case llvm::BitstreamEntry::Record:
1542 // The interesting case.
1543 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001544 }
1545
1546 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001547 Record.clear();
1548 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001549 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001551 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001552 case PP_MACRO_DIRECTIVE_HISTORY:
1553 return Macro;
1554
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 case PP_MACRO_OBJECT_LIKE:
1556 case PP_MACRO_FUNCTION_LIKE: {
1557 // If we already have a macro, that means that we've hit the end
1558 // of the definition of the macro we were looking for. We're
1559 // done.
1560 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001561 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001562
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001563 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001564 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001565 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001566 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001567 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001568 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001569
Guy Benyei11169dd2012-12-18 14:30:41 +00001570 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1571 // Decode function-like macro info.
1572 bool isC99VarArgs = Record[NextIndex++];
1573 bool isGNUVarArgs = Record[NextIndex++];
1574 bool hasCommaPasting = Record[NextIndex++];
1575 MacroArgs.clear();
1576 unsigned NumArgs = Record[NextIndex++];
1577 for (unsigned i = 0; i != NumArgs; ++i)
1578 MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
1579
1580 // Install function-like macro info.
1581 MI->setIsFunctionLike();
1582 if (isC99VarArgs) MI->setIsC99Varargs();
1583 if (isGNUVarArgs) MI->setIsGNUVarargs();
1584 if (hasCommaPasting) MI->setHasCommaPasting();
Craig Topperd96b3f92015-10-22 04:59:52 +00001585 MI->setArgumentList(MacroArgs, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001586 }
1587
Guy Benyei11169dd2012-12-18 14:30:41 +00001588 // Remember that we saw this macro last so that we add the tokens that
1589 // form its body to it.
1590 Macro = MI;
1591
1592 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1593 Record[NextIndex]) {
1594 // We have a macro definition. Register the association
1595 PreprocessedEntityID
1596 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1597 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001598 PreprocessingRecord::PPEntityID PPID =
1599 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1600 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1601 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001602 if (PPDef)
1603 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001604 }
1605
1606 ++NumMacrosRead;
1607 break;
1608 }
1609
1610 case PP_TOKEN: {
1611 // If we see a TOKEN before a PP_MACRO_*, then the file is
1612 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001613 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001614
John McCallf413f5e2013-05-03 00:10:13 +00001615 unsigned Idx = 0;
1616 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001617 Macro->AddTokenToBody(Tok);
1618 break;
1619 }
1620 }
1621 }
1622}
1623
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001624PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001625ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1626 unsigned LocalID) const {
1627 if (!M.ModuleOffsetMap.empty())
1628 ReadModuleOffsetMap(M);
1629
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001630 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001631 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001632 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001634
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 return LocalID + I->second;
1636}
1637
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001638unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1639 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001640}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001641
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001642HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001643HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001644 internal_key_type ikey = {FE->getSize(),
1645 M.HasTimestamps ? FE->getModificationTime() : 0,
1646 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001647 return ikey;
1648}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001649
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001650bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001651 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001652 return false;
1653
Mehdi Amini004b9c72016-10-10 22:52:47 +00001654 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001655 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001656
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001658 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001659 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1660 if (!Key.Imported)
1661 return FileMgr.getFile(Key.Filename);
1662
1663 std::string Resolved = Key.Filename;
1664 Reader.ResolveImportedPath(M, Resolved);
1665 return FileMgr.getFile(Resolved);
1666 };
1667
1668 const FileEntry *FEA = GetFile(a);
1669 const FileEntry *FEB = GetFile(b);
1670 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001671}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001672
Guy Benyei11169dd2012-12-18 14:30:41 +00001673std::pair<unsigned, unsigned>
1674HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001675 using namespace llvm::support;
1676 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001677 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001678 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001679}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001680
1681HeaderFileInfoTrait::internal_key_type
1682HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001683 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001684 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001685 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1686 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001687 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001688 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001689 return ikey;
1690}
1691
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001692HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001693HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001694 unsigned DataLen) {
1695 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001696 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001697 HeaderFileInfo HFI;
1698 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001699 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
1700 HFI.isImport |= (Flags >> 4) & 0x01;
1701 HFI.isPragmaOnce |= (Flags >> 3) & 0x01;
1702 HFI.DirInfo = (Flags >> 1) & 0x03;
Guy Benyei11169dd2012-12-18 14:30:41 +00001703 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001704 // FIXME: Find a better way to handle this. Maybe just store a
1705 // "has been included" flag?
1706 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1707 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001708 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1709 M, endian::readNext<uint32_t, little, unaligned>(d));
1710 if (unsigned FrameworkOffset =
1711 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001712 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 // since 0 is used as an indicator for "no framework name".
1714 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1715 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1716 }
Richard Smith386bb072015-08-18 23:42:23 +00001717
1718 assert((End - d) % 4 == 0 &&
1719 "Wrong data length in HeaderFileInfo deserialization");
1720 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001721 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001722 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1723 LocalSMID >>= 2;
1724
1725 // This header is part of a module. Associate it with the module to enable
1726 // implicit module import.
1727 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1728 Module *Mod = Reader.getSubmodule(GlobalSMID);
1729 FileManager &FileMgr = Reader.getFileManager();
1730 ModuleMap &ModMap =
1731 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1732
1733 std::string Filename = key.Filename;
1734 if (key.Imported)
1735 Reader.ResolveImportedPath(M, Filename);
1736 // FIXME: This is not always the right filename-as-written, but we're not
1737 // going to use this information to rebuild the module, so it doesn't make
1738 // a lot of difference.
1739 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001740 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1741 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001742 }
1743
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 // This HeaderFileInfo was externally loaded.
1745 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001746 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 return HFI;
1748}
1749
Richard Smithd7329392015-04-21 21:46:32 +00001750void ASTReader::addPendingMacro(IdentifierInfo *II,
1751 ModuleFile *M,
1752 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001753 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1754 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001755}
1756
1757void ASTReader::ReadDefinedMacros() {
1758 // Note that we are loading defined macros.
1759 Deserializing Macros(this);
1760
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001761 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1762 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001763
1764 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001765 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 continue;
1767
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001768 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001769 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001770
1771 RecordData Record;
1772 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001773 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001774
Chris Lattnere7b154b2013-01-19 21:39:22 +00001775 switch (E.Kind) {
1776 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1777 case llvm::BitstreamEntry::Error:
1778 Error("malformed block record in AST file");
1779 return;
1780 case llvm::BitstreamEntry::EndBlock:
1781 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001782
Chris Lattnere7b154b2013-01-19 21:39:22 +00001783 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001784 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001785 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001786 default: // Default behavior: ignore.
1787 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001788
Chris Lattnere7b154b2013-01-19 21:39:22 +00001789 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001790 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001791 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001792 if (II->isOutOfDate())
1793 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001794 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001795 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001796
Chris Lattnere7b154b2013-01-19 21:39:22 +00001797 case PP_TOKEN:
1798 // Ignore tokens.
1799 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 break;
1802 }
1803 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001804 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001805 }
1806}
1807
1808namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001809
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 /// \brief Visitor class used to look up identifirs in an AST file.
1811 class IdentifierLookupVisitor {
1812 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001813 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001814 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001815 unsigned &NumIdentifierLookups;
1816 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001818
Guy Benyei11169dd2012-12-18 14:30:41 +00001819 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001820 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1821 unsigned &NumIdentifierLookups,
1822 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001823 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1824 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001825 NumIdentifierLookups(NumIdentifierLookups),
1826 NumIdentifierLookupHits(NumIdentifierLookupHits),
1827 Found()
1828 {
1829 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001830
1831 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001833 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001835
Guy Benyei11169dd2012-12-18 14:30:41 +00001836 ASTIdentifierLookupTable *IdTable
1837 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1838 if (!IdTable)
1839 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001840
1841 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001842 Found);
1843 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001844 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001845 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001846 if (Pos == IdTable->end())
1847 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001848
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 // Dereferencing the iterator has the effect of building the
1850 // IdentifierInfo node and populating it with the various
1851 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001852 ++NumIdentifierLookupHits;
1853 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 return true;
1855 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001856
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 // \brief Retrieve the identifier info found within the module
1858 // files.
1859 IdentifierInfo *getIdentifierInfo() const { return Found; }
1860 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001861
1862} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001863
1864void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1865 // Note that we are loading an identifier.
1866 Deserializing AnIdentifier(this);
1867
1868 unsigned PriorGeneration = 0;
1869 if (getContext().getLangOpts().Modules)
1870 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001871
1872 // If there is a global index, look there first to determine which modules
1873 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001874 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001875 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001876 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001877 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1878 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001879 }
1880 }
1881
Douglas Gregor7211ac12013-01-25 23:32:03 +00001882 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001883 NumIdentifierLookups,
1884 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001885 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 markIdentifierUpToDate(&II);
1887}
1888
1889void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1890 if (!II)
1891 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001892
Guy Benyei11169dd2012-12-18 14:30:41 +00001893 II->setOutOfDate(false);
1894
1895 // Update the generation for this identifier.
1896 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001897 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001898}
1899
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001900void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1901 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001902 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001903
1904 BitstreamCursor &Cursor = M.MacroCursor;
1905 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001906 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001907
Richard Smith713369b2015-04-23 20:40:50 +00001908 struct ModuleMacroRecord {
1909 SubmoduleID SubModID;
1910 MacroInfo *MI;
1911 SmallVector<SubmoduleID, 8> Overrides;
1912 };
1913 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001914
Richard Smithd7329392015-04-21 21:46:32 +00001915 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1916 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1917 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001918 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001919 while (true) {
1920 llvm::BitstreamEntry Entry =
1921 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1922 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1923 Error("malformed block record in AST file");
1924 return;
1925 }
1926
1927 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001928 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001929 case PP_MACRO_DIRECTIVE_HISTORY:
1930 break;
1931
1932 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001933 ModuleMacros.push_back(ModuleMacroRecord());
1934 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001935 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1936 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001937 for (int I = 2, N = Record.size(); I != N; ++I)
1938 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001939 continue;
1940 }
1941
1942 default:
1943 Error("malformed block record in AST file");
1944 return;
1945 }
1946
1947 // We found the macro directive history; that's the last record
1948 // for this macro.
1949 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001950 }
1951
Richard Smithd7329392015-04-21 21:46:32 +00001952 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001953 {
1954 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001955 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001956 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001957 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001958 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001959 Module *Mod = getSubmodule(ModID);
1960 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001961 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001962 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001963 }
1964
1965 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001966 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001967 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001968 }
1969 }
1970
1971 // Don't read the directive history for a module; we don't have anywhere
1972 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001973 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001974 return;
1975
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001976 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001977 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001978 unsigned Idx = 0, N = Record.size();
1979 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001980 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001981 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001982 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1983 switch (K) {
1984 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001985 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001986 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001987 break;
1988 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001989 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001990 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001991 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001992 }
1993 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001994 bool isPublic = Record[Idx++];
1995 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1996 break;
1997 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001998
1999 if (!Latest)
2000 Latest = MD;
2001 if (Earliest)
2002 Earliest->setPrevious(MD);
2003 Earliest = MD;
2004 }
2005
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002006 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002007 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002008}
2009
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002010ASTReader::InputFileInfo
2011ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002012 // Go find this input file.
2013 BitstreamCursor &Cursor = F.InputFilesCursor;
2014 SavedStreamPosition SavedPosition(Cursor);
2015 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2016
2017 unsigned Code = Cursor.ReadCode();
2018 RecordData Record;
2019 StringRef Blob;
2020
2021 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2022 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2023 "invalid record type for input file");
2024 (void)Result;
2025
2026 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002027 InputFileInfo R;
2028 R.StoredSize = static_cast<off_t>(Record[1]);
2029 R.StoredTime = static_cast<time_t>(Record[2]);
2030 R.Overridden = static_cast<bool>(Record[3]);
2031 R.Transient = static_cast<bool>(Record[4]);
2032 R.Filename = Blob;
2033 ResolveImportedPath(F, R.Filename);
Hans Wennborg73945142014-03-14 17:45:06 +00002034 return R;
Ben Langmuir198c1682014-03-07 07:27:49 +00002035}
2036
Manman Renc8c94152016-10-21 23:35:03 +00002037static unsigned moduleKindForDiagnostic(ModuleKind Kind);
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002038InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002039 // If this ID is bogus, just return an empty input file.
2040 if (ID == 0 || ID > F.InputFilesLoaded.size())
2041 return InputFile();
2042
2043 // If we've already loaded this input file, return it.
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002044 if (F.InputFilesLoaded[ID-1].getFile())
Guy Benyei11169dd2012-12-18 14:30:41 +00002045 return F.InputFilesLoaded[ID-1];
2046
Argyrios Kyrtzidis9308f0a2014-01-08 19:13:34 +00002047 if (F.InputFilesLoaded[ID-1].isNotFound())
2048 return InputFile();
2049
Guy Benyei11169dd2012-12-18 14:30:41 +00002050 // Go find this input file.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002051 BitstreamCursor &Cursor = F.InputFilesCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00002052 SavedStreamPosition SavedPosition(Cursor);
2053 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002054
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002055 InputFileInfo FI = readInputFileInfo(F, ID);
2056 off_t StoredSize = FI.StoredSize;
2057 time_t StoredTime = FI.StoredTime;
2058 bool Overridden = FI.Overridden;
Richard Smitha8cfffa2015-11-26 02:04:16 +00002059 bool Transient = FI.Transient;
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002060 StringRef Filename = FI.Filename;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002061
Richard Smitha8cfffa2015-11-26 02:04:16 +00002062 const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
Ben Langmuir198c1682014-03-07 07:27:49 +00002063
2064 // If we didn't find the file, resolve it relative to the
2065 // original directory from which this AST file was created.
Craig Toppera13603a2014-05-22 05:54:18 +00002066 if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
Ben Langmuir198c1682014-03-07 07:27:49 +00002067 F.OriginalDir != CurrentDir) {
2068 std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
2069 F.OriginalDir,
2070 CurrentDir);
2071 if (!Resolved.empty())
2072 File = FileMgr.getFile(Resolved);
2073 }
2074
2075 // For an overridden file, create a virtual file with the stored
2076 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002077 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002078 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002079
Craig Toppera13603a2014-05-22 05:54:18 +00002080 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002081 if (Complain) {
2082 std::string ErrorStr = "could not find file '";
2083 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002084 ErrorStr += "' referenced by AST file '";
2085 ErrorStr += F.FileName;
2086 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002087 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002088 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002089 // Record that we didn't find the file.
2090 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2091 return InputFile();
2092 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002093
Ben Langmuir198c1682014-03-07 07:27:49 +00002094 // Check if there was a request to override the contents of the file
2095 // that was part of the precompiled header. Overridding such a file
2096 // can lead to problems when lexing using the source locations from the
2097 // PCH.
2098 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002099 // FIXME: Reject if the overrides are different.
2100 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002101 if (Complain)
2102 Error(diag::err_fe_pch_file_overridden, Filename);
2103 // After emitting the diagnostic, recover by disabling the override so
2104 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002105 //
2106 // FIXME: This recovery is just as broken as the original state; there may
2107 // be another precompiled module that's using the overridden contents, or
2108 // we might be half way through parsing it. Instead, we should treat the
2109 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002110 SM.disableFileContentsOverride(File);
2111 // The FileEntry is a virtual file entry with the size of the contents
2112 // that would override the original contents. Set it to the original's
2113 // size/time.
2114 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2115 StoredSize, StoredTime);
2116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002117
Ben Langmuir198c1682014-03-07 07:27:49 +00002118 bool IsOutOfDate = false;
2119
2120 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002121 if (!Overridden && //
2122 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002123 (StoredTime && StoredTime != File->getModificationTime() &&
2124 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002125 )) {
2126 if (Complain) {
2127 // Build a list of the PCH imports that got us here (in reverse).
2128 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2129 while (ImportStack.back()->ImportedBy.size() > 0)
2130 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002131
Ben Langmuir198c1682014-03-07 07:27:49 +00002132 // The top-level PCH is stale.
2133 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002134 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2135 if (DiagnosticKind == 0)
2136 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2137 else if (DiagnosticKind == 1)
2138 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2139 else
2140 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002141
Ben Langmuir198c1682014-03-07 07:27:49 +00002142 // Print the import stack.
2143 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2144 Diag(diag::note_pch_required_by)
2145 << Filename << ImportStack[0]->FileName;
2146 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002147 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002148 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002149 }
2150
Ben Langmuir198c1682014-03-07 07:27:49 +00002151 if (!Diags.isDiagnosticInFlight())
2152 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002153 }
2154
Ben Langmuir198c1682014-03-07 07:27:49 +00002155 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002157 // FIXME: If the file is overridden and we've already opened it,
2158 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002159
Richard Smitha8cfffa2015-11-26 02:04:16 +00002160 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002161
2162 // Note that we've loaded this input file.
2163 F.InputFilesLoaded[ID-1] = IF;
2164 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002165}
2166
Richard Smith7ed1bc92014-12-05 22:42:13 +00002167/// \brief If we are loading a relocatable PCH or module file, and the filename
2168/// is not an absolute path, add the system or module root to the beginning of
2169/// the file name.
2170void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2171 // Resolve relative to the base directory, if we have one.
2172 if (!M.BaseDirectory.empty())
2173 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002174}
2175
Richard Smith7ed1bc92014-12-05 22:42:13 +00002176void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002177 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2178 return;
2179
Richard Smith7ed1bc92014-12-05 22:42:13 +00002180 SmallString<128> Buffer;
2181 llvm::sys::path::append(Buffer, Prefix, Filename);
2182 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002183}
2184
Richard Smith0f99d6a2015-08-09 08:48:41 +00002185static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2186 switch (ARR) {
2187 case ASTReader::Failure: return true;
2188 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2189 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2190 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2191 case ASTReader::ConfigurationMismatch:
2192 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2193 case ASTReader::HadErrors: return true;
2194 case ASTReader::Success: return false;
2195 }
2196
2197 llvm_unreachable("unknown ASTReadResult");
2198}
2199
Richard Smith0516b182015-09-08 19:40:14 +00002200ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2201 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2202 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002203 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002204 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2205 return Failure;
2206
2207 // Read all of the records in the options block.
2208 RecordData Record;
2209 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002210 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002211 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002212
Richard Smith0516b182015-09-08 19:40:14 +00002213 switch (Entry.Kind) {
2214 case llvm::BitstreamEntry::Error:
2215 case llvm::BitstreamEntry::SubBlock:
2216 return Failure;
2217
2218 case llvm::BitstreamEntry::EndBlock:
2219 return Result;
2220
2221 case llvm::BitstreamEntry::Record:
2222 // The interesting case.
2223 break;
2224 }
2225
2226 // Read and process a record.
2227 Record.clear();
2228 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2229 case LANGUAGE_OPTIONS: {
2230 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2231 if (ParseLanguageOptions(Record, Complain, Listener,
2232 AllowCompatibleConfigurationMismatch))
2233 Result = ConfigurationMismatch;
2234 break;
2235 }
2236
2237 case TARGET_OPTIONS: {
2238 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2239 if (ParseTargetOptions(Record, Complain, Listener,
2240 AllowCompatibleConfigurationMismatch))
2241 Result = ConfigurationMismatch;
2242 break;
2243 }
2244
Richard Smith0516b182015-09-08 19:40:14 +00002245 case FILE_SYSTEM_OPTIONS: {
2246 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2247 if (!AllowCompatibleConfigurationMismatch &&
2248 ParseFileSystemOptions(Record, Complain, Listener))
2249 Result = ConfigurationMismatch;
2250 break;
2251 }
2252
2253 case HEADER_SEARCH_OPTIONS: {
2254 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2255 if (!AllowCompatibleConfigurationMismatch &&
2256 ParseHeaderSearchOptions(Record, Complain, Listener))
2257 Result = ConfigurationMismatch;
2258 break;
2259 }
2260
2261 case PREPROCESSOR_OPTIONS:
2262 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2263 if (!AllowCompatibleConfigurationMismatch &&
2264 ParsePreprocessorOptions(Record, Complain, Listener,
2265 SuggestedPredefines))
2266 Result = ConfigurationMismatch;
2267 break;
2268 }
2269 }
2270}
2271
Guy Benyei11169dd2012-12-18 14:30:41 +00002272ASTReader::ASTReadResult
2273ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002274 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002275 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002277 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002278 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002279
2280 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2281 Error("malformed block record in AST file");
2282 return Failure;
2283 }
2284
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002285 // Lambda to read the unhashed control block the first time it's called.
2286 //
2287 // For PCM files, the unhashed control block cannot be read until after the
2288 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2289 // need to look ahead before reading the IMPORTS record. For consistency,
2290 // this block is always read somehow (see BitstreamEntry::EndBlock).
2291 bool HasReadUnhashedControlBlock = false;
2292 auto readUnhashedControlBlockOnce = [&]() {
2293 if (!HasReadUnhashedControlBlock) {
2294 HasReadUnhashedControlBlock = true;
2295 if (ASTReadResult Result =
2296 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2297 return Result;
2298 }
2299 return Success;
2300 };
2301
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 // Read all of the records and blocks in the control block.
2303 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002304 unsigned NumInputs = 0;
2305 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002306 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002307 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002308
Chris Lattnere7b154b2013-01-19 21:39:22 +00002309 switch (Entry.Kind) {
2310 case llvm::BitstreamEntry::Error:
2311 Error("malformed block record in AST file");
2312 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002313 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002314 // Validate the module before returning. This call catches an AST with
2315 // no module name and no imports.
2316 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2317 return Result;
2318
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002319 // Validate input files.
2320 const HeaderSearchOptions &HSOpts =
2321 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002322
Richard Smitha1825302014-10-23 22:18:29 +00002323 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002324 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2325 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002326 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2327 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002328 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002329
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002330 // If we are reading a module, we will create a verification timestamp,
2331 // so we verify all input files. Otherwise, verify only user input
2332 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002333
2334 unsigned N = NumUserInputs;
2335 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002336 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002337 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002338 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002339 N = NumInputs;
2340
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002341 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002342 InputFile IF = getInputFile(F, I+1, Complain);
2343 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002345 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002346 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002347
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002348 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002349 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002350
Ben Langmuircb69b572014-03-07 06:40:32 +00002351 if (Listener && Listener->needsInputFileVisitation()) {
2352 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2353 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002354 for (unsigned I = 0; I < N; ++I) {
2355 bool IsSystem = I >= NumUserInputs;
2356 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002357 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002358 F.Kind == MK_ExplicitModule ||
2359 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002360 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002361 }
2362
Richard Smith8a308ec2015-11-05 00:54:55 +00002363 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002364 }
2365
Chris Lattnere7b154b2013-01-19 21:39:22 +00002366 case llvm::BitstreamEntry::SubBlock:
2367 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 case INPUT_FILES_BLOCK_ID:
2369 F.InputFilesCursor = Stream;
2370 if (Stream.SkipBlock() || // Skip with the main cursor
2371 // Read the abbreviations
2372 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2373 Error("malformed block record in AST file");
2374 return Failure;
2375 }
2376 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002377
2378 case OPTIONS_BLOCK_ID:
2379 // If we're reading the first module for this group, check its options
2380 // are compatible with ours. For modules it imports, no further checking
2381 // is required, because we checked them when we built it.
2382 if (Listener && !ImportedBy) {
2383 // Should we allow the configuration of the module file to differ from
2384 // the configuration of the current translation unit in a compatible
2385 // way?
2386 //
2387 // FIXME: Allow this for files explicitly specified with -include-pch.
2388 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002389 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002390
Richard Smith8a308ec2015-11-05 00:54:55 +00002391 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2392 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002393 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002394 if (Result == Failure) {
2395 Error("malformed block record in AST file");
2396 return Result;
2397 }
2398
Richard Smith8a308ec2015-11-05 00:54:55 +00002399 if (DisableValidation ||
2400 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2401 Result = Success;
2402
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002403 // If we can't load the module, exit early since we likely
2404 // will rebuild the module anyway. The stream may be in the
2405 // middle of a block.
2406 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002407 return Result;
2408 } else if (Stream.SkipBlock()) {
2409 Error("malformed block record in AST file");
2410 return Failure;
2411 }
2412 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002413
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002415 if (Stream.SkipBlock()) {
2416 Error("malformed block record in AST file");
2417 return Failure;
2418 }
2419 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002420 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002421
Chris Lattnere7b154b2013-01-19 21:39:22 +00002422 case llvm::BitstreamEntry::Record:
2423 // The interesting case.
2424 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 }
2426
2427 // Read and process a record.
2428 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002429 StringRef Blob;
2430 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002431 case METADATA: {
2432 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2433 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002434 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2435 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002436 return VersionMismatch;
2437 }
2438
Richard Smithe75ee0f2015-08-17 07:13:32 +00002439 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002440 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2441 Diag(diag::err_pch_with_compiler_errors);
2442 return HadErrors;
2443 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002444 if (hasErrors) {
2445 Diags.ErrorOccurred = true;
2446 Diags.UncompilableErrorOccurred = true;
2447 Diags.UnrecoverableErrorOccurred = true;
2448 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002449
2450 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002451 // Relative paths in a relocatable PCH are relative to our sysroot.
2452 if (F.RelocatablePCH)
2453 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002454
Richard Smithe75ee0f2015-08-17 07:13:32 +00002455 F.HasTimestamps = Record[5];
2456
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002458 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002459 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2460 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002461 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002462 return VersionMismatch;
2463 }
2464 break;
2465 }
2466
2467 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002468 // Validate the AST before processing any imports (otherwise, untangling
2469 // them can be error-prone and expensive). A module will have a name and
2470 // will already have been validated, but this catches the PCH case.
2471 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2472 return Result;
2473
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002474 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002475 unsigned Idx = 0, N = Record.size();
2476 while (Idx < N) {
2477 // Read information about the AST file.
2478 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2479 // The import location will be the local one for now; we will adjust
2480 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002481 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002482 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002483 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002484 off_t StoredSize = (off_t)Record[Idx++];
2485 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002486 ASTFileSignature StoredSignature = {
2487 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2488 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2489 (uint32_t)Record[Idx++]}}};
Richard Smith7ed1bc92014-12-05 22:42:13 +00002490 auto ImportedFile = ReadPath(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002491
Richard Smith0f99d6a2015-08-09 08:48:41 +00002492 // If our client can't cope with us being out of date, we can't cope with
2493 // our dependency being missing.
2494 unsigned Capabilities = ClientLoadCapabilities;
2495 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2496 Capabilities &= ~ARR_Missing;
2497
Guy Benyei11169dd2012-12-18 14:30:41 +00002498 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002499 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2500 Loaded, StoredSize, StoredModTime,
2501 StoredSignature, Capabilities);
2502
2503 // If we diagnosed a problem, produce a backtrace.
2504 if (isDiagnosedResult(Result, Capabilities))
2505 Diag(diag::note_module_file_imported_by)
2506 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2507
2508 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002509 case Failure: return Failure;
2510 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002511 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 case OutOfDate: return OutOfDate;
2513 case VersionMismatch: return VersionMismatch;
2514 case ConfigurationMismatch: return ConfigurationMismatch;
2515 case HadErrors: return HadErrors;
2516 case Success: break;
2517 }
2518 }
2519 break;
2520 }
2521
Guy Benyei11169dd2012-12-18 14:30:41 +00002522 case ORIGINAL_FILE:
2523 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002524 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002525 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002526 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 break;
2528
2529 case ORIGINAL_FILE_ID:
2530 F.OriginalSourceFileID = FileID::get(Record[0]);
2531 break;
2532
2533 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002534 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002535 break;
2536
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002537 case MODULE_NAME:
2538 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002539 if (Listener)
2540 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002541
2542 // Validate the AST as soon as we have a name so we can exit early on
2543 // failure.
2544 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2545 return Result;
2546
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002547 break;
2548
Richard Smith223d3f22014-12-06 03:21:08 +00002549 case MODULE_DIRECTORY: {
2550 assert(!F.ModuleName.empty() &&
2551 "MODULE_DIRECTORY found before MODULE_NAME");
2552 // If we've already loaded a module map file covering this module, we may
2553 // have a better path for it (relative to the current build).
2554 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2555 if (M && M->Directory) {
2556 // If we're implicitly loading a module, the base directory can't
2557 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002558 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002559 const DirectoryEntry *BuildDir =
2560 PP.getFileManager().getDirectory(Blob);
2561 if (!BuildDir || BuildDir != M->Directory) {
2562 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2563 Diag(diag::err_imported_module_relocated)
2564 << F.ModuleName << Blob << M->Directory->getName();
2565 return OutOfDate;
2566 }
2567 }
2568 F.BaseDirectory = M->Directory->getName();
2569 } else {
2570 F.BaseDirectory = Blob;
2571 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002572 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002573 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002574
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002575 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002576 if (ASTReadResult Result =
2577 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2578 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002579 break;
2580
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002581 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002582 NumInputs = Record[0];
2583 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002584 F.InputFileOffsets =
2585 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002586 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002587 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002588 break;
2589 }
2590 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002591}
2592
Ben Langmuir2c9af442014-04-10 17:57:43 +00002593ASTReader::ASTReadResult
2594ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002595 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002596
2597 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2598 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002599 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002600 }
2601
2602 // Read all of the records and blocks for the AST file.
2603 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002604 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002605 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002606
Chris Lattnere7b154b2013-01-19 21:39:22 +00002607 switch (Entry.Kind) {
2608 case llvm::BitstreamEntry::Error:
2609 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002610 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002611 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002612 // Outside of C++, we do not store a lookup map for the translation unit.
2613 // Instead, mark it as needing a lookup map to be built if this module
2614 // contains any declarations lexically within it (which it always does!).
2615 // This usually has no cost, since we very rarely need the lookup map for
2616 // the translation unit outside C++.
Guy Benyei11169dd2012-12-18 14:30:41 +00002617 DeclContext *DC = Context.getTranslationUnitDecl();
Richard Smithc0fbba72013-04-03 22:49:41 +00002618 if (DC->hasExternalLexicalStorage() &&
2619 !getContext().getLangOpts().CPlusPlus)
Guy Benyei11169dd2012-12-18 14:30:41 +00002620 DC->setMustBuildLookupTable();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002621
Ben Langmuir2c9af442014-04-10 17:57:43 +00002622 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002623 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002624 case llvm::BitstreamEntry::SubBlock:
2625 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 case DECLTYPES_BLOCK_ID:
2627 // We lazily load the decls block, but we want to set up the
2628 // DeclsCursor cursor to point into it. Clone our current bitcode
2629 // cursor to it, enter the block and read the abbrevs in that block.
2630 // With the main cursor, we just skip over it.
2631 F.DeclsCursor = Stream;
2632 if (Stream.SkipBlock() || // Skip with the main cursor.
2633 // Read the abbrevs.
2634 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2635 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002636 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002637 }
2638 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002639
Guy Benyei11169dd2012-12-18 14:30:41 +00002640 case PREPROCESSOR_BLOCK_ID:
2641 F.MacroCursor = Stream;
2642 if (!PP.getExternalSource())
2643 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002644
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 if (Stream.SkipBlock() ||
2646 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2647 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002648 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002649 }
2650 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2651 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002652
Guy Benyei11169dd2012-12-18 14:30:41 +00002653 case PREPROCESSOR_DETAIL_BLOCK_ID:
2654 F.PreprocessorDetailCursor = Stream;
2655 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002656 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002658 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002659 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002660 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002661 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002662 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002663
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 if (!PP.getPreprocessingRecord())
2665 PP.createPreprocessingRecord();
2666 if (!PP.getPreprocessingRecord()->getExternalSource())
2667 PP.getPreprocessingRecord()->SetExternalSource(*this);
2668 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002669
Guy Benyei11169dd2012-12-18 14:30:41 +00002670 case SOURCE_MANAGER_BLOCK_ID:
2671 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002672 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002674
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002676 if (ASTReadResult Result =
2677 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002678 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002680
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002682 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 if (Stream.SkipBlock() ||
2684 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2685 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002686 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 }
2688 CommentsCursors.push_back(std::make_pair(C, &F));
2689 break;
2690 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002691
Guy Benyei11169dd2012-12-18 14:30:41 +00002692 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002693 if (Stream.SkipBlock()) {
2694 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002695 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002696 }
2697 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 }
2699 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002700
Chris Lattnere7b154b2013-01-19 21:39:22 +00002701 case llvm::BitstreamEntry::Record:
2702 // The interesting case.
2703 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 }
2705
2706 // Read and process a record.
2707 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002708 StringRef Blob;
2709 switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002710 default: // Default behavior: ignore.
2711 break;
2712
2713 case TYPE_OFFSET: {
2714 if (F.LocalNumTypes != 0) {
2715 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002716 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002717 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002718 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 F.LocalNumTypes = Record[0];
2720 unsigned LocalBaseTypeIndex = Record[1];
2721 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002722
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 if (F.LocalNumTypes > 0) {
2724 // Introduce the global -> local mapping for types within this module.
2725 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002726
Guy Benyei11169dd2012-12-18 14:30:41 +00002727 // Introduce the local -> global mapping for types within this module.
2728 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002729 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002730 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002731
2732 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 }
2734 break;
2735 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002736
Guy Benyei11169dd2012-12-18 14:30:41 +00002737 case DECL_OFFSET: {
2738 if (F.LocalNumDecls != 0) {
2739 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002740 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002741 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002742 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002743 F.LocalNumDecls = Record[0];
2744 unsigned LocalBaseDeclID = Record[1];
2745 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002748 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 // module.
2750 GlobalDeclMap.insert(
2751 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002752
Guy Benyei11169dd2012-12-18 14:30:41 +00002753 // Introduce the local -> global mapping for declarations within this
2754 // module.
2755 F.DeclRemap.insertOrReplace(
2756 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002757
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 // Introduce the global -> local mapping for declarations within this
2759 // module.
2760 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002761
Ben Langmuir52ca6782014-10-20 16:27:32 +00002762 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2763 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 break;
2765 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002766
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 case TU_UPDATE_LEXICAL: {
2768 DeclContext *TU = Context.getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002769 LexicalContents Contents(
2770 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2771 Blob.data()),
2772 static_cast<unsigned int>(Blob.size() / 4));
2773 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 TU->setHasExternalLexicalStorage(true);
2775 break;
2776 }
2777
2778 case UPDATE_VISIBLE: {
2779 unsigned Idx = 0;
2780 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002781 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002782 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002783 // If we've already loaded the decl, perform the updates when we finish
2784 // loading this block.
2785 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002786 PendingUpdateRecords.push_back(
2787 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 break;
2789 }
2790
2791 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002792 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002794 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2795 (const unsigned char *)F.IdentifierTableData + Record[0],
2796 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2797 (const unsigned char *)F.IdentifierTableData,
2798 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002799
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2801 }
2802 break;
2803
2804 case IDENTIFIER_OFFSET: {
2805 if (F.LocalNumIdentifiers != 0) {
2806 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002807 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002809 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 F.LocalNumIdentifiers = Record[0];
2811 unsigned LocalBaseIdentifierID = Record[1];
2812 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002813
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 if (F.LocalNumIdentifiers > 0) {
2815 // Introduce the global -> local mapping for identifiers within this
2816 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002817 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002818 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002819
Guy Benyei11169dd2012-12-18 14:30:41 +00002820 // Introduce the local -> global mapping for identifiers within this
2821 // module.
2822 F.IdentifierRemap.insertOrReplace(
2823 std::make_pair(LocalBaseIdentifierID,
2824 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002825
Ben Langmuir52ca6782014-10-20 16:27:32 +00002826 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2827 + F.LocalNumIdentifiers);
2828 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 break;
2830 }
2831
Richard Smith33e0f7e2015-07-22 02:08:40 +00002832 case INTERESTING_IDENTIFIERS:
2833 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2834 break;
2835
Ben Langmuir332aafe2014-01-31 01:06:56 +00002836 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002837 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2838 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002840 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 break;
2842
David Blaikie9ffe5a32017-01-30 05:00:26 +00002843 case MODULAR_CODEGEN_DECLS:
2844 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2845 // them (ie: if we're not codegenerating this module).
2846 if (F.Kind == MK_MainFile)
2847 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2848 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2849 break;
2850
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002852 if (SpecialTypes.empty()) {
2853 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2854 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2855 break;
2856 }
2857
2858 if (SpecialTypes.size() != Record.size()) {
2859 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002860 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002861 }
2862
2863 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2864 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2865 if (!SpecialTypes[I])
2866 SpecialTypes[I] = ID;
2867 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2868 // merge step?
2869 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 break;
2871
2872 case STATISTICS:
2873 TotalNumStatements += Record[0];
2874 TotalNumMacros += Record[1];
2875 TotalLexicalDeclContexts += Record[2];
2876 TotalVisibleDeclContexts += Record[3];
2877 break;
2878
2879 case UNUSED_FILESCOPED_DECLS:
2880 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2881 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2882 break;
2883
2884 case DELEGATING_CTORS:
2885 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2886 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2887 break;
2888
2889 case WEAK_UNDECLARED_IDENTIFIERS:
2890 if (Record.size() % 4 != 0) {
2891 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002892 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002893 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002894
2895 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002896 // files. This isn't the way to do it :)
2897 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002898
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 // Translate the weak, undeclared identifiers into global IDs.
2900 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2901 WeakUndeclaredIdentifiers.push_back(
2902 getGlobalIdentifierID(F, Record[I++]));
2903 WeakUndeclaredIdentifiers.push_back(
2904 getGlobalIdentifierID(F, Record[I++]));
2905 WeakUndeclaredIdentifiers.push_back(
2906 ReadSourceLocation(F, Record, I).getRawEncoding());
2907 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2908 }
2909 break;
2910
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002912 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002913 F.LocalNumSelectors = Record[0];
2914 unsigned LocalBaseSelectorID = Record[1];
2915 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002916
Guy Benyei11169dd2012-12-18 14:30:41 +00002917 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002918 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002919 // module.
2920 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002921
2922 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002923 // module.
2924 F.SelectorRemap.insertOrReplace(
2925 std::make_pair(LocalBaseSelectorID,
2926 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002927
2928 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002929 }
2930 break;
2931 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002932
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002934 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002935 if (Record[0])
2936 F.SelectorLookupTable
2937 = ASTSelectorLookupTable::Create(
2938 F.SelectorLookupTableData + Record[0],
2939 F.SelectorLookupTableData,
2940 ASTSelectorLookupTrait(*this, F));
2941 TotalNumMethodPoolEntries += Record[1];
2942 break;
2943
2944 case REFERENCED_SELECTOR_POOL:
2945 if (!Record.empty()) {
2946 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002947 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002948 Record[Idx++]));
2949 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2950 getRawEncoding());
2951 }
2952 }
2953 break;
2954
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002955 case PP_CONDITIONAL_STACK:
2956 if (!Record.empty()) {
2957 SmallVector<PPConditionalInfo, 4> ConditionalStack;
2958 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
2959 auto Loc = ReadSourceLocation(F, Record, Idx);
2960 bool WasSkipping = Record[Idx++];
2961 bool FoundNonSkip = Record[Idx++];
2962 bool FoundElse = Record[Idx++];
2963 ConditionalStack.push_back(
2964 {Loc, WasSkipping, FoundNonSkip, FoundElse});
2965 }
2966 PP.setReplayablePreambleConditionalStack(ConditionalStack);
2967 }
2968 break;
2969
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 case PP_COUNTER_VALUE:
2971 if (!Record.empty() && Listener)
2972 Listener->ReadCounter(F, Record[0]);
2973 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002974
Guy Benyei11169dd2012-12-18 14:30:41 +00002975 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002976 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002977 F.NumFileSortedDecls = Record[0];
2978 break;
2979
2980 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002981 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 F.LocalNumSLocEntries = Record[0];
2983 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002984 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00002985 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00002987 if (!F.SLocEntryBaseID) {
2988 Error("ran out of source locations");
2989 break;
2990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 // Make our entry in the range map. BaseID is negative and growing, so
2992 // we invert it. Because we invert it, though, we need the other end of
2993 // the range.
2994 unsigned RangeStart =
2995 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
2996 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
2997 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
2998
2999 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3000 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3001 GlobalSLocOffsetMap.insert(
3002 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3003 - SLocSpaceSize,&F));
3004
3005 // Initialize the remapping table.
3006 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003007 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003008 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003009 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003010 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003011
Guy Benyei11169dd2012-12-18 14:30:41 +00003012 TotalNumSLocEntries += F.LocalNumSLocEntries;
3013 break;
3014 }
3015
Richard Smith37a93df2017-02-18 00:32:02 +00003016 case MODULE_OFFSET_MAP:
3017 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003019
3020 case SOURCE_MANAGER_LINE_TABLE:
3021 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003022 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 break;
3024
3025 case SOURCE_LOCATION_PRELOADS: {
3026 // Need to transform from the local view (1-based IDs) to the global view,
3027 // which is based off F.SLocEntryBaseID.
3028 if (!F.PreloadSLocEntries.empty()) {
3029 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003030 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003031 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003032
Guy Benyei11169dd2012-12-18 14:30:41 +00003033 F.PreloadSLocEntries.swap(Record);
3034 break;
3035 }
3036
3037 case EXT_VECTOR_DECLS:
3038 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3039 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3040 break;
3041
3042 case VTABLE_USES:
3043 if (Record.size() % 3 != 0) {
3044 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003045 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003046 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003047
Guy Benyei11169dd2012-12-18 14:30:41 +00003048 // Later tables overwrite earlier ones.
3049 // FIXME: Modules will have some trouble with this. This is clearly not
3050 // the right way to do this.
3051 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003052
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3054 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3055 VTableUses.push_back(
3056 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3057 VTableUses.push_back(Record[Idx++]);
3058 }
3059 break;
3060
Guy Benyei11169dd2012-12-18 14:30:41 +00003061 case PENDING_IMPLICIT_INSTANTIATIONS:
3062 if (PendingInstantiations.size() % 2 != 0) {
3063 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003064 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003065 }
3066
3067 if (Record.size() % 2 != 0) {
3068 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003069 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 }
3071
3072 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3073 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3074 PendingInstantiations.push_back(
3075 ReadSourceLocation(F, Record, I).getRawEncoding());
3076 }
3077 break;
3078
3079 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003080 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003081 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003082 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003083 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3085 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3086 break;
3087
3088 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003089 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3090 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3091 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003092
3093 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003094
Guy Benyei11169dd2012-12-18 14:30:41 +00003095 unsigned StartingID;
3096 if (!PP.getPreprocessingRecord())
3097 PP.createPreprocessingRecord();
3098 if (!PP.getPreprocessingRecord()->getExternalSource())
3099 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003100 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003102 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003103 F.BasePreprocessedEntityID = StartingID;
3104
3105 if (F.NumPreprocessedEntities > 0) {
3106 // Introduce the global -> local mapping for preprocessed entities in
3107 // this module.
3108 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003109
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 // Introduce the local -> global mapping for preprocessed entities in
3111 // this module.
3112 F.PreprocessedEntityRemap.insertOrReplace(
3113 std::make_pair(LocalBasePreprocessedEntityID,
3114 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3115 }
3116
3117 break;
3118 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003119
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 case DECL_UPDATE_OFFSETS: {
3121 if (Record.size() % 2 != 0) {
3122 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003124 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003125 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3126 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3127 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3128
3129 // If we've already loaded the decl, perform the updates when we finish
3130 // loading this block.
3131 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003132 PendingUpdateRecords.push_back(
3133 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003134 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 break;
3136 }
3137
Guy Benyei11169dd2012-12-18 14:30:41 +00003138 case OBJC_CATEGORIES_MAP: {
3139 if (F.LocalNumObjCCategoriesInMap != 0) {
3140 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003141 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003143
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003145 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 break;
3147 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003148
Guy Benyei11169dd2012-12-18 14:30:41 +00003149 case OBJC_CATEGORIES:
3150 F.ObjCCategories.swap(Record);
3151 break;
Richard Smithc2bb8182015-03-24 06:36:48 +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;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003344
3345 case PACK_PRAGMA_OPTIONS: {
3346 if (Record.size() < 3) {
3347 Error("invalid pragma pack record");
3348 return Failure;
3349 }
3350 PragmaPackCurrentValue = Record[0];
3351 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3352 unsigned NumStackEntries = Record[2];
3353 unsigned Idx = 3;
3354 // Reset the stack when importing a new module.
3355 PragmaPackStack.clear();
3356 for (unsigned I = 0; I < NumStackEntries; ++I) {
3357 PragmaPackStackEntry Entry;
3358 Entry.Value = Record[Idx++];
3359 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
3360 PragmaPackStrings.push_back(ReadString(Record, Idx));
3361 Entry.SlotLabel = PragmaPackStrings.back();
3362 PragmaPackStack.push_back(Entry);
3363 }
3364 break;
3365 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003366 }
3367 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003368}
3369
Richard Smith37a93df2017-02-18 00:32:02 +00003370void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3371 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3372
3373 // Additional remapping information.
3374 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3375 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3376 F.ModuleOffsetMap = StringRef();
3377
3378 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3379 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3380 F.SLocRemap.insert(std::make_pair(0U, 0));
3381 F.SLocRemap.insert(std::make_pair(2U, 1));
3382 }
3383
3384 // Continuous range maps we may be updating in our module.
3385 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3386 RemapBuilder;
3387 RemapBuilder SLocRemap(F.SLocRemap);
3388 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3389 RemapBuilder MacroRemap(F.MacroRemap);
3390 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3391 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3392 RemapBuilder SelectorRemap(F.SelectorRemap);
3393 RemapBuilder DeclRemap(F.DeclRemap);
3394 RemapBuilder TypeRemap(F.TypeRemap);
3395
3396 while (Data < DataEnd) {
3397 // FIXME: Looking up dependency modules by filename is horrible.
3398 using namespace llvm::support;
3399 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3400 StringRef Name = StringRef((const char*)Data, Len);
3401 Data += Len;
3402 ModuleFile *OM = ModuleMgr.lookup(Name);
3403 if (!OM) {
3404 std::string Msg =
3405 "SourceLocation remap refers to unknown module, cannot find ";
3406 Msg.append(Name);
3407 Error(Msg);
3408 return;
3409 }
3410
3411 uint32_t SLocOffset =
3412 endian::readNext<uint32_t, little, unaligned>(Data);
3413 uint32_t IdentifierIDOffset =
3414 endian::readNext<uint32_t, little, unaligned>(Data);
3415 uint32_t MacroIDOffset =
3416 endian::readNext<uint32_t, little, unaligned>(Data);
3417 uint32_t PreprocessedEntityIDOffset =
3418 endian::readNext<uint32_t, little, unaligned>(Data);
3419 uint32_t SubmoduleIDOffset =
3420 endian::readNext<uint32_t, little, unaligned>(Data);
3421 uint32_t SelectorIDOffset =
3422 endian::readNext<uint32_t, little, unaligned>(Data);
3423 uint32_t DeclIDOffset =
3424 endian::readNext<uint32_t, little, unaligned>(Data);
3425 uint32_t TypeIndexOffset =
3426 endian::readNext<uint32_t, little, unaligned>(Data);
3427
3428 uint32_t None = std::numeric_limits<uint32_t>::max();
3429
3430 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3431 RemapBuilder &Remap) {
3432 if (Offset != None)
3433 Remap.insert(std::make_pair(Offset,
3434 static_cast<int>(BaseOffset - Offset)));
3435 };
3436 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3437 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3438 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3439 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3440 PreprocessedEntityRemap);
3441 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3442 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3443 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3444 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3445
3446 // Global -> local mappings.
3447 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3448 }
3449}
3450
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003451ASTReader::ASTReadResult
3452ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3453 const ModuleFile *ImportedBy,
3454 unsigned ClientLoadCapabilities) {
3455 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003456 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003457
Manman Ren11f2a472016-08-18 17:42:15 +00003458 if (F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule) {
Richard Smithe842a472014-10-22 02:05:46 +00003459 // For an explicitly-loaded module, we don't care whether the original
3460 // module map file exists or matches.
3461 return Success;
3462 }
3463
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003464 // Try to resolve ModuleName in the current header search context and
3465 // verify that it is found in the same module map file as we saved. If the
3466 // top-level AST file is a main file, skip this check because there is no
3467 // usable header search context.
3468 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003469 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003470 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003471 // An implicitly-loaded module file should have its module listed in some
3472 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003473 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003474 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3475 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3476 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003477 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003478 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3479 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3480 // This module was defined by an imported (explicit) module.
3481 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3482 << ASTFE->getName();
3483 else
3484 // This module was built with a different module map.
3485 Diag(diag::err_imported_module_not_found)
3486 << F.ModuleName << F.FileName << ImportedBy->FileName
3487 << F.ModuleMapPath;
3488 }
3489 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003490 }
3491
Richard Smithe842a472014-10-22 02:05:46 +00003492 assert(M->Name == F.ModuleName && "found module with different name");
3493
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003494 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003495 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003496 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3497 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003498 assert(ImportedBy && "top-level import should be verified");
3499 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3500 Diag(diag::err_imported_module_modmap_changed)
3501 << F.ModuleName << ImportedBy->FileName
3502 << ModMap->getName() << F.ModuleMapPath;
3503 return OutOfDate;
3504 }
3505
3506 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3507 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3508 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003509 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003510 const FileEntry *F =
3511 FileMgr.getFile(Filename, false, false);
3512 if (F == nullptr) {
3513 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3514 Error("could not find file '" + Filename +"' referenced by AST file");
3515 return OutOfDate;
3516 }
3517 AdditionalStoredMaps.insert(F);
3518 }
3519
3520 // Check any additional module map files (e.g. module.private.modulemap)
3521 // that are not in the pcm.
3522 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3523 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3524 // Remove files that match
3525 // Note: SmallPtrSet::erase is really remove
3526 if (!AdditionalStoredMaps.erase(ModMap)) {
3527 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3528 Diag(diag::err_module_different_modmap)
3529 << F.ModuleName << /*new*/0 << ModMap->getName();
3530 return OutOfDate;
3531 }
3532 }
3533 }
3534
3535 // Check any additional module map files that are in the pcm, but not
3536 // found in header search. Cases that match are already removed.
3537 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3538 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3539 Diag(diag::err_module_different_modmap)
3540 << F.ModuleName << /*not new*/1 << ModMap->getName();
3541 return OutOfDate;
3542 }
3543 }
3544
3545 if (Listener)
3546 Listener->ReadModuleMapFile(F.ModuleMapPath);
3547 return Success;
3548}
3549
3550
Douglas Gregorc1489562013-02-12 23:36:21 +00003551/// \brief Move the given method to the back of the global list of methods.
3552static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3553 // Find the entry for this selector in the method pool.
3554 Sema::GlobalMethodPool::iterator Known
3555 = S.MethodPool.find(Method->getSelector());
3556 if (Known == S.MethodPool.end())
3557 return;
3558
3559 // Retrieve the appropriate method list.
3560 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3561 : Known->second.second;
3562 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003563 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003564 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003565 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003566 Found = true;
3567 } else {
3568 // Keep searching.
3569 continue;
3570 }
3571 }
3572
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003573 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003574 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003575 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003576 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003577 }
3578}
3579
Richard Smithde711422015-04-23 21:20:19 +00003580void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003581 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003582 for (Decl *D : Names) {
Richard Smith49f906a2014-03-01 00:08:04 +00003583 bool wasHidden = D->Hidden;
3584 D->Hidden = false;
Guy Benyei11169dd2012-12-18 14:30:41 +00003585
Richard Smith49f906a2014-03-01 00:08:04 +00003586 if (wasHidden && SemaObj) {
3587 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3588 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003589 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003590 }
3591 }
3592}
3593
Richard Smith49f906a2014-03-01 00:08:04 +00003594void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003595 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003596 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003597 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003598 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003599 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003600 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003601 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003602
3603 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003604 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 // there is nothing more to do.
3606 continue;
3607 }
Richard Smith49f906a2014-03-01 00:08:04 +00003608
Guy Benyei11169dd2012-12-18 14:30:41 +00003609 if (!Mod->isAvailable()) {
3610 // Modules that aren't available cannot be made visible.
3611 continue;
3612 }
3613
3614 // Update the module's name visibility.
3615 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003616
Guy Benyei11169dd2012-12-18 14:30:41 +00003617 // If we've already deserialized any names from this module,
3618 // mark them as visible.
3619 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3620 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003621 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003623 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003624 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3625 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003626 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003627
Guy Benyei11169dd2012-12-18 14:30:41 +00003628 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003629 SmallVector<Module *, 16> Exports;
3630 Mod->getExportedModules(Exports);
3631 for (SmallVectorImpl<Module *>::iterator
3632 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3633 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003634 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003635 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003636 }
3637 }
3638}
3639
Richard Smith6561f922016-09-12 21:06:40 +00003640/// We've merged the definition \p MergedDef into the existing definition
3641/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3642/// visible.
3643void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3644 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003645 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3646 // in modules other than its owning module. We should instead give the
3647 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003648 if (Def->isHidden()) {
3649 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003650 if (!MergedDef->isHidden())
3651 Def->Hidden = false;
3652 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3653 getContext().mergeDefinitionIntoModule(
3654 Def, MergedDef->getImportedOwningModule(),
3655 /*NotifyListeners*/ false);
3656 PendingMergedDefinitionsToDeduplicate.insert(Def);
3657 } else {
3658 auto SubmoduleID = MergedDef->getOwningModuleID();
3659 assert(SubmoduleID && "hidden definition in no module");
3660 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3661 }
Richard Smith6561f922016-09-12 21:06:40 +00003662 }
3663}
3664
Douglas Gregore060e572013-01-25 01:03:03 +00003665bool ASTReader::loadGlobalIndex() {
3666 if (GlobalIndex)
3667 return false;
3668
3669 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
3670 !Context.getLangOpts().Modules)
3671 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003672
Douglas Gregore060e572013-01-25 01:03:03 +00003673 // Try to load the global index.
3674 TriedLoadingGlobalIndex = true;
3675 StringRef ModuleCachePath
3676 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3677 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003678 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003679 if (!Result.first)
3680 return true;
3681
3682 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003683 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003684 return false;
3685}
3686
3687bool ASTReader::isGlobalIndexUnavailable() const {
3688 return Context.getLangOpts().Modules && UseGlobalIndex &&
3689 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3690}
3691
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003692static void updateModuleTimestamp(ModuleFile &MF) {
3693 // Overwrite the timestamp file contents so that file's mtime changes.
3694 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003695 std::error_code EC;
3696 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3697 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003698 return;
3699 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003700 OS.close();
3701 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003702}
3703
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003704/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3705/// cursor into the start of the given block ID, returning false on success and
3706/// true on failure.
3707static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003708 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003709 llvm::BitstreamEntry Entry = Cursor.advance();
3710 switch (Entry.Kind) {
3711 case llvm::BitstreamEntry::Error:
3712 case llvm::BitstreamEntry::EndBlock:
3713 return true;
3714
3715 case llvm::BitstreamEntry::Record:
3716 // Ignore top-level records.
3717 Cursor.skipRecord(Entry.ID);
3718 break;
3719
3720 case llvm::BitstreamEntry::SubBlock:
3721 if (Entry.ID == BlockID) {
3722 if (Cursor.EnterSubBlock(BlockID))
3723 return true;
3724 // Found it!
3725 return false;
3726 }
3727
3728 if (Cursor.SkipBlock())
3729 return true;
3730 }
3731 }
3732}
3733
Benjamin Kramer0772c422016-02-13 13:42:54 +00003734ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 ModuleKind Type,
3736 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003737 unsigned ClientLoadCapabilities,
3738 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003739 llvm::SaveAndRestore<SourceLocation>
3740 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3741
Richard Smithd1c46742014-04-30 02:24:17 +00003742 // Defer any pending actions until we get to the end of reading the AST file.
3743 Deserializing AnASTFile(this);
3744
Guy Benyei11169dd2012-12-18 14:30:41 +00003745 // Bump the generation number.
Richard Smith053f6c62014-05-16 23:01:30 +00003746 unsigned PreviousGeneration = incrementGeneration(Context);
Guy Benyei11169dd2012-12-18 14:30:41 +00003747
3748 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003749 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003750 switch (ASTReadResult ReadResult =
3751 ReadASTCore(FileName, Type, ImportLoc,
3752 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3753 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003754 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003755 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003756 case OutOfDate:
3757 case VersionMismatch:
3758 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003759 case HadErrors: {
3760 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3761 for (const ImportedModule &IM : Loaded)
3762 LoadedSet.insert(IM.Mod);
3763
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003764 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003765 Context.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003766 ? &PP.getHeaderSearchInfo().getModuleMap()
3767 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003768
3769 // If we find that any modules are unusable, the global index is going
3770 // to be out-of-date. Just remove it.
3771 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003772 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003775 case Success:
3776 break;
3777 }
3778
3779 // Here comes stuff that we only do once the entire chain is loaded.
3780
3781 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003782 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3783 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003784 M != MEnd; ++M) {
3785 ModuleFile &F = *M->Mod;
3786
3787 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003788 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3789 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003790
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003791 // Read the extension blocks.
3792 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3793 if (ASTReadResult Result = ReadExtensionBlock(F))
3794 return Result;
3795 }
3796
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003797 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 // bits of all files we've seen.
3799 F.GlobalBitOffset = TotalModulesSizeInBits;
3800 TotalModulesSizeInBits += F.SizeInBits;
3801 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003802
Guy Benyei11169dd2012-12-18 14:30:41 +00003803 // Preload SLocEntries.
3804 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3805 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3806 // Load it through the SourceManager and don't call ReadSLocEntry()
3807 // directly because the entry may have already been loaded in which case
3808 // calling ReadSLocEntry() directly would trigger an assertion in
3809 // SourceManager.
3810 SourceMgr.getLoadedSLocEntryByID(Index);
3811 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003812
Richard Smithea741482017-05-01 22:10:47 +00003813 // Map the original source file ID into the ID space of the current
3814 // compilation.
3815 if (F.OriginalSourceFileID.isValid()) {
3816 F.OriginalSourceFileID = FileID::get(
3817 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3818 }
3819
Richard Smith33e0f7e2015-07-22 02:08:40 +00003820 // Preload all the pending interesting identifiers by marking them out of
3821 // date.
3822 for (auto Offset : F.PreloadIdentifierOffsets) {
3823 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3824 F.IdentifierTableData + Offset);
3825
3826 ASTIdentifierLookupTrait Trait(*this, F);
3827 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3828 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003829 auto &II = PP.getIdentifierTable().getOwn(Key);
3830 II.setOutOfDate(true);
3831
3832 // Mark this identifier as being from an AST file so that we can track
3833 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003834 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003835
3836 // Associate the ID with the identifier so that the writer can reuse it.
3837 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3838 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003839 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003840 }
3841
Douglas Gregor603cd862013-03-22 18:50:14 +00003842 // Setup the import locations and notify the module manager that we've
3843 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003844 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3845 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003846 M != MEnd; ++M) {
3847 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003848
3849 ModuleMgr.moduleFileAccepted(&F);
3850
3851 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003852 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003853 // FIXME: We assume that locations from PCH / preamble do not need
3854 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 if (!M->ImportedBy)
3856 F.ImportLoc = M->ImportLoc;
3857 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003858 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003859 }
3860
Richard Smith33e0f7e2015-07-22 02:08:40 +00003861 if (!Context.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003862 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3863 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003864 // Mark all of the identifiers in the identifier table as being out of date,
3865 // so that various accessors know to check the loaded modules when the
3866 // identifier is used.
3867 //
3868 // For C++ modules, we don't need information on many identifiers (just
3869 // those that provide macros or are poisoned), so we mark all of
3870 // the interesting ones via PreloadIdentifierOffsets.
3871 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3872 IdEnd = PP.getIdentifierTable().end();
3873 Id != IdEnd; ++Id)
3874 Id->second->setOutOfDate(true);
3875 }
Manman Rena0f31a02016-04-29 19:04:05 +00003876 // Mark selectors as out of date.
3877 for (auto Sel : SelectorGeneration)
3878 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003881 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3882 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003883 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3884 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003885
3886 switch (Unresolved.Kind) {
3887 case UnresolvedModuleRef::Conflict:
3888 if (ResolvedMod) {
3889 Module::Conflict Conflict;
3890 Conflict.Other = ResolvedMod;
3891 Conflict.Message = Unresolved.String.str();
3892 Unresolved.Mod->Conflicts.push_back(Conflict);
3893 }
3894 continue;
3895
3896 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003897 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003898 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003900
Douglas Gregorfb912652013-03-20 21:10:35 +00003901 case UnresolvedModuleRef::Export:
3902 if (ResolvedMod || Unresolved.IsWildcard)
3903 Unresolved.Mod->Exports.push_back(
3904 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3905 continue;
3906 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003907 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003908 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003909
Graydon Hoaree7196af2016-12-09 21:45:49 +00003910 if (Imported)
3911 Imported->append(ImportedModules.begin(),
3912 ImportedModules.end());
3913
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003914 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3915 // Might be unnecessary as use declarations are only used to build the
3916 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003917
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 InitializeContext();
3919
Richard Smith3d8e97e2013-10-18 06:54:39 +00003920 if (SemaObj)
3921 UpdateSema();
3922
Guy Benyei11169dd2012-12-18 14:30:41 +00003923 if (DeserializationListener)
3924 DeserializationListener->ReaderInitialized(this);
3925
3926 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003927 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003928 // If this AST file is a precompiled preamble, then set the
3929 // preamble file ID of the source manager to the file source file
3930 // from which the preamble was built.
3931 if (Type == MK_Preamble) {
3932 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3933 } else if (Type == MK_MainFile) {
3934 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3935 }
3936 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003937
Guy Benyei11169dd2012-12-18 14:30:41 +00003938 // For any Objective-C class definitions we have already loaded, make sure
3939 // that we load any additional categories.
3940 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003941 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003942 ObjCClassesLoaded[I],
3943 PreviousGeneration);
3944 }
Douglas Gregore060e572013-01-25 01:03:03 +00003945
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003946 if (PP.getHeaderSearchInfo()
3947 .getHeaderSearchOpts()
3948 .ModulesValidateOncePerBuildSession) {
3949 // Now we are certain that the module and all modules it depends on are
3950 // up to date. Create or update timestamp files for modules that are
3951 // located in the module cache (not for PCH files that could be anywhere
3952 // in the filesystem).
3953 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
3954 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00003955 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003956 updateModuleTimestamp(*M.Mod);
3957 }
3958 }
3959 }
3960
Guy Benyei11169dd2012-12-18 14:30:41 +00003961 return Success;
3962}
3963
Peter Collingbourne77c89b62016-11-08 04:17:11 +00003964static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00003965
Ben Langmuir70a1b812015-03-24 04:43:52 +00003966/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
3967static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00003968 return Stream.canSkipToPos(4) &&
3969 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00003970 Stream.Read(8) == 'P' &&
3971 Stream.Read(8) == 'C' &&
3972 Stream.Read(8) == 'H';
3973}
3974
Richard Smith0f99d6a2015-08-09 08:48:41 +00003975static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
3976 switch (Kind) {
3977 case MK_PCH:
3978 return 0; // PCH
3979 case MK_ImplicitModule:
3980 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00003981 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00003982 return 1; // module
3983 case MK_MainFile:
3984 case MK_Preamble:
3985 return 2; // main source file
3986 }
3987 llvm_unreachable("unknown module kind");
3988}
3989
Guy Benyei11169dd2012-12-18 14:30:41 +00003990ASTReader::ASTReadResult
3991ASTReader::ReadASTCore(StringRef FileName,
3992 ModuleKind Type,
3993 SourceLocation ImportLoc,
3994 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003995 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00003996 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00003997 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 unsigned ClientLoadCapabilities) {
3999 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004001 ModuleManager::AddModuleResult AddResult
4002 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004003 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004004 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004005 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004006
Douglas Gregor7029ce12013-03-19 00:28:20 +00004007 switch (AddResult) {
4008 case ModuleManager::AlreadyLoaded:
4009 return Success;
4010
4011 case ModuleManager::NewlyLoaded:
4012 // Load module file below.
4013 break;
4014
4015 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004016 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004017 // it.
4018 if (ClientLoadCapabilities & ARR_Missing)
4019 return Missing;
4020
4021 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004022 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004023 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004024 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004025 return Failure;
4026
4027 case ModuleManager::OutOfDate:
4028 // We couldn't load the module file because it is out-of-date. If the
4029 // client can handle out-of-date, return it.
4030 if (ClientLoadCapabilities & ARR_OutOfDate)
4031 return OutOfDate;
4032
4033 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004034 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004035 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004036 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004037 return Failure;
4038 }
4039
Douglas Gregor7029ce12013-03-19 00:28:20 +00004040 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004041
4042 // FIXME: This seems rather a hack. Should CurrentDir be part of the
4043 // module?
4044 if (FileName != "-") {
4045 CurrentDir = llvm::sys::path::parent_path(FileName);
4046 if (CurrentDir.empty()) CurrentDir = ".";
4047 }
4048
4049 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004050 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004051 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004052 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004053
Guy Benyei11169dd2012-12-18 14:30:41 +00004054 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004055 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004056 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4057 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 return Failure;
4059 }
4060
4061 // This is used for compatibility with older PCH formats.
4062 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004063 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004064 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004065
Chris Lattnerefa77172013-01-20 00:00:22 +00004066 switch (Entry.Kind) {
4067 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004068 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004069 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004070 Error("invalid record at top-level of AST file");
4071 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004072
Chris Lattnerefa77172013-01-20 00:00:22 +00004073 case llvm::BitstreamEntry::SubBlock:
4074 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004075 }
4076
Chris Lattnerefa77172013-01-20 00:00:22 +00004077 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004078 case CONTROL_BLOCK_ID:
4079 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004080 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004081 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004082 // Check that we didn't try to load a non-module AST file as a module.
4083 //
4084 // FIXME: Should we also perform the converse check? Loading a module as
4085 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004086 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4087 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004088 F.ModuleName.empty()) {
4089 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4090 if (Result != OutOfDate ||
4091 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4092 Diag(diag::err_module_file_not_module) << FileName;
4093 return Result;
4094 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004095 break;
4096
4097 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004098 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004099 case OutOfDate: return OutOfDate;
4100 case VersionMismatch: return VersionMismatch;
4101 case ConfigurationMismatch: return ConfigurationMismatch;
4102 case HadErrors: return HadErrors;
4103 }
4104 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004105
Guy Benyei11169dd2012-12-18 14:30:41 +00004106 case AST_BLOCK_ID:
4107 if (!HaveReadControlBlock) {
4108 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004109 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 return VersionMismatch;
4111 }
4112
4113 // Record that we've loaded this module.
4114 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4115 return Success;
4116
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004117 case UNHASHED_CONTROL_BLOCK_ID:
4118 // This block is handled using look-ahead during ReadControlBlock. We
4119 // shouldn't get here!
4120 Error("malformed block record in AST file");
4121 return Failure;
4122
Guy Benyei11169dd2012-12-18 14:30:41 +00004123 default:
4124 if (Stream.SkipBlock()) {
4125 Error("malformed block record in AST file");
4126 return Failure;
4127 }
4128 break;
4129 }
4130 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004131
4132 return Success;
4133}
4134
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004135ASTReader::ASTReadResult
4136ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4137 unsigned ClientLoadCapabilities) {
4138 const HeaderSearchOptions &HSOpts =
4139 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4140 bool AllowCompatibleConfigurationMismatch =
4141 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4142
4143 ASTReadResult Result = readUnhashedControlBlockImpl(
4144 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4145 Listener.get(),
4146 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4147
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004148 // If F was directly imported by another module, it's implicitly validated by
4149 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004150 if (DisableValidation || WasImportedBy ||
4151 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4152 return Success;
4153
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004154 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004155 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004156 return Failure;
4157 }
4158
4159 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4160 // If this module has already been finalized in the PCMCache, we're stuck
4161 // with it; we can only load a single version of each module.
4162 //
4163 // This can happen when a module is imported in two contexts: in one, as a
4164 // user module; in another, as a system module (due to an import from
4165 // another module marked with the [system] flag). It usually indicates a
4166 // bug in the module map: this module should also be marked with [system].
4167 //
4168 // If -Wno-system-headers (the default), and the first import is as a
4169 // system module, then validation will fail during the as-user import,
4170 // since -Werror flags won't have been validated. However, it's reasonable
4171 // to treat this consistently as a system module.
4172 //
4173 // If -Wsystem-headers, the PCM on disk was built with
4174 // -Wno-system-headers, and the first import is as a user module, then
4175 // validation will fail during the as-system import since the PCM on disk
4176 // doesn't guarantee that -Werror was respected. However, the -Werror
4177 // flags were checked during the initial as-user import.
4178 if (PCMCache.isBufferFinal(F.FileName)) {
4179 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4180 return Success;
4181 }
4182 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004183
4184 return Result;
4185}
4186
4187ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4188 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4189 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4190 bool ValidateDiagnosticOptions) {
4191 // Initialize a stream.
4192 BitstreamCursor Stream(StreamData);
4193
4194 // Sniff for the signature.
4195 if (!startsWithASTFileMagic(Stream))
4196 return Failure;
4197
4198 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4199 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4200 return Failure;
4201
4202 // Read all of the records in the options block.
4203 RecordData Record;
4204 ASTReadResult Result = Success;
4205 while (1) {
4206 llvm::BitstreamEntry Entry = Stream.advance();
4207
4208 switch (Entry.Kind) {
4209 case llvm::BitstreamEntry::Error:
4210 case llvm::BitstreamEntry::SubBlock:
4211 return Failure;
4212
4213 case llvm::BitstreamEntry::EndBlock:
4214 return Result;
4215
4216 case llvm::BitstreamEntry::Record:
4217 // The interesting case.
4218 break;
4219 }
4220
4221 // Read and process a record.
4222 Record.clear();
4223 switch (
4224 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4225 case SIGNATURE: {
4226 if (F)
4227 std::copy(Record.begin(), Record.end(), F->Signature.data());
4228 break;
4229 }
4230 case DIAGNOSTIC_OPTIONS: {
4231 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4232 if (Listener && ValidateDiagnosticOptions &&
4233 !AllowCompatibleConfigurationMismatch &&
4234 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004235 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004236 break;
4237 }
4238 case DIAG_PRAGMA_MAPPINGS:
4239 if (!F)
4240 break;
4241 if (F->PragmaDiagMappings.empty())
4242 F->PragmaDiagMappings.swap(Record);
4243 else
4244 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4245 Record.begin(), Record.end());
4246 break;
4247 }
4248 }
4249}
4250
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004251/// Parse a record and blob containing module file extension metadata.
4252static bool parseModuleFileExtensionMetadata(
4253 const SmallVectorImpl<uint64_t> &Record,
4254 StringRef Blob,
4255 ModuleFileExtensionMetadata &Metadata) {
4256 if (Record.size() < 4) return true;
4257
4258 Metadata.MajorVersion = Record[0];
4259 Metadata.MinorVersion = Record[1];
4260
4261 unsigned BlockNameLen = Record[2];
4262 unsigned UserInfoLen = Record[3];
4263
4264 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4265
4266 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4267 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4268 Blob.data() + BlockNameLen + UserInfoLen);
4269 return false;
4270}
4271
4272ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4273 BitstreamCursor &Stream = F.Stream;
4274
4275 RecordData Record;
4276 while (true) {
4277 llvm::BitstreamEntry Entry = Stream.advance();
4278 switch (Entry.Kind) {
4279 case llvm::BitstreamEntry::SubBlock:
4280 if (Stream.SkipBlock())
4281 return Failure;
4282
4283 continue;
4284
4285 case llvm::BitstreamEntry::EndBlock:
4286 return Success;
4287
4288 case llvm::BitstreamEntry::Error:
4289 return HadErrors;
4290
4291 case llvm::BitstreamEntry::Record:
4292 break;
4293 }
4294
4295 Record.clear();
4296 StringRef Blob;
4297 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4298 switch (RecCode) {
4299 case EXTENSION_METADATA: {
4300 ModuleFileExtensionMetadata Metadata;
4301 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4302 return Failure;
4303
4304 // Find a module file extension with this block name.
4305 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4306 if (Known == ModuleFileExtensions.end()) break;
4307
4308 // Form a reader.
4309 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4310 F, Stream)) {
4311 F.ExtensionReaders.push_back(std::move(Reader));
4312 }
4313
4314 break;
4315 }
4316 }
4317 }
4318
4319 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004320}
4321
Richard Smitha7e2cc62015-05-01 01:53:09 +00004322void ASTReader::InitializeContext() {
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 // If there's a listener, notify them that we "read" the translation unit.
4324 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004325 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004326 Context.getTranslationUnitDecl());
4327
Guy Benyei11169dd2012-12-18 14:30:41 +00004328 // FIXME: Find a better way to deal with collisions between these
4329 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004330
Guy Benyei11169dd2012-12-18 14:30:41 +00004331 // Load the special types.
4332 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4333 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4334 if (!Context.CFConstantStringTypeDecl)
4335 Context.setCFConstantStringType(GetType(String));
4336 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004337
Guy Benyei11169dd2012-12-18 14:30:41 +00004338 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4339 QualType FileType = GetType(File);
4340 if (FileType.isNull()) {
4341 Error("FILE type is NULL");
4342 return;
4343 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004344
Guy Benyei11169dd2012-12-18 14:30:41 +00004345 if (!Context.FILEDecl) {
4346 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4347 Context.setFILEDecl(Typedef->getDecl());
4348 else {
4349 const TagType *Tag = FileType->getAs<TagType>();
4350 if (!Tag) {
4351 Error("Invalid FILE type in AST file");
4352 return;
4353 }
4354 Context.setFILEDecl(Tag->getDecl());
4355 }
4356 }
4357 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004358
Guy Benyei11169dd2012-12-18 14:30:41 +00004359 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4360 QualType Jmp_bufType = GetType(Jmp_buf);
4361 if (Jmp_bufType.isNull()) {
4362 Error("jmp_buf type is NULL");
4363 return;
4364 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 if (!Context.jmp_bufDecl) {
4367 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4368 Context.setjmp_bufDecl(Typedef->getDecl());
4369 else {
4370 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4371 if (!Tag) {
4372 Error("Invalid jmp_buf type in AST file");
4373 return;
4374 }
4375 Context.setjmp_bufDecl(Tag->getDecl());
4376 }
4377 }
4378 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004379
Guy Benyei11169dd2012-12-18 14:30:41 +00004380 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4381 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4382 if (Sigjmp_bufType.isNull()) {
4383 Error("sigjmp_buf type is NULL");
4384 return;
4385 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004386
Guy Benyei11169dd2012-12-18 14:30:41 +00004387 if (!Context.sigjmp_bufDecl) {
4388 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4389 Context.setsigjmp_bufDecl(Typedef->getDecl());
4390 else {
4391 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4392 assert(Tag && "Invalid sigjmp_buf type in AST file");
4393 Context.setsigjmp_bufDecl(Tag->getDecl());
4394 }
4395 }
4396 }
4397
4398 if (unsigned ObjCIdRedef
4399 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4400 if (Context.ObjCIdRedefinitionType.isNull())
4401 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4402 }
4403
4404 if (unsigned ObjCClassRedef
4405 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4406 if (Context.ObjCClassRedefinitionType.isNull())
4407 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4408 }
4409
4410 if (unsigned ObjCSelRedef
4411 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4412 if (Context.ObjCSelRedefinitionType.isNull())
4413 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4414 }
4415
4416 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4417 QualType Ucontext_tType = GetType(Ucontext_t);
4418 if (Ucontext_tType.isNull()) {
4419 Error("ucontext_t type is NULL");
4420 return;
4421 }
4422
4423 if (!Context.ucontext_tDecl) {
4424 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4425 Context.setucontext_tDecl(Typedef->getDecl());
4426 else {
4427 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4428 assert(Tag && "Invalid ucontext_t type in AST file");
4429 Context.setucontext_tDecl(Tag->getDecl());
4430 }
4431 }
4432 }
4433 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004434
Guy Benyei11169dd2012-12-18 14:30:41 +00004435 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4436
4437 // If there were any CUDA special declarations, deserialize them.
4438 if (!CUDASpecialDeclRefs.empty()) {
4439 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4440 Context.setcudaConfigureCallDecl(
4441 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4442 }
Richard Smith56be7542014-03-21 00:33:59 +00004443
Guy Benyei11169dd2012-12-18 14:30:41 +00004444 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004445 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004446 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004447 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004448 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004449 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004450 if (Import.ImportLoc.isValid())
4451 PP.makeModuleVisible(Imported, Import.ImportLoc);
4452 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004453 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004454 }
4455 ImportedModules.clear();
4456}
4457
4458void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004459 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004460}
4461
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004462/// \brief Reads and return the signature record from \p PCH's control block, or
4463/// else returns 0.
4464static ASTFileSignature readASTFileSignature(StringRef PCH) {
4465 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004466 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004467 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004468
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004469 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4470 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4471 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004472
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004473 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004474 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004475 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004476 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004477 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004478 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004479
4480 Record.clear();
4481 StringRef Blob;
4482 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004483 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4484 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004485 }
4486}
4487
Guy Benyei11169dd2012-12-18 14:30:41 +00004488/// \brief Retrieve the name of the original source file name
4489/// directly from the AST file, without actually loading the AST
4490/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004491std::string ASTReader::getOriginalSourceFile(
4492 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004493 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004494 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004495 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004497 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4498 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004499 return std::string();
4500 }
4501
4502 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004503 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004504
4505 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004506 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004507 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4508 return std::string();
4509 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004510
Chris Lattnere7b154b2013-01-19 21:39:22 +00004511 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004512 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004513 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4514 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004515 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004516
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004517 // Scan for ORIGINAL_FILE inside the control block.
4518 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004519 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004520 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004521 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4522 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004523
Chris Lattnere7b154b2013-01-19 21:39:22 +00004524 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4525 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4526 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004527 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004528
Guy Benyei11169dd2012-12-18 14:30:41 +00004529 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004530 StringRef Blob;
4531 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4532 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004534}
4535
4536namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004537
Guy Benyei11169dd2012-12-18 14:30:41 +00004538 class SimplePCHValidator : public ASTReaderListener {
4539 const LangOptions &ExistingLangOpts;
4540 const TargetOptions &ExistingTargetOpts;
4541 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004542 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004543 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004544
Guy Benyei11169dd2012-12-18 14:30:41 +00004545 public:
4546 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4547 const TargetOptions &ExistingTargetOpts,
4548 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004549 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 FileManager &FileMgr)
4551 : ExistingLangOpts(ExistingLangOpts),
4552 ExistingTargetOpts(ExistingTargetOpts),
4553 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004554 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004555 FileMgr(FileMgr)
4556 {
4557 }
4558
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004559 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4560 bool AllowCompatibleDifferences) override {
4561 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4562 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004563 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004564
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004565 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4566 bool AllowCompatibleDifferences) override {
4567 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4568 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004569 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004570
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004571 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4572 StringRef SpecificModuleCachePath,
4573 bool Complain) override {
4574 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4575 ExistingModuleCachePath,
4576 nullptr, ExistingLangOpts);
4577 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004578
Craig Topper3e89dfe2014-03-13 02:13:41 +00004579 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4580 bool Complain,
4581 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004582 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004583 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004584 }
4585 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004586
4587} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004588
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004589bool ASTReader::readASTFileControlBlock(
4590 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004591 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004592 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004593 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004594 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004595 // FIXME: This allows use of the VFS; we do not allow use of the
4596 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004597 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 if (!Buffer) {
4599 return true;
4600 }
4601
4602 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004603 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4604 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004605
4606 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004607 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004608 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004609
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004610 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004611 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004612 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004613
4614 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004615 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004616 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004617 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004618
Guy Benyei11169dd2012-12-18 14:30:41 +00004619 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004620 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004621 bool DoneWithControlBlock = false;
4622 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004623 llvm::BitstreamEntry Entry = Stream.advance();
4624
4625 switch (Entry.Kind) {
4626 case llvm::BitstreamEntry::SubBlock: {
4627 switch (Entry.ID) {
4628 case OPTIONS_BLOCK_ID: {
4629 std::string IgnoredSuggestedPredefines;
4630 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4631 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004632 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004633 return true;
4634 break;
4635 }
4636
4637 case INPUT_FILES_BLOCK_ID:
4638 InputFilesCursor = Stream;
4639 if (Stream.SkipBlock() ||
4640 (NeedsInputFiles &&
4641 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4642 return true;
4643 break;
4644
4645 default:
4646 if (Stream.SkipBlock())
4647 return true;
4648 break;
4649 }
4650
4651 continue;
4652 }
4653
4654 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004655 DoneWithControlBlock = true;
4656 break;
Richard Smith0516b182015-09-08 19:40:14 +00004657
4658 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004659 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004660
4661 case llvm::BitstreamEntry::Record:
4662 break;
4663 }
4664
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004665 if (DoneWithControlBlock) break;
4666
Guy Benyei11169dd2012-12-18 14:30:41 +00004667 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004668 StringRef Blob;
4669 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004670 switch ((ControlRecordTypes)RecCode) {
4671 case METADATA: {
4672 if (Record[0] != VERSION_MAJOR)
4673 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004674
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004675 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004676 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004677
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004678 break;
4679 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004680 case MODULE_NAME:
4681 Listener.ReadModuleName(Blob);
4682 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004683 case MODULE_DIRECTORY:
4684 ModuleDir = Blob;
4685 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004686 case MODULE_MAP_FILE: {
4687 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004688 auto Path = ReadString(Record, Idx);
4689 ResolveImportedPath(Path, ModuleDir);
4690 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004691 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004692 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004693 case INPUT_FILE_OFFSETS: {
4694 if (!NeedsInputFiles)
4695 break;
4696
4697 unsigned NumInputFiles = Record[0];
4698 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004699 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004700 for (unsigned I = 0; I != NumInputFiles; ++I) {
4701 // Go find this input file.
4702 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004703
4704 if (isSystemFile && !NeedsSystemInputFiles)
4705 break; // the rest are system input files
4706
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004707 BitstreamCursor &Cursor = InputFilesCursor;
4708 SavedStreamPosition SavedPosition(Cursor);
4709 Cursor.JumpToBit(InputFileOffs[I]);
4710
4711 unsigned Code = Cursor.ReadCode();
4712 RecordData Record;
4713 StringRef Blob;
4714 bool shouldContinue = false;
4715 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4716 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004717 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004718 std::string Filename = Blob;
4719 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004720 shouldContinue = Listener.visitInputFile(
4721 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004722 break;
4723 }
4724 if (!shouldContinue)
4725 break;
4726 }
4727 break;
4728 }
4729
Richard Smithd4b230b2014-10-27 23:01:16 +00004730 case IMPORTS: {
4731 if (!NeedsImports)
4732 break;
4733
4734 unsigned Idx = 0, N = Record.size();
4735 while (Idx < N) {
4736 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004737 Idx += 5; // ImportLoc, Size, ModTime, Signature
Richard Smith7ed1bc92014-12-05 22:42:13 +00004738 std::string Filename = ReadString(Record, Idx);
4739 ResolveImportedPath(Filename, ModuleDir);
4740 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004741 }
4742 break;
4743 }
4744
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004745 default:
4746 // No other validation to perform.
4747 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004748 }
4749 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004750
4751 // Look for module file extension blocks, if requested.
4752 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004753 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004754 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4755 bool DoneWithExtensionBlock = false;
4756 while (!DoneWithExtensionBlock) {
4757 llvm::BitstreamEntry Entry = Stream.advance();
4758
4759 switch (Entry.Kind) {
4760 case llvm::BitstreamEntry::SubBlock:
4761 if (Stream.SkipBlock())
4762 return true;
4763
4764 continue;
4765
4766 case llvm::BitstreamEntry::EndBlock:
4767 DoneWithExtensionBlock = true;
4768 continue;
4769
4770 case llvm::BitstreamEntry::Error:
4771 return true;
4772
4773 case llvm::BitstreamEntry::Record:
4774 break;
4775 }
4776
4777 Record.clear();
4778 StringRef Blob;
4779 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4780 switch (RecCode) {
4781 case EXTENSION_METADATA: {
4782 ModuleFileExtensionMetadata Metadata;
4783 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4784 return true;
4785
4786 Listener.readModuleFileExtension(Metadata);
4787 break;
4788 }
4789 }
4790 }
4791 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004792 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004793 }
4794
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004795 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4796 if (readUnhashedControlBlockImpl(
4797 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4798 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4799 ValidateDiagnosticOptions) != Success)
4800 return true;
4801
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004802 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004803}
4804
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004805bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4806 const PCHContainerReader &PCHContainerRdr,
4807 const LangOptions &LangOpts,
4808 const TargetOptions &TargetOpts,
4809 const PreprocessorOptions &PPOpts,
4810 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004811 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4812 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004813 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004814 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004815 validator,
4816 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004817}
4818
Ben Langmuir2c9af442014-04-10 17:57:43 +00004819ASTReader::ASTReadResult
4820ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 // Enter the submodule block.
4822 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4823 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004824 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004825 }
4826
4827 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4828 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004829 Module *CurrentModule = nullptr;
Richard Smith145e15a2017-04-24 23:12:30 +00004830 Module::ModuleKind ModuleKind = Module::ModuleMapModule;
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 RecordData Record;
4832 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004833 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004834
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004835 switch (Entry.Kind) {
4836 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4837 case llvm::BitstreamEntry::Error:
4838 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004839 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004840 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004841 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004842 case llvm::BitstreamEntry::Record:
4843 // The interesting case.
4844 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004845 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004846
Guy Benyei11169dd2012-12-18 14:30:41 +00004847 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004848 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004849 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004850 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4851
4852 if ((Kind == SUBMODULE_METADATA) != First) {
4853 Error("submodule metadata record should be at beginning of block");
4854 return Failure;
4855 }
4856 First = false;
4857
4858 // Submodule information is only valid if we have a current module.
4859 // FIXME: Should we error on these cases?
4860 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4861 Kind != SUBMODULE_DEFINITION)
4862 continue;
4863
4864 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 default: // Default behavior: ignore.
4866 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004867
Richard Smith03478d92014-10-23 22:12:14 +00004868 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004869 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004870 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004871 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004872 }
Richard Smith03478d92014-10-23 22:12:14 +00004873
Chris Lattner0e6c9402013-01-20 02:38:54 +00004874 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004875 unsigned Idx = 0;
4876 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4877 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
4878 bool IsFramework = Record[Idx++];
4879 bool IsExplicit = Record[Idx++];
4880 bool IsSystem = Record[Idx++];
4881 bool IsExternC = Record[Idx++];
4882 bool InferSubmodules = Record[Idx++];
4883 bool InferExplicitSubmodules = Record[Idx++];
4884 bool InferExportWildcard = Record[Idx++];
4885 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004886
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004887 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004888 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004890
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 // Retrieve this (sub)module from the module map, creating it if
4892 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004893 CurrentModule =
4894 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4895 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004896
4897 // FIXME: set the definition loc for CurrentModule, or call
4898 // ModMap.setInferredModuleAllowedBy()
4899
Guy Benyei11169dd2012-12-18 14:30:41 +00004900 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4901 if (GlobalIndex >= SubmodulesLoaded.size() ||
4902 SubmodulesLoaded[GlobalIndex]) {
4903 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004904 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004905 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004906
Douglas Gregor7029ce12013-03-19 00:28:20 +00004907 if (!ParentModule) {
4908 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4909 if (CurFile != F.File) {
4910 if (!Diags.isDiagnosticInFlight()) {
4911 Diag(diag::err_module_file_conflict)
4912 << CurrentModule->getTopLevelModuleName()
4913 << CurFile->getName()
4914 << F.File->getName();
4915 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004916 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004917 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004918 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004919
4920 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00004921 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004922 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004923
Richard Smith145e15a2017-04-24 23:12:30 +00004924 CurrentModule->Kind = ModuleKind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00004925 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004926 CurrentModule->IsFromModuleFile = true;
4927 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004928 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004929 CurrentModule->InferSubmodules = InferSubmodules;
4930 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4931 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004932 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 if (DeserializationListener)
4934 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004935
Guy Benyei11169dd2012-12-18 14:30:41 +00004936 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004937
Richard Smith8a3e39a2016-03-28 21:31:09 +00004938 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004939 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004940 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004941 CurrentModule->UnresolvedConflicts.clear();
4942 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004943
4944 // The module is available unless it's missing a requirement; relevant
4945 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4946 // Missing headers that were present when the module was built do not
4947 // make it unavailable -- if we got this far, this must be an explicitly
4948 // imported module file.
4949 CurrentModule->Requirements.clear();
4950 CurrentModule->MissingHeaders.clear();
4951 CurrentModule->IsMissingRequirement =
4952 ParentModule && ParentModule->IsMissingRequirement;
4953 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004954 break;
4955 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00004956
Guy Benyei11169dd2012-12-18 14:30:41 +00004957 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00004958 std::string Filename = Blob;
4959 ResolveImportedPath(F, Filename);
4960 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004961 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00004962 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
4963 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00004964 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4965 Error("mismatched umbrella headers in submodule");
4966 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00004967 }
4968 }
4969 break;
4970 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004971
Richard Smith202210b2014-10-24 20:23:01 +00004972 case SUBMODULE_HEADER:
4973 case SUBMODULE_EXCLUDED_HEADER:
4974 case SUBMODULE_PRIVATE_HEADER:
4975 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00004976 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
4977 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00004978 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004979
Richard Smith202210b2014-10-24 20:23:01 +00004980 case SUBMODULE_TEXTUAL_HEADER:
4981 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
4982 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
4983 // them here.
4984 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00004985
Guy Benyei11169dd2012-12-18 14:30:41 +00004986 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00004987 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00004988 break;
4989 }
4990
4991 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00004992 std::string Dirname = Blob;
4993 ResolveImportedPath(F, Dirname);
4994 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004995 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00004996 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
4997 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00004998 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
4999 Error("mismatched umbrella directories in submodule");
5000 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 }
5002 }
5003 break;
5004 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005005
Guy Benyei11169dd2012-12-18 14:30:41 +00005006 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005007 F.BaseSubmoduleID = getTotalNumSubmodules();
5008 F.LocalNumSubmodules = Record[0];
5009 unsigned LocalBaseSubmoduleID = Record[1];
5010 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005011 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005012 // module.
5013 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005014
5015 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005016 // module.
5017 F.SubmoduleRemap.insertOrReplace(
5018 std::make_pair(LocalBaseSubmoduleID,
5019 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005020
Ben Langmuir52ca6782014-10-20 16:27:32 +00005021 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5022 }
Richard Smith145e15a2017-04-24 23:12:30 +00005023 ModuleKind = (Module::ModuleKind)Record[2];
Guy Benyei11169dd2012-12-18 14:30:41 +00005024 break;
5025 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005026
Guy Benyei11169dd2012-12-18 14:30:41 +00005027 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005028 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005029 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 Unresolved.File = &F;
5031 Unresolved.Mod = CurrentModule;
5032 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005033 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005034 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005035 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005036 }
5037 break;
5038 }
5039
5040 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005041 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005042 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005043 Unresolved.File = &F;
5044 Unresolved.Mod = CurrentModule;
5045 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005046 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005047 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005048 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005049 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005050
5051 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005052 // the parsed, unresolved exports around.
5053 CurrentModule->UnresolvedExports.clear();
5054 break;
5055 }
5056 case SUBMODULE_REQUIRES: {
Richard Smitha3feee22013-10-28 22:18:19 +00005057 CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
Guy Benyei11169dd2012-12-18 14:30:41 +00005058 Context.getTargetInfo());
5059 break;
5060 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005061
5062 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005063 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005064 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005065 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005066
5067 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005068 CurrentModule->ConfigMacros.push_back(Blob.str());
5069 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005070
5071 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005072 UnresolvedModuleRef Unresolved;
5073 Unresolved.File = &F;
5074 Unresolved.Mod = CurrentModule;
5075 Unresolved.ID = Record[0];
5076 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5077 Unresolved.IsWildcard = false;
5078 Unresolved.String = Blob;
5079 UnresolvedModuleRefs.push_back(Unresolved);
5080 break;
5081 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005082
5083 case SUBMODULE_INITIALIZERS:
5084 SmallVector<uint32_t, 16> Inits;
5085 for (auto &ID : Record)
5086 Inits.push_back(getGlobalDeclID(F, ID));
5087 Context.addLazyModuleInitializers(CurrentModule, Inits);
5088 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005089 }
5090 }
5091}
5092
5093/// \brief Parse the record that corresponds to a LangOptions data
5094/// structure.
5095///
5096/// This routine parses the language options from the AST file and then gives
5097/// them to the AST listener if one is set.
5098///
5099/// \returns true if the listener deems the file unacceptable, false otherwise.
5100bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5101 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005102 ASTReaderListener &Listener,
5103 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005104 LangOptions LangOpts;
5105 unsigned Idx = 0;
5106#define LANGOPT(Name, Bits, Default, Description) \
5107 LangOpts.Name = Record[Idx++];
5108#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5109 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5110#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005111#define SANITIZER(NAME, ID) \
5112 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005113#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005114
Ben Langmuircd98cb72015-06-23 18:20:18 +00005115 for (unsigned N = Record[Idx++]; N; --N)
5116 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5117
Guy Benyei11169dd2012-12-18 14:30:41 +00005118 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5119 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5120 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005121
Ben Langmuird4a667a2015-06-23 18:20:23 +00005122 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005123
5124 // Comment options.
5125 for (unsigned N = Record[Idx++]; N; --N) {
5126 LangOpts.CommentOpts.BlockCommandNames.push_back(
5127 ReadString(Record, Idx));
5128 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005129 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005130
Samuel Antaoee8fb302016-01-06 13:42:12 +00005131 // OpenMP offloading options.
5132 for (unsigned N = Record[Idx++]; N; --N) {
5133 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5134 }
5135
5136 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5137
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005138 return Listener.ReadLanguageOptions(LangOpts, Complain,
5139 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005140}
5141
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005142bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5143 ASTReaderListener &Listener,
5144 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005145 unsigned Idx = 0;
5146 TargetOptions TargetOpts;
5147 TargetOpts.Triple = ReadString(Record, Idx);
5148 TargetOpts.CPU = ReadString(Record, Idx);
5149 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005150 for (unsigned N = Record[Idx++]; N; --N) {
5151 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5152 }
5153 for (unsigned N = Record[Idx++]; N; --N) {
5154 TargetOpts.Features.push_back(ReadString(Record, Idx));
5155 }
5156
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005157 return Listener.ReadTargetOptions(TargetOpts, Complain,
5158 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005159}
5160
5161bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5162 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005163 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005164 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005165#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005166#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005167 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005168#include "clang/Basic/DiagnosticOptions.def"
5169
Richard Smith3be1cb22014-08-07 00:24:21 +00005170 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005171 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005172 for (unsigned N = Record[Idx++]; N; --N)
5173 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005174
5175 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5176}
5177
5178bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5179 ASTReaderListener &Listener) {
5180 FileSystemOptions FSOpts;
5181 unsigned Idx = 0;
5182 FSOpts.WorkingDir = ReadString(Record, Idx);
5183 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5184}
5185
5186bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5187 bool Complain,
5188 ASTReaderListener &Listener) {
5189 HeaderSearchOptions HSOpts;
5190 unsigned Idx = 0;
5191 HSOpts.Sysroot = ReadString(Record, Idx);
5192
5193 // Include entries.
5194 for (unsigned N = Record[Idx++]; N; --N) {
5195 std::string Path = ReadString(Record, Idx);
5196 frontend::IncludeDirGroup Group
5197 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005198 bool IsFramework = Record[Idx++];
5199 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005200 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5201 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005202 }
5203
5204 // System header prefixes.
5205 for (unsigned N = Record[Idx++]; N; --N) {
5206 std::string Prefix = ReadString(Record, Idx);
5207 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005208 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005209 }
5210
5211 HSOpts.ResourceDir = ReadString(Record, Idx);
5212 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005213 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 HSOpts.DisableModuleHash = Record[Idx++];
5215 HSOpts.UseBuiltinIncludes = Record[Idx++];
5216 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5217 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5218 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005219 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005220
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005221 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5222 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005223}
5224
5225bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5226 bool Complain,
5227 ASTReaderListener &Listener,
5228 std::string &SuggestedPredefines) {
5229 PreprocessorOptions PPOpts;
5230 unsigned Idx = 0;
5231
5232 // Macro definitions/undefs
5233 for (unsigned N = Record[Idx++]; N; --N) {
5234 std::string Macro = ReadString(Record, Idx);
5235 bool IsUndef = Record[Idx++];
5236 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5237 }
5238
5239 // Includes
5240 for (unsigned N = Record[Idx++]; N; --N) {
5241 PPOpts.Includes.push_back(ReadString(Record, Idx));
5242 }
5243
5244 // Macro Includes
5245 for (unsigned N = Record[Idx++]; N; --N) {
5246 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5247 }
5248
5249 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005250 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005251 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5252 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5253 PPOpts.ObjCXXARCStandardLibrary =
5254 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5255 SuggestedPredefines.clear();
5256 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5257 SuggestedPredefines);
5258}
5259
5260std::pair<ModuleFile *, unsigned>
5261ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5262 GlobalPreprocessedEntityMapType::iterator
5263 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005264 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005265 "Corrupted global preprocessed entity map");
5266 ModuleFile *M = I->second;
5267 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5268 return std::make_pair(M, LocalIndex);
5269}
5270
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005271llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005272ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5273 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5274 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5275 Mod.NumPreprocessedEntities);
5276
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005277 return llvm::make_range(PreprocessingRecord::iterator(),
5278 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005279}
5280
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005281llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005282ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005283 return llvm::make_range(
5284 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5285 ModuleDeclIterator(this, &Mod,
5286 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005287}
5288
5289PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5290 PreprocessedEntityID PPID = Index+1;
5291 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5292 ModuleFile &M = *PPInfo.first;
5293 unsigned LocalIndex = PPInfo.second;
5294 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5295
Guy Benyei11169dd2012-12-18 14:30:41 +00005296 if (!PP.getPreprocessingRecord()) {
5297 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005298 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005299 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005300
5301 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005302 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5303
5304 llvm::BitstreamEntry Entry =
5305 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5306 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005307 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005308
Guy Benyei11169dd2012-12-18 14:30:41 +00005309 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005310 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5311 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005312 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005313 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005314 RecordData Record;
5315 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005316 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5317 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005318 switch (RecType) {
5319 case PPD_MACRO_EXPANSION: {
5320 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005321 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005322 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005323 if (isBuiltin)
5324 Name = getLocalIdentifier(M, Record[1]);
5325 else {
Richard Smith66a81862015-05-04 02:25:31 +00005326 PreprocessedEntityID GlobalID =
5327 getGlobalPreprocessedEntityID(M, Record[1]);
5328 Def = cast<MacroDefinitionRecord>(
5329 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005330 }
5331
5332 MacroExpansion *ME;
5333 if (isBuiltin)
5334 ME = new (PPRec) MacroExpansion(Name, Range);
5335 else
5336 ME = new (PPRec) MacroExpansion(Def, Range);
5337
5338 return ME;
5339 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005340
Guy Benyei11169dd2012-12-18 14:30:41 +00005341 case PPD_MACRO_DEFINITION: {
5342 // Decode the identifier info and then check again; if the macro is
5343 // still defined and associated with the identifier,
5344 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005345 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005346
5347 if (DeserializationListener)
5348 DeserializationListener->MacroDefinitionRead(PPID, MD);
5349
5350 return MD;
5351 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005352
Guy Benyei11169dd2012-12-18 14:30:41 +00005353 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005354 const char *FullFileNameStart = Blob.data() + Record[0];
5355 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005356 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005357 if (!FullFileName.empty())
5358 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005359
Guy Benyei11169dd2012-12-18 14:30:41 +00005360 // FIXME: Stable encoding
5361 InclusionDirective::InclusionKind Kind
5362 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5363 InclusionDirective *ID
5364 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005365 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 Record[1], Record[3],
5367 File,
5368 Range);
5369 return ID;
5370 }
5371 }
5372
5373 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5374}
5375
5376/// \brief \arg SLocMapI points at a chunk of a module that contains no
5377/// preprocessed entities or the entities it contains are not the ones we are
5378/// looking for. Find the next module that contains entities and return the ID
5379/// of the first entry.
5380PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5381 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5382 ++SLocMapI;
5383 for (GlobalSLocOffsetMapType::const_iterator
5384 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5385 ModuleFile &M = *SLocMapI->second;
5386 if (M.NumPreprocessedEntities)
5387 return M.BasePreprocessedEntityID;
5388 }
5389
5390 return getTotalNumPreprocessedEntities();
5391}
5392
5393namespace {
5394
Guy Benyei11169dd2012-12-18 14:30:41 +00005395struct PPEntityComp {
5396 const ASTReader &Reader;
5397 ModuleFile &M;
5398
5399 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5400
5401 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5402 SourceLocation LHS = getLoc(L);
5403 SourceLocation RHS = getLoc(R);
5404 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5405 }
5406
5407 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5408 SourceLocation LHS = getLoc(L);
5409 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5410 }
5411
5412 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5413 SourceLocation RHS = getLoc(R);
5414 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5415 }
5416
5417 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005418 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005419 }
5420};
5421
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005422} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005423
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005424PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5425 bool EndsAfter) const {
5426 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005427 return getTotalNumPreprocessedEntities();
5428
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005429 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5430 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005431 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5432 "Corrupted global sloc offset map");
5433
5434 if (SLocMapI->second->NumPreprocessedEntities == 0)
5435 return findNextPreprocessedEntity(SLocMapI);
5436
5437 ModuleFile &M = *SLocMapI->second;
5438 typedef const PPEntityOffset *pp_iterator;
5439 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5440 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5441
5442 size_t Count = M.NumPreprocessedEntities;
5443 size_t Half;
5444 pp_iterator First = pp_begin;
5445 pp_iterator PPI;
5446
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005447 if (EndsAfter) {
5448 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005449 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005450 } else {
5451 // Do a binary search manually instead of using std::lower_bound because
5452 // The end locations of entities may be unordered (when a macro expansion
5453 // is inside another macro argument), but for this case it is not important
5454 // whether we get the first macro expansion or its containing macro.
5455 while (Count > 0) {
5456 Half = Count / 2;
5457 PPI = First;
5458 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005459 if (SourceMgr.isBeforeInTranslationUnit(
5460 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005461 First = PPI;
5462 ++First;
5463 Count = Count - Half - 1;
5464 } else
5465 Count = Half;
5466 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005467 }
5468
5469 if (PPI == pp_end)
5470 return findNextPreprocessedEntity(SLocMapI);
5471
5472 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5473}
5474
Guy Benyei11169dd2012-12-18 14:30:41 +00005475/// \brief Returns a pair of [Begin, End) indices of preallocated
5476/// preprocessed entities that \arg Range encompasses.
5477std::pair<unsigned, unsigned>
5478 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5479 if (Range.isInvalid())
5480 return std::make_pair(0,0);
5481 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5482
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005483 PreprocessedEntityID BeginID =
5484 findPreprocessedEntity(Range.getBegin(), false);
5485 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005486 return std::make_pair(BeginID, EndID);
5487}
5488
5489/// \brief Optionally returns true or false if the preallocated preprocessed
5490/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005491Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005492 FileID FID) {
5493 if (FID.isInvalid())
5494 return false;
5495
5496 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5497 ModuleFile &M = *PPInfo.first;
5498 unsigned LocalIndex = PPInfo.second;
5499 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005500
Richard Smithcb34bd32016-03-27 07:28:06 +00005501 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005502 if (Loc.isInvalid())
5503 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005504
Guy Benyei11169dd2012-12-18 14:30:41 +00005505 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5506 return true;
5507 else
5508 return false;
5509}
5510
5511namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005512
Guy Benyei11169dd2012-12-18 14:30:41 +00005513 /// \brief Visitor used to search for information about a header file.
5514 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005515 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005516
David Blaikie05785d12013-02-20 22:23:23 +00005517 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005518
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005520 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5521 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005522
5523 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005524 HeaderFileInfoLookupTable *Table
5525 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5526 if (!Table)
5527 return false;
5528
5529 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005530 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005531 if (Pos == Table->end())
5532 return false;
5533
Richard Smithbdf2d932015-07-30 03:37:16 +00005534 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005535 return true;
5536 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005537
David Blaikie05785d12013-02-20 22:23:23 +00005538 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005539 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005540
5541} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005542
5543HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005544 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005545 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005546 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005547 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005548
Guy Benyei11169dd2012-12-18 14:30:41 +00005549 return HeaderFileInfo();
5550}
5551
5552void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005553 using DiagState = DiagnosticsEngine::DiagState;
5554 SmallVector<DiagState *, 32> DiagStates;
5555
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005556 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005557 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005558 auto &Record = F.PragmaDiagMappings;
5559 if (Record.empty())
5560 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005561
Richard Smithd230de22017-01-26 01:01:01 +00005562 DiagStates.clear();
5563
5564 auto ReadDiagState =
5565 [&](const DiagState &BasedOn, SourceLocation Loc,
5566 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5567 unsigned BackrefID = Record[Idx++];
5568 if (BackrefID != 0)
5569 return DiagStates[BackrefID - 1];
5570
Guy Benyei11169dd2012-12-18 14:30:41 +00005571 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005572 Diag.DiagStates.push_back(BasedOn);
5573 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005574 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005575 unsigned Size = Record[Idx++];
5576 assert(Idx + Size * 2 <= Record.size() &&
5577 "Invalid data, not enough diag/map pairs");
5578 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005579 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005580 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005581 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005582 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5583 continue;
5584
5585 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5586
5587 // If this mapping was specified as a warning but the severity was
5588 // upgraded due to diagnostic settings, simulate the current diagnostic
5589 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005590 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5591 NewMapping.setSeverity(diag::Severity::Warning);
5592 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005593 }
5594
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005595 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005596 }
Richard Smithd230de22017-01-26 01:01:01 +00005597 return NewState;
5598 };
5599
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005600 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005601 DiagState *FirstState;
5602 if (F.Kind == MK_ImplicitModule) {
5603 // Implicitly-built modules are reused with different diagnostic
5604 // settings. Use the initial diagnostic state from Diag to simulate this
5605 // compilation's diagnostic settings.
5606 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5607 DiagStates.push_back(FirstState);
5608
5609 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005610 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005611 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005612 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005613 assert(Idx < Record.size() &&
5614 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005615 } else if (F.isModule()) {
5616 // For an explicit module, preserve the flags from the module build
5617 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5618 // -Wblah flags.
5619 unsigned Flags = Record[Idx++];
5620 DiagState Initial;
5621 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5622 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5623 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5624 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5625 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5626 Initial.ExtBehavior = (diag::Severity)Flags;
5627 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005628
Richard Smithe37391c2017-05-03 00:28:49 +00005629 // Set up the root buffer of the module to start with the initial
5630 // diagnostic state of the module itself, to cover files that contain no
5631 // explicit transitions (for which we did not serialize anything).
5632 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5633 .StateTransitions.push_back({FirstState, 0});
5634 } else {
5635 // For prefix ASTs, start with whatever the user configured on the
5636 // command line.
5637 Idx++; // Skip flags.
5638 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5639 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005640 }
Richard Smithd230de22017-01-26 01:01:01 +00005641
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005642 // Read the state transitions.
5643 unsigned NumLocations = Record[Idx++];
5644 while (NumLocations--) {
5645 assert(Idx < Record.size() &&
5646 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005647 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5648 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5649 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5650 unsigned Transitions = Record[Idx++];
5651
5652 // Note that we don't need to set up Parent/ParentOffset here, because
5653 // we won't be changing the diagnostic state within imported FileIDs
5654 // (other than perhaps appending to the main source file, which has no
5655 // parent).
5656 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5657 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5658 for (unsigned I = 0; I != Transitions; ++I) {
5659 unsigned Offset = Record[Idx++];
5660 auto *State =
5661 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5662 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005663 }
5664 }
Richard Smithd230de22017-01-26 01:01:01 +00005665
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005666 // Read the final state.
5667 assert(Idx < Record.size() &&
5668 "Invalid data, missing final pragma diagnostic state");
5669 SourceLocation CurStateLoc =
5670 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5671 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5672
5673 if (!F.isModule()) {
5674 Diag.DiagStatesByLoc.CurDiagState = CurState;
5675 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5676
5677 // Preserve the property that the imaginary root file describes the
5678 // current state.
5679 auto &T = Diag.DiagStatesByLoc.Files[FileID()].StateTransitions;
5680 if (T.empty())
5681 T.push_back({CurState, 0});
5682 else
5683 T[0].State = CurState;
5684 }
5685
Richard Smithd230de22017-01-26 01:01:01 +00005686 // Don't try to read these mappings again.
5687 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005688 }
5689}
5690
5691/// \brief Get the correct cursor and offset for loading a type.
5692ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5693 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5694 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5695 ModuleFile *M = I->second;
5696 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5697}
5698
5699/// \brief Read and return the type with the given index..
5700///
5701/// The index is the type ID, shifted and minus the number of predefs. This
5702/// routine actually reads the record corresponding to the type at the given
5703/// location. It is a helper routine for GetType, which deals with reading type
5704/// IDs.
5705QualType ASTReader::readTypeRecord(unsigned Index) {
5706 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005707 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005708
5709 // Keep track of where we are in the stream, then jump back there
5710 // after reading this type.
5711 SavedStreamPosition SavedPosition(DeclsCursor);
5712
5713 ReadingKindTracker ReadingKind(Read_Type, *this);
5714
5715 // Note that we are loading a type record.
5716 Deserializing AType(this);
5717
5718 unsigned Idx = 0;
5719 DeclsCursor.JumpToBit(Loc.Offset);
5720 RecordData Record;
5721 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005722 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005723 case TYPE_EXT_QUAL: {
5724 if (Record.size() != 2) {
5725 Error("Incorrect encoding of extended qualifier type");
5726 return QualType();
5727 }
5728 QualType Base = readType(*Loc.F, Record, Idx);
5729 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5730 return Context.getQualifiedType(Base, Quals);
5731 }
5732
5733 case TYPE_COMPLEX: {
5734 if (Record.size() != 1) {
5735 Error("Incorrect encoding of complex type");
5736 return QualType();
5737 }
5738 QualType ElemType = readType(*Loc.F, Record, Idx);
5739 return Context.getComplexType(ElemType);
5740 }
5741
5742 case TYPE_POINTER: {
5743 if (Record.size() != 1) {
5744 Error("Incorrect encoding of pointer type");
5745 return QualType();
5746 }
5747 QualType PointeeType = readType(*Loc.F, Record, Idx);
5748 return Context.getPointerType(PointeeType);
5749 }
5750
Reid Kleckner8a365022013-06-24 17:51:48 +00005751 case TYPE_DECAYED: {
5752 if (Record.size() != 1) {
5753 Error("Incorrect encoding of decayed type");
5754 return QualType();
5755 }
5756 QualType OriginalType = readType(*Loc.F, Record, Idx);
5757 QualType DT = Context.getAdjustedParameterType(OriginalType);
5758 if (!isa<DecayedType>(DT))
5759 Error("Decayed type does not decay");
5760 return DT;
5761 }
5762
Reid Kleckner0503a872013-12-05 01:23:43 +00005763 case TYPE_ADJUSTED: {
5764 if (Record.size() != 2) {
5765 Error("Incorrect encoding of adjusted type");
5766 return QualType();
5767 }
5768 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5769 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5770 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5771 }
5772
Guy Benyei11169dd2012-12-18 14:30:41 +00005773 case TYPE_BLOCK_POINTER: {
5774 if (Record.size() != 1) {
5775 Error("Incorrect encoding of block pointer type");
5776 return QualType();
5777 }
5778 QualType PointeeType = readType(*Loc.F, Record, Idx);
5779 return Context.getBlockPointerType(PointeeType);
5780 }
5781
5782 case TYPE_LVALUE_REFERENCE: {
5783 if (Record.size() != 2) {
5784 Error("Incorrect encoding of lvalue reference type");
5785 return QualType();
5786 }
5787 QualType PointeeType = readType(*Loc.F, Record, Idx);
5788 return Context.getLValueReferenceType(PointeeType, Record[1]);
5789 }
5790
5791 case TYPE_RVALUE_REFERENCE: {
5792 if (Record.size() != 1) {
5793 Error("Incorrect encoding of rvalue reference type");
5794 return QualType();
5795 }
5796 QualType PointeeType = readType(*Loc.F, Record, Idx);
5797 return Context.getRValueReferenceType(PointeeType);
5798 }
5799
5800 case TYPE_MEMBER_POINTER: {
5801 if (Record.size() != 2) {
5802 Error("Incorrect encoding of member pointer type");
5803 return QualType();
5804 }
5805 QualType PointeeType = readType(*Loc.F, Record, Idx);
5806 QualType ClassType = readType(*Loc.F, Record, Idx);
5807 if (PointeeType.isNull() || ClassType.isNull())
5808 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005809
Guy Benyei11169dd2012-12-18 14:30:41 +00005810 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5811 }
5812
5813 case TYPE_CONSTANT_ARRAY: {
5814 QualType ElementType = readType(*Loc.F, Record, Idx);
5815 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5816 unsigned IndexTypeQuals = Record[2];
5817 unsigned Idx = 3;
5818 llvm::APInt Size = ReadAPInt(Record, Idx);
5819 return Context.getConstantArrayType(ElementType, Size,
5820 ASM, IndexTypeQuals);
5821 }
5822
5823 case TYPE_INCOMPLETE_ARRAY: {
5824 QualType ElementType = readType(*Loc.F, Record, Idx);
5825 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5826 unsigned IndexTypeQuals = Record[2];
5827 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5828 }
5829
5830 case TYPE_VARIABLE_ARRAY: {
5831 QualType ElementType = readType(*Loc.F, Record, Idx);
5832 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5833 unsigned IndexTypeQuals = Record[2];
5834 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5835 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5836 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5837 ASM, IndexTypeQuals,
5838 SourceRange(LBLoc, RBLoc));
5839 }
5840
5841 case TYPE_VECTOR: {
5842 if (Record.size() != 3) {
5843 Error("incorrect encoding of vector type in AST file");
5844 return QualType();
5845 }
5846
5847 QualType ElementType = readType(*Loc.F, Record, Idx);
5848 unsigned NumElements = Record[1];
5849 unsigned VecKind = Record[2];
5850 return Context.getVectorType(ElementType, NumElements,
5851 (VectorType::VectorKind)VecKind);
5852 }
5853
5854 case TYPE_EXT_VECTOR: {
5855 if (Record.size() != 3) {
5856 Error("incorrect encoding of extended vector type in AST file");
5857 return QualType();
5858 }
5859
5860 QualType ElementType = readType(*Loc.F, Record, Idx);
5861 unsigned NumElements = Record[1];
5862 return Context.getExtVectorType(ElementType, NumElements);
5863 }
5864
5865 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005866 if (Record.size() != 7) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005867 Error("incorrect encoding of no-proto function type");
5868 return QualType();
5869 }
5870 QualType ResultType = readType(*Loc.F, Record, Idx);
5871 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005872 (CallingConv)Record[4], Record[5], Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005873 return Context.getFunctionNoProtoType(ResultType, Info);
5874 }
5875
5876 case TYPE_FUNCTION_PROTO: {
5877 QualType ResultType = readType(*Loc.F, Record, Idx);
5878
5879 FunctionProtoType::ExtProtoInfo EPI;
5880 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5881 /*hasregparm*/ Record[2],
5882 /*regparm*/ Record[3],
5883 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005884 /*produces*/ Record[5],
5885 /*nocallersavedregs*/ Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005886
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005887 unsigned Idx = 7;
Guy Benyei11169dd2012-12-18 14:30:41 +00005888
5889 EPI.Variadic = Record[Idx++];
5890 EPI.HasTrailingReturn = Record[Idx++];
5891 EPI.TypeQuals = Record[Idx++];
5892 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005893 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005894 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005895
5896 unsigned NumParams = Record[Idx++];
5897 SmallVector<QualType, 16> ParamTypes;
5898 for (unsigned I = 0; I != NumParams; ++I)
5899 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5900
John McCall18afab72016-03-01 00:49:02 +00005901 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5902 if (Idx != Record.size()) {
5903 for (unsigned I = 0; I != NumParams; ++I)
5904 ExtParameterInfos.push_back(
5905 FunctionProtoType::ExtParameterInfo
5906 ::getFromOpaqueValue(Record[Idx++]));
5907 EPI.ExtParameterInfos = ExtParameterInfos.data();
5908 }
5909
5910 assert(Idx == Record.size());
5911
Jordan Rose5c382722013-03-08 21:51:21 +00005912 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005913 }
5914
5915 case TYPE_UNRESOLVED_USING: {
5916 unsigned Idx = 0;
5917 return Context.getTypeDeclType(
5918 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5919 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005920
Guy Benyei11169dd2012-12-18 14:30:41 +00005921 case TYPE_TYPEDEF: {
5922 if (Record.size() != 2) {
5923 Error("incorrect encoding of typedef type");
5924 return QualType();
5925 }
5926 unsigned Idx = 0;
5927 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5928 QualType Canonical = readType(*Loc.F, Record, Idx);
5929 if (!Canonical.isNull())
5930 Canonical = Context.getCanonicalType(Canonical);
5931 return Context.getTypedefType(Decl, Canonical);
5932 }
5933
5934 case TYPE_TYPEOF_EXPR:
5935 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5936
5937 case TYPE_TYPEOF: {
5938 if (Record.size() != 1) {
5939 Error("incorrect encoding of typeof(type) in AST file");
5940 return QualType();
5941 }
5942 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5943 return Context.getTypeOfType(UnderlyingType);
5944 }
5945
5946 case TYPE_DECLTYPE: {
5947 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5948 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
5949 }
5950
5951 case TYPE_UNARY_TRANSFORM: {
5952 QualType BaseType = readType(*Loc.F, Record, Idx);
5953 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5954 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
5955 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
5956 }
5957
Richard Smith74aeef52013-04-26 16:15:35 +00005958 case TYPE_AUTO: {
5959 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00005960 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00005961 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00005962 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00005963 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005964
Richard Smith600b5262017-01-26 20:40:47 +00005965 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
5966 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
5967 QualType Deduced = readType(*Loc.F, Record, Idx);
5968 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
5969 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
5970 IsDependent);
5971 }
5972
Guy Benyei11169dd2012-12-18 14:30:41 +00005973 case TYPE_RECORD: {
5974 if (Record.size() != 2) {
5975 Error("incorrect encoding of record type");
5976 return QualType();
5977 }
5978 unsigned Idx = 0;
5979 bool IsDependent = Record[Idx++];
5980 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
5981 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
5982 QualType T = Context.getRecordType(RD);
5983 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5984 return T;
5985 }
5986
5987 case TYPE_ENUM: {
5988 if (Record.size() != 2) {
5989 Error("incorrect encoding of enum type");
5990 return QualType();
5991 }
5992 unsigned Idx = 0;
5993 bool IsDependent = Record[Idx++];
5994 QualType T
5995 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
5996 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
5997 return T;
5998 }
5999
6000 case TYPE_ATTRIBUTED: {
6001 if (Record.size() != 3) {
6002 Error("incorrect encoding of attributed type");
6003 return QualType();
6004 }
6005 QualType modifiedType = readType(*Loc.F, Record, Idx);
6006 QualType equivalentType = readType(*Loc.F, Record, Idx);
6007 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6008 return Context.getAttributedType(kind, modifiedType, equivalentType);
6009 }
6010
6011 case TYPE_PAREN: {
6012 if (Record.size() != 1) {
6013 Error("incorrect encoding of paren type");
6014 return QualType();
6015 }
6016 QualType InnerType = readType(*Loc.F, Record, Idx);
6017 return Context.getParenType(InnerType);
6018 }
6019
6020 case TYPE_PACK_EXPANSION: {
6021 if (Record.size() != 2) {
6022 Error("incorrect encoding of pack expansion type");
6023 return QualType();
6024 }
6025 QualType Pattern = readType(*Loc.F, Record, Idx);
6026 if (Pattern.isNull())
6027 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006028 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006029 if (Record[1])
6030 NumExpansions = Record[1] - 1;
6031 return Context.getPackExpansionType(Pattern, NumExpansions);
6032 }
6033
6034 case TYPE_ELABORATED: {
6035 unsigned Idx = 0;
6036 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6037 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6038 QualType NamedType = readType(*Loc.F, Record, Idx);
6039 return Context.getElaboratedType(Keyword, NNS, NamedType);
6040 }
6041
6042 case TYPE_OBJC_INTERFACE: {
6043 unsigned Idx = 0;
6044 ObjCInterfaceDecl *ItfD
6045 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6046 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6047 }
6048
Manman Rene6be26c2016-09-13 17:25:08 +00006049 case TYPE_OBJC_TYPE_PARAM: {
6050 unsigned Idx = 0;
6051 ObjCTypeParamDecl *Decl
6052 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6053 unsigned NumProtos = Record[Idx++];
6054 SmallVector<ObjCProtocolDecl*, 4> Protos;
6055 for (unsigned I = 0; I != NumProtos; ++I)
6056 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6057 return Context.getObjCTypeParamType(Decl, Protos);
6058 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006059 case TYPE_OBJC_OBJECT: {
6060 unsigned Idx = 0;
6061 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006062 unsigned NumTypeArgs = Record[Idx++];
6063 SmallVector<QualType, 4> TypeArgs;
6064 for (unsigned I = 0; I != NumTypeArgs; ++I)
6065 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006066 unsigned NumProtos = Record[Idx++];
6067 SmallVector<ObjCProtocolDecl*, 4> Protos;
6068 for (unsigned I = 0; I != NumProtos; ++I)
6069 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006070 bool IsKindOf = Record[Idx++];
6071 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006072 }
6073
6074 case TYPE_OBJC_OBJECT_POINTER: {
6075 unsigned Idx = 0;
6076 QualType Pointee = readType(*Loc.F, Record, Idx);
6077 return Context.getObjCObjectPointerType(Pointee);
6078 }
6079
6080 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6081 unsigned Idx = 0;
6082 QualType Parm = readType(*Loc.F, Record, Idx);
6083 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006084 return Context.getSubstTemplateTypeParmType(
6085 cast<TemplateTypeParmType>(Parm),
6086 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006087 }
6088
6089 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6090 unsigned Idx = 0;
6091 QualType Parm = readType(*Loc.F, Record, Idx);
6092 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6093 return Context.getSubstTemplateTypeParmPackType(
6094 cast<TemplateTypeParmType>(Parm),
6095 ArgPack);
6096 }
6097
6098 case TYPE_INJECTED_CLASS_NAME: {
6099 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6100 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6101 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6102 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006103 const Type *T = nullptr;
6104 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6105 if (const Type *Existing = DI->getTypeForDecl()) {
6106 T = Existing;
6107 break;
6108 }
6109 }
6110 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006111 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006112 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6113 DI->setTypeForDecl(T);
6114 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006115 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006116 }
6117
6118 case TYPE_TEMPLATE_TYPE_PARM: {
6119 unsigned Idx = 0;
6120 unsigned Depth = Record[Idx++];
6121 unsigned Index = Record[Idx++];
6122 bool Pack = Record[Idx++];
6123 TemplateTypeParmDecl *D
6124 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6125 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6126 }
6127
6128 case TYPE_DEPENDENT_NAME: {
6129 unsigned Idx = 0;
6130 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6131 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006132 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006133 QualType Canon = readType(*Loc.F, Record, Idx);
6134 if (!Canon.isNull())
6135 Canon = Context.getCanonicalType(Canon);
6136 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6137 }
6138
6139 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6140 unsigned Idx = 0;
6141 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6142 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006143 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006144 unsigned NumArgs = Record[Idx++];
6145 SmallVector<TemplateArgument, 8> Args;
6146 Args.reserve(NumArgs);
6147 while (NumArgs--)
6148 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6149 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006150 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006151 }
6152
6153 case TYPE_DEPENDENT_SIZED_ARRAY: {
6154 unsigned Idx = 0;
6155
6156 // ArrayType
6157 QualType ElementType = readType(*Loc.F, Record, Idx);
6158 ArrayType::ArraySizeModifier ASM
6159 = (ArrayType::ArraySizeModifier)Record[Idx++];
6160 unsigned IndexTypeQuals = Record[Idx++];
6161
6162 // DependentSizedArrayType
6163 Expr *NumElts = ReadExpr(*Loc.F);
6164 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6165
6166 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6167 IndexTypeQuals, Brackets);
6168 }
6169
6170 case TYPE_TEMPLATE_SPECIALIZATION: {
6171 unsigned Idx = 0;
6172 bool IsDependent = Record[Idx++];
6173 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6174 SmallVector<TemplateArgument, 8> Args;
6175 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6176 QualType Underlying = readType(*Loc.F, Record, Idx);
6177 QualType T;
6178 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006179 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006180 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006181 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006182 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6183 return T;
6184 }
6185
6186 case TYPE_ATOMIC: {
6187 if (Record.size() != 1) {
6188 Error("Incorrect encoding of atomic type");
6189 return QualType();
6190 }
6191 QualType ValueType = readType(*Loc.F, Record, Idx);
6192 return Context.getAtomicType(ValueType);
6193 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006194
Joey Goulye3c85de2016-12-01 11:30:49 +00006195 case TYPE_PIPE: {
6196 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006197 Error("Incorrect encoding of pipe type");
6198 return QualType();
6199 }
6200
6201 // Reading the pipe element type.
6202 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006203 unsigned ReadOnly = Record[1];
6204 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006205 }
6206
Alex Lorenz00aee432017-03-22 10:04:48 +00006207 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6208 unsigned Idx = 0;
6209
6210 // DependentSizedExtVectorType
6211 QualType ElementType = readType(*Loc.F, Record, Idx);
6212 Expr *SizeExpr = ReadExpr(*Loc.F);
6213 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6214
6215 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6216 AttrLoc);
6217 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006218 }
6219 llvm_unreachable("Invalid TypeCode!");
6220}
6221
Richard Smith564417a2014-03-20 21:47:22 +00006222void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6223 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006224 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006225 const RecordData &Record, unsigned &Idx) {
6226 ExceptionSpecificationType EST =
6227 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006228 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006229 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006230 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006231 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006232 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006233 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006234 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006235 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006236 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6237 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006238 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006239 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006240 }
6241}
6242
Guy Benyei11169dd2012-12-18 14:30:41 +00006243class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006244 ModuleFile *F;
6245 ASTReader *Reader;
6246 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006247 unsigned &Idx;
6248
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006249 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006250 return Reader->ReadSourceLocation(*F, Record, Idx);
6251 }
6252
6253 TypeSourceInfo *GetTypeSourceInfo() {
6254 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6255 }
6256
6257 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6258 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006259 }
6260
Guy Benyei11169dd2012-12-18 14:30:41 +00006261public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006262 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006263 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006264 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006265
6266 // We want compile-time assurance that we've enumerated all of
6267 // these, so unfortunately we have to declare them first, then
6268 // define them out-of-line.
6269#define ABSTRACT_TYPELOC(CLASS, PARENT)
6270#define TYPELOC(CLASS, PARENT) \
6271 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6272#include "clang/AST/TypeLocNodes.def"
6273
6274 void VisitFunctionTypeLoc(FunctionTypeLoc);
6275 void VisitArrayTypeLoc(ArrayTypeLoc);
6276};
6277
6278void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6279 // nothing to do
6280}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006281
Guy Benyei11169dd2012-12-18 14:30:41 +00006282void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006283 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006284 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006285 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6286 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6287 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6288 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006289 }
6290}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006291
Guy Benyei11169dd2012-12-18 14:30:41 +00006292void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006293 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006294}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006295
Guy Benyei11169dd2012-12-18 14:30:41 +00006296void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006297 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006298}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006299
Reid Kleckner8a365022013-06-24 17:51:48 +00006300void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6301 // nothing to do
6302}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006303
Reid Kleckner0503a872013-12-05 01:23:43 +00006304void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6305 // nothing to do
6306}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006307
Guy Benyei11169dd2012-12-18 14:30:41 +00006308void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006309 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006310}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006311
Guy Benyei11169dd2012-12-18 14:30:41 +00006312void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006313 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006314}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006315
Guy Benyei11169dd2012-12-18 14:30:41 +00006316void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006317 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006318}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006319
Guy Benyei11169dd2012-12-18 14:30:41 +00006320void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006321 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006322 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006323}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006324
Guy Benyei11169dd2012-12-18 14:30:41 +00006325void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006326 TL.setLBracketLoc(ReadSourceLocation());
6327 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006328 if (Record[Idx++])
6329 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 else
Craig Toppera13603a2014-05-22 05:54:18 +00006331 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006332}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006333
Guy Benyei11169dd2012-12-18 14:30:41 +00006334void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6335 VisitArrayTypeLoc(TL);
6336}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006337
Guy Benyei11169dd2012-12-18 14:30:41 +00006338void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6339 VisitArrayTypeLoc(TL);
6340}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006341
Guy Benyei11169dd2012-12-18 14:30:41 +00006342void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6343 VisitArrayTypeLoc(TL);
6344}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006345
Guy Benyei11169dd2012-12-18 14:30:41 +00006346void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6347 DependentSizedArrayTypeLoc TL) {
6348 VisitArrayTypeLoc(TL);
6349}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006350
Guy Benyei11169dd2012-12-18 14:30:41 +00006351void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6352 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006353 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006354}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006355
Guy Benyei11169dd2012-12-18 14:30:41 +00006356void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006357 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006358}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006359
Guy Benyei11169dd2012-12-18 14:30:41 +00006360void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006361 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006362}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006363
Guy Benyei11169dd2012-12-18 14:30:41 +00006364void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006365 TL.setLocalRangeBegin(ReadSourceLocation());
6366 TL.setLParenLoc(ReadSourceLocation());
6367 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006368 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6369 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006370 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006371 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006372 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006373 }
6374}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006375
Guy Benyei11169dd2012-12-18 14:30:41 +00006376void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6377 VisitFunctionTypeLoc(TL);
6378}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006379
Guy Benyei11169dd2012-12-18 14:30:41 +00006380void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6381 VisitFunctionTypeLoc(TL);
6382}
6383void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006384 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006385}
6386void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006387 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006388}
6389void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006390 TL.setTypeofLoc(ReadSourceLocation());
6391 TL.setLParenLoc(ReadSourceLocation());
6392 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006393}
6394void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006395 TL.setTypeofLoc(ReadSourceLocation());
6396 TL.setLParenLoc(ReadSourceLocation());
6397 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006398 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006399}
6400void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006401 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006402}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006403
Guy Benyei11169dd2012-12-18 14:30:41 +00006404void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006405 TL.setKWLoc(ReadSourceLocation());
6406 TL.setLParenLoc(ReadSourceLocation());
6407 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006408 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006409}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006410
Guy Benyei11169dd2012-12-18 14:30:41 +00006411void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006412 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006413}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006414
Richard Smith600b5262017-01-26 20:40:47 +00006415void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6416 DeducedTemplateSpecializationTypeLoc TL) {
6417 TL.setTemplateNameLoc(ReadSourceLocation());
6418}
6419
Guy Benyei11169dd2012-12-18 14:30:41 +00006420void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006421 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006422}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006423
Guy Benyei11169dd2012-12-18 14:30:41 +00006424void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006425 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006426}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006427
Guy Benyei11169dd2012-12-18 14:30:41 +00006428void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006429 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006430 if (TL.hasAttrOperand()) {
6431 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006432 range.setBegin(ReadSourceLocation());
6433 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006434 TL.setAttrOperandParensRange(range);
6435 }
6436 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006437 if (Record[Idx++])
6438 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006439 else
Craig Toppera13603a2014-05-22 05:54:18 +00006440 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006441 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006442 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006443}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006444
Guy Benyei11169dd2012-12-18 14:30:41 +00006445void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006446 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006447}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006448
Guy Benyei11169dd2012-12-18 14:30:41 +00006449void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6450 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006451 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006452}
6453void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6454 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006455 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006456}
6457void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6458 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006459 TL.setTemplateKeywordLoc(ReadSourceLocation());
6460 TL.setTemplateNameLoc(ReadSourceLocation());
6461 TL.setLAngleLoc(ReadSourceLocation());
6462 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006463 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006464 TL.setArgLocInfo(
6465 i,
6466 Reader->GetTemplateArgumentLocInfo(
6467 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006468}
6469void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006470 TL.setLParenLoc(ReadSourceLocation());
6471 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006472}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006473
Guy Benyei11169dd2012-12-18 14:30:41 +00006474void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006475 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006476 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006477}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006478
Guy Benyei11169dd2012-12-18 14:30:41 +00006479void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006480 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006481}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006482
Guy Benyei11169dd2012-12-18 14:30:41 +00006483void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006484 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006485 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006486 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006487}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006488
Guy Benyei11169dd2012-12-18 14:30:41 +00006489void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6490 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006491 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006492 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006493 TL.setTemplateKeywordLoc(ReadSourceLocation());
6494 TL.setTemplateNameLoc(ReadSourceLocation());
6495 TL.setLAngleLoc(ReadSourceLocation());
6496 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006497 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006498 TL.setArgLocInfo(
6499 I,
6500 Reader->GetTemplateArgumentLocInfo(
6501 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006502}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006503
Guy Benyei11169dd2012-12-18 14:30:41 +00006504void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006505 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006506}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006507
Guy Benyei11169dd2012-12-18 14:30:41 +00006508void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006509 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006510}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006511
Manman Rene6be26c2016-09-13 17:25:08 +00006512void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6513 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006514 TL.setProtocolLAngleLoc(ReadSourceLocation());
6515 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006516 }
6517 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006518 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006519}
6520
Guy Benyei11169dd2012-12-18 14:30:41 +00006521void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006522 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006523 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6524 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006525 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006526 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006527 TL.setProtocolLAngleLoc(ReadSourceLocation());
6528 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006529 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006530 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006531}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006532
Guy Benyei11169dd2012-12-18 14:30:41 +00006533void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006534 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006535}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006536
Guy Benyei11169dd2012-12-18 14:30:41 +00006537void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006538 TL.setKWLoc(ReadSourceLocation());
6539 TL.setLParenLoc(ReadSourceLocation());
6540 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006541}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006542
Xiuli Pan9c14e282016-01-09 12:53:17 +00006543void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006544 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006545}
Guy Benyei11169dd2012-12-18 14:30:41 +00006546
David L. Jonesbe1557a2016-12-21 00:17:49 +00006547TypeSourceInfo *
6548ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6549 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006550 QualType InfoTy = readType(F, Record, Idx);
6551 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006552 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006553
6554 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006555 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006556 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6557 TLR.Visit(TL);
6558 return TInfo;
6559}
6560
6561QualType ASTReader::GetType(TypeID ID) {
6562 unsigned FastQuals = ID & Qualifiers::FastMask;
6563 unsigned Index = ID >> Qualifiers::FastWidth;
6564
6565 if (Index < NUM_PREDEF_TYPE_IDS) {
6566 QualType T;
6567 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006568 case PREDEF_TYPE_NULL_ID:
6569 return QualType();
6570 case PREDEF_TYPE_VOID_ID:
6571 T = Context.VoidTy;
6572 break;
6573 case PREDEF_TYPE_BOOL_ID:
6574 T = Context.BoolTy;
6575 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006576
6577 case PREDEF_TYPE_CHAR_U_ID:
6578 case PREDEF_TYPE_CHAR_S_ID:
6579 // FIXME: Check that the signedness of CharTy is correct!
6580 T = Context.CharTy;
6581 break;
6582
Alexey Baderbdf7c842015-09-15 12:18:29 +00006583 case PREDEF_TYPE_UCHAR_ID:
6584 T = Context.UnsignedCharTy;
6585 break;
6586 case PREDEF_TYPE_USHORT_ID:
6587 T = Context.UnsignedShortTy;
6588 break;
6589 case PREDEF_TYPE_UINT_ID:
6590 T = Context.UnsignedIntTy;
6591 break;
6592 case PREDEF_TYPE_ULONG_ID:
6593 T = Context.UnsignedLongTy;
6594 break;
6595 case PREDEF_TYPE_ULONGLONG_ID:
6596 T = Context.UnsignedLongLongTy;
6597 break;
6598 case PREDEF_TYPE_UINT128_ID:
6599 T = Context.UnsignedInt128Ty;
6600 break;
6601 case PREDEF_TYPE_SCHAR_ID:
6602 T = Context.SignedCharTy;
6603 break;
6604 case PREDEF_TYPE_WCHAR_ID:
6605 T = Context.WCharTy;
6606 break;
6607 case PREDEF_TYPE_SHORT_ID:
6608 T = Context.ShortTy;
6609 break;
6610 case PREDEF_TYPE_INT_ID:
6611 T = Context.IntTy;
6612 break;
6613 case PREDEF_TYPE_LONG_ID:
6614 T = Context.LongTy;
6615 break;
6616 case PREDEF_TYPE_LONGLONG_ID:
6617 T = Context.LongLongTy;
6618 break;
6619 case PREDEF_TYPE_INT128_ID:
6620 T = Context.Int128Ty;
6621 break;
6622 case PREDEF_TYPE_HALF_ID:
6623 T = Context.HalfTy;
6624 break;
6625 case PREDEF_TYPE_FLOAT_ID:
6626 T = Context.FloatTy;
6627 break;
6628 case PREDEF_TYPE_DOUBLE_ID:
6629 T = Context.DoubleTy;
6630 break;
6631 case PREDEF_TYPE_LONGDOUBLE_ID:
6632 T = Context.LongDoubleTy;
6633 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006634 case PREDEF_TYPE_FLOAT128_ID:
6635 T = Context.Float128Ty;
6636 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006637 case PREDEF_TYPE_OVERLOAD_ID:
6638 T = Context.OverloadTy;
6639 break;
6640 case PREDEF_TYPE_BOUND_MEMBER:
6641 T = Context.BoundMemberTy;
6642 break;
6643 case PREDEF_TYPE_PSEUDO_OBJECT:
6644 T = Context.PseudoObjectTy;
6645 break;
6646 case PREDEF_TYPE_DEPENDENT_ID:
6647 T = Context.DependentTy;
6648 break;
6649 case PREDEF_TYPE_UNKNOWN_ANY:
6650 T = Context.UnknownAnyTy;
6651 break;
6652 case PREDEF_TYPE_NULLPTR_ID:
6653 T = Context.NullPtrTy;
6654 break;
6655 case PREDEF_TYPE_CHAR16_ID:
6656 T = Context.Char16Ty;
6657 break;
6658 case PREDEF_TYPE_CHAR32_ID:
6659 T = Context.Char32Ty;
6660 break;
6661 case PREDEF_TYPE_OBJC_ID:
6662 T = Context.ObjCBuiltinIdTy;
6663 break;
6664 case PREDEF_TYPE_OBJC_CLASS:
6665 T = Context.ObjCBuiltinClassTy;
6666 break;
6667 case PREDEF_TYPE_OBJC_SEL:
6668 T = Context.ObjCBuiltinSelTy;
6669 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006670#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6671 case PREDEF_TYPE_##Id##_ID: \
6672 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006673 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006674#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006675 case PREDEF_TYPE_SAMPLER_ID:
6676 T = Context.OCLSamplerTy;
6677 break;
6678 case PREDEF_TYPE_EVENT_ID:
6679 T = Context.OCLEventTy;
6680 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006681 case PREDEF_TYPE_CLK_EVENT_ID:
6682 T = Context.OCLClkEventTy;
6683 break;
6684 case PREDEF_TYPE_QUEUE_ID:
6685 T = Context.OCLQueueTy;
6686 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006687 case PREDEF_TYPE_RESERVE_ID_ID:
6688 T = Context.OCLReserveIDTy;
6689 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006690 case PREDEF_TYPE_AUTO_DEDUCT:
6691 T = Context.getAutoDeductType();
6692 break;
6693
6694 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6695 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006696 break;
6697
6698 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6699 T = Context.ARCUnbridgedCastTy;
6700 break;
6701
Guy Benyei11169dd2012-12-18 14:30:41 +00006702 case PREDEF_TYPE_BUILTIN_FN:
6703 T = Context.BuiltinFnTy;
6704 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006705
6706 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6707 T = Context.OMPArraySectionTy;
6708 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006709 }
6710
6711 assert(!T.isNull() && "Unknown predefined type");
6712 return T.withFastQualifiers(FastQuals);
6713 }
6714
6715 Index -= NUM_PREDEF_TYPE_IDS;
6716 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6717 if (TypesLoaded[Index].isNull()) {
6718 TypesLoaded[Index] = readTypeRecord(Index);
6719 if (TypesLoaded[Index].isNull())
6720 return QualType();
6721
6722 TypesLoaded[Index]->setFromAST();
6723 if (DeserializationListener)
6724 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6725 TypesLoaded[Index]);
6726 }
6727
6728 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6729}
6730
6731QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6732 return GetType(getGlobalTypeID(F, LocalID));
6733}
6734
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006735serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006736ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6737 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6738 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006739
Guy Benyei11169dd2012-12-18 14:30:41 +00006740 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6741 return LocalID;
6742
Richard Smith37a93df2017-02-18 00:32:02 +00006743 if (!F.ModuleOffsetMap.empty())
6744 ReadModuleOffsetMap(F);
6745
Guy Benyei11169dd2012-12-18 14:30:41 +00006746 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6747 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6748 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006749
Guy Benyei11169dd2012-12-18 14:30:41 +00006750 unsigned GlobalIndex = LocalIndex + I->second;
6751 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6752}
6753
6754TemplateArgumentLocInfo
6755ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6756 TemplateArgument::ArgKind Kind,
6757 const RecordData &Record,
6758 unsigned &Index) {
6759 switch (Kind) {
6760 case TemplateArgument::Expression:
6761 return ReadExpr(F);
6762 case TemplateArgument::Type:
6763 return GetTypeSourceInfo(F, Record, Index);
6764 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006765 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006766 Index);
6767 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6768 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6769 SourceLocation());
6770 }
6771 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006772 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006773 Index);
6774 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6775 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006776 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006777 EllipsisLoc);
6778 }
6779 case TemplateArgument::Null:
6780 case TemplateArgument::Integral:
6781 case TemplateArgument::Declaration:
6782 case TemplateArgument::NullPtr:
6783 case TemplateArgument::Pack:
6784 // FIXME: Is this right?
6785 return TemplateArgumentLocInfo();
6786 }
6787 llvm_unreachable("unexpected template argument loc");
6788}
6789
6790TemplateArgumentLoc
6791ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6792 const RecordData &Record, unsigned &Index) {
6793 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6794
6795 if (Arg.getKind() == TemplateArgument::Expression) {
6796 if (Record[Index++]) // bool InfoHasSameExpr.
6797 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6798 }
6799 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6800 Record, Index));
6801}
6802
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006803const ASTTemplateArgumentListInfo*
6804ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6805 const RecordData &Record,
6806 unsigned &Index) {
6807 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6808 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6809 unsigned NumArgsAsWritten = Record[Index++];
6810 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6811 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6812 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6813 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6814}
6815
Guy Benyei11169dd2012-12-18 14:30:41 +00006816Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6817 return GetDecl(ID);
6818}
6819
Richard Smith053f6c62014-05-16 23:01:30 +00006820void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006821 if (NumCurrentElementsDeserializing) {
6822 // We arrange to not care about the complete redeclaration chain while we're
6823 // deserializing. Just remember that the AST has marked this one as complete
6824 // but that it's not actually complete yet, so we know we still need to
6825 // complete it later.
6826 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6827 return;
6828 }
6829
Richard Smith053f6c62014-05-16 23:01:30 +00006830 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6831
Richard Smith053f6c62014-05-16 23:01:30 +00006832 // If this is a named declaration, complete it by looking it up
6833 // within its context.
6834 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006835 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006836 // all mergeable entities within it.
6837 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6838 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6839 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006840 if (!getContext().getLangOpts().CPlusPlus &&
6841 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006842 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006843 // the identifier instead. (For C++ modules, we don't store decls
6844 // in the serialized identifier table, so we do the lookup in the TU.)
6845 auto *II = Name.getAsIdentifierInfo();
6846 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006847 if (II->isOutOfDate())
6848 updateOutOfDateIdentifier(*II);
6849 } else
6850 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006851 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006852 // Find all declarations of this kind from the relevant context.
6853 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6854 auto *DC = cast<DeclContext>(DCDecl);
6855 SmallVector<Decl*, 8> Decls;
6856 FindExternalLexicalDecls(
6857 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6858 }
Richard Smith053f6c62014-05-16 23:01:30 +00006859 }
6860 }
Richard Smith50895422015-01-31 03:04:55 +00006861
6862 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6863 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6864 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6865 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6866 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6867 if (auto *Template = FD->getPrimaryTemplate())
6868 Template->LoadLazySpecializations();
6869 }
Richard Smith053f6c62014-05-16 23:01:30 +00006870}
6871
Richard Smithc2bb8182015-03-24 06:36:48 +00006872CXXCtorInitializer **
6873ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6874 RecordLocation Loc = getLocalBitOffset(Offset);
6875 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6876 SavedStreamPosition SavedPosition(Cursor);
6877 Cursor.JumpToBit(Loc.Offset);
6878 ReadingKindTracker ReadingKind(Read_Decl, *this);
6879
6880 RecordData Record;
6881 unsigned Code = Cursor.ReadCode();
6882 unsigned RecCode = Cursor.readRecord(Code, Record);
6883 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6884 Error("malformed AST file: missing C++ ctor initializers");
6885 return nullptr;
6886 }
6887
6888 unsigned Idx = 0;
6889 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6890}
6891
Guy Benyei11169dd2012-12-18 14:30:41 +00006892CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
6893 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006894 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006895 SavedStreamPosition SavedPosition(Cursor);
6896 Cursor.JumpToBit(Loc.Offset);
6897 ReadingKindTracker ReadingKind(Read_Decl, *this);
6898 RecordData Record;
6899 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006900 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006901 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006902 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006903 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006904 }
6905
6906 unsigned Idx = 0;
6907 unsigned NumBases = Record[Idx++];
6908 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6909 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6910 for (unsigned I = 0; I != NumBases; ++I)
6911 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6912 return Bases;
6913}
6914
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006915serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00006916ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
6917 if (LocalID < NUM_PREDEF_DECL_IDS)
6918 return LocalID;
6919
Richard Smith37a93df2017-02-18 00:32:02 +00006920 if (!F.ModuleOffsetMap.empty())
6921 ReadModuleOffsetMap(F);
6922
Guy Benyei11169dd2012-12-18 14:30:41 +00006923 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6924 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
6925 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006926
Guy Benyei11169dd2012-12-18 14:30:41 +00006927 return LocalID + I->second;
6928}
6929
6930bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
6931 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00006932 // Predefined decls aren't from any module.
6933 if (ID < NUM_PREDEF_DECL_IDS)
6934 return false;
6935
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006936 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00006937 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00006938}
6939
Douglas Gregor9f782892013-01-21 15:25:38 +00006940ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006941 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00006942 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006943 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
6944 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
6945 return I->second;
6946}
6947
6948SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
6949 if (ID < NUM_PREDEF_DECL_IDS)
6950 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00006951
Guy Benyei11169dd2012-12-18 14:30:41 +00006952 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
6953
6954 if (Index > DeclsLoaded.size()) {
6955 Error("declaration ID out-of-range for AST file");
6956 return SourceLocation();
6957 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00006958
Guy Benyei11169dd2012-12-18 14:30:41 +00006959 if (Decl *D = DeclsLoaded[Index])
6960 return D->getLocation();
6961
Richard Smithcb34bd32016-03-27 07:28:06 +00006962 SourceLocation Loc;
6963 DeclCursorForID(ID, Loc);
6964 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00006965}
6966
Richard Smithfe620d22015-03-05 23:24:12 +00006967static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
6968 switch (ID) {
6969 case PREDEF_DECL_NULL_ID:
6970 return nullptr;
6971
6972 case PREDEF_DECL_TRANSLATION_UNIT_ID:
6973 return Context.getTranslationUnitDecl();
6974
6975 case PREDEF_DECL_OBJC_ID_ID:
6976 return Context.getObjCIdDecl();
6977
6978 case PREDEF_DECL_OBJC_SEL_ID:
6979 return Context.getObjCSelDecl();
6980
6981 case PREDEF_DECL_OBJC_CLASS_ID:
6982 return Context.getObjCClassDecl();
6983
6984 case PREDEF_DECL_OBJC_PROTOCOL_ID:
6985 return Context.getObjCProtocolDecl();
6986
6987 case PREDEF_DECL_INT_128_ID:
6988 return Context.getInt128Decl();
6989
6990 case PREDEF_DECL_UNSIGNED_INT_128_ID:
6991 return Context.getUInt128Decl();
6992
6993 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
6994 return Context.getObjCInstanceTypeDecl();
6995
6996 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
6997 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00006998
Richard Smith9b88a4c2015-07-27 05:40:23 +00006999 case PREDEF_DECL_VA_LIST_TAG:
7000 return Context.getVaListTagDecl();
7001
Charles Davisc7d5c942015-09-17 20:55:33 +00007002 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7003 return Context.getBuiltinMSVaListDecl();
7004
Richard Smithf19e1272015-03-07 00:04:49 +00007005 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7006 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007007
7008 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7009 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007010
7011 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7012 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007013
7014 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7015 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007016
7017 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7018 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007019 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007020 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007021}
7022
Richard Smithcd45dbc2014-04-19 03:48:30 +00007023Decl *ASTReader::GetExistingDecl(DeclID ID) {
7024 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithfe620d22015-03-05 23:24:12 +00007025 Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
7026 if (D) {
7027 // Track that we have merged the declaration with ID \p ID into the
7028 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007029 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007030 if (Merged.empty())
7031 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007032 }
Richard Smithfe620d22015-03-05 23:24:12 +00007033 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007034 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007035
Guy Benyei11169dd2012-12-18 14:30:41 +00007036 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7037
7038 if (Index >= DeclsLoaded.size()) {
7039 assert(0 && "declaration ID out-of-range for AST file");
7040 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007041 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007042 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007043
7044 return DeclsLoaded[Index];
7045}
7046
7047Decl *ASTReader::GetDecl(DeclID ID) {
7048 if (ID < NUM_PREDEF_DECL_IDS)
7049 return GetExistingDecl(ID);
7050
7051 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7052
7053 if (Index >= DeclsLoaded.size()) {
7054 assert(0 && "declaration ID out-of-range for AST file");
7055 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007056 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007057 }
7058
Guy Benyei11169dd2012-12-18 14:30:41 +00007059 if (!DeclsLoaded[Index]) {
7060 ReadDeclRecord(ID);
7061 if (DeserializationListener)
7062 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7063 }
7064
7065 return DeclsLoaded[Index];
7066}
7067
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007068DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007069 DeclID GlobalID) {
7070 if (GlobalID < NUM_PREDEF_DECL_IDS)
7071 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007072
Guy Benyei11169dd2012-12-18 14:30:41 +00007073 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7074 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7075 ModuleFile *Owner = I->second;
7076
7077 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7078 = M.GlobalToLocalDeclIDs.find(Owner);
7079 if (Pos == M.GlobalToLocalDeclIDs.end())
7080 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007081
Guy Benyei11169dd2012-12-18 14:30:41 +00007082 return GlobalID - Owner->BaseDeclID + Pos->second;
7083}
7084
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007085serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007086 const RecordData &Record,
7087 unsigned &Idx) {
7088 if (Idx >= Record.size()) {
7089 Error("Corrupted AST file");
7090 return 0;
7091 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007092
Guy Benyei11169dd2012-12-18 14:30:41 +00007093 return getGlobalDeclID(F, Record[Idx++]);
7094}
7095
7096/// \brief Resolve the offset of a statement into a statement.
7097///
7098/// This operation will read a new statement from the external
7099/// source each time it is called, and is meant to be used via a
7100/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7101Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7102 // Switch case IDs are per Decl.
7103 ClearSwitchCaseIDs();
7104
7105 // Offset here is a global offset across the entire chain.
7106 RecordLocation Loc = getLocalBitOffset(Offset);
7107 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007108 assert(NumCurrentElementsDeserializing == 0 &&
7109 "should not be called while already deserializing");
7110 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007111 return ReadStmtFromStream(*Loc.F);
7112}
7113
Richard Smith3cb15722015-08-05 22:41:45 +00007114void ASTReader::FindExternalLexicalDecls(
7115 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7116 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007117 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7118
Richard Smith9ccdd932015-08-06 22:14:12 +00007119 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007120 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7121 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7122 auto K = (Decl::Kind)+LexicalDecls[I];
7123 if (!IsKindWeWant(K))
7124 continue;
7125
7126 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7127
7128 // Don't add predefined declarations to the lexical context more
7129 // than once.
7130 if (ID < NUM_PREDEF_DECL_IDS) {
7131 if (PredefsVisited[ID])
7132 continue;
7133
7134 PredefsVisited[ID] = true;
7135 }
7136
7137 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007138 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007139 if (!DC->isDeclInLexicalTraversal(D))
7140 Decls.push_back(D);
7141 }
7142 }
7143 };
7144
7145 if (isa<TranslationUnitDecl>(DC)) {
7146 for (auto Lexical : TULexicalDecls)
7147 Visit(Lexical.first, Lexical.second);
7148 } else {
7149 auto I = LexicalDecls.find(DC);
7150 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007151 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007152 }
7153
Guy Benyei11169dd2012-12-18 14:30:41 +00007154 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007155}
7156
7157namespace {
7158
7159class DeclIDComp {
7160 ASTReader &Reader;
7161 ModuleFile &Mod;
7162
7163public:
7164 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7165
7166 bool operator()(LocalDeclID L, LocalDeclID R) const {
7167 SourceLocation LHS = getLocation(L);
7168 SourceLocation RHS = getLocation(R);
7169 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7170 }
7171
7172 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7173 SourceLocation RHS = getLocation(R);
7174 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7175 }
7176
7177 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7178 SourceLocation LHS = getLocation(L);
7179 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7180 }
7181
7182 SourceLocation getLocation(LocalDeclID ID) const {
7183 return Reader.getSourceManager().getFileLoc(
7184 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7185 }
7186};
7187
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007188} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007189
7190void ASTReader::FindFileRegionDecls(FileID File,
7191 unsigned Offset, unsigned Length,
7192 SmallVectorImpl<Decl *> &Decls) {
7193 SourceManager &SM = getSourceManager();
7194
7195 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7196 if (I == FileDeclIDs.end())
7197 return;
7198
7199 FileDeclsInfo &DInfo = I->second;
7200 if (DInfo.Decls.empty())
7201 return;
7202
7203 SourceLocation
7204 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7205 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7206
7207 DeclIDComp DIDComp(*this, *DInfo.Mod);
7208 ArrayRef<serialization::LocalDeclID>::iterator
7209 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7210 BeginLoc, DIDComp);
7211 if (BeginIt != DInfo.Decls.begin())
7212 --BeginIt;
7213
7214 // If we are pointing at a top-level decl inside an objc container, we need
7215 // to backtrack until we find it otherwise we will fail to report that the
7216 // region overlaps with an objc container.
7217 while (BeginIt != DInfo.Decls.begin() &&
7218 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7219 ->isTopLevelDeclInObjCContainer())
7220 --BeginIt;
7221
7222 ArrayRef<serialization::LocalDeclID>::iterator
7223 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7224 EndLoc, DIDComp);
7225 if (EndIt != DInfo.Decls.end())
7226 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007227
Guy Benyei11169dd2012-12-18 14:30:41 +00007228 for (ArrayRef<serialization::LocalDeclID>::iterator
7229 DIt = BeginIt; DIt != EndIt; ++DIt)
7230 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7231}
7232
Richard Smith9ce12e32013-02-07 03:30:24 +00007233bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007234ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7235 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007236 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007237 "DeclContext has no visible decls in storage");
7238 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007239 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007240
Richard Smithd88a7f12015-09-01 20:35:42 +00007241 auto It = Lookups.find(DC);
7242 if (It == Lookups.end())
7243 return false;
7244
Richard Smith8c913ec2014-08-14 02:21:01 +00007245 Deserializing LookupResults(this);
7246
Richard Smithd88a7f12015-09-01 20:35:42 +00007247 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007248 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007249 for (DeclID ID : It->second.Table.find(Name)) {
7250 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7251 if (ND->getDeclName() == Name)
7252 Decls.push_back(ND);
7253 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007254
Guy Benyei11169dd2012-12-18 14:30:41 +00007255 ++NumVisibleDeclContextsRead;
7256 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007257 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007258}
7259
Guy Benyei11169dd2012-12-18 14:30:41 +00007260void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7261 if (!DC->hasExternalVisibleStorage())
7262 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007263
7264 auto It = Lookups.find(DC);
7265 assert(It != Lookups.end() &&
7266 "have external visible storage but no lookup tables");
7267
Craig Topper79be4cd2013-07-05 04:33:53 +00007268 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007269
Richard Smithd88a7f12015-09-01 20:35:42 +00007270 for (DeclID ID : It->second.Table.findAll()) {
7271 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7272 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007273 }
7274
Guy Benyei11169dd2012-12-18 14:30:41 +00007275 ++NumVisibleDeclContextsRead;
7276
Craig Topper79be4cd2013-07-05 04:33:53 +00007277 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007278 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7279 }
7280 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7281}
7282
Richard Smithd88a7f12015-09-01 20:35:42 +00007283const serialization::reader::DeclContextLookupTable *
7284ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7285 auto I = Lookups.find(Primary);
7286 return I == Lookups.end() ? nullptr : &I->second;
7287}
7288
Guy Benyei11169dd2012-12-18 14:30:41 +00007289/// \brief Under non-PCH compilation the consumer receives the objc methods
7290/// before receiving the implementation, and codegen depends on this.
7291/// We simulate this by deserializing and passing to consumer the methods of the
7292/// implementation before passing the deserialized implementation decl.
7293static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7294 ASTConsumer *Consumer) {
7295 assert(ImplD && Consumer);
7296
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007297 for (auto *I : ImplD->methods())
7298 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007299
7300 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7301}
7302
Guy Benyei11169dd2012-12-18 14:30:41 +00007303void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7304 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7305 PassObjCImplDeclToConsumer(ImplD, Consumer);
7306 else
7307 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7308}
7309
7310void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7311 this->Consumer = Consumer;
7312
Richard Smith9e2341d2015-03-23 03:25:59 +00007313 if (Consumer)
7314 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007315
7316 if (DeserializationListener)
7317 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007318}
7319
7320void ASTReader::PrintStats() {
7321 std::fprintf(stderr, "*** AST File Statistics:\n");
7322
7323 unsigned NumTypesLoaded
7324 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7325 QualType());
7326 unsigned NumDeclsLoaded
7327 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007328 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007329 unsigned NumIdentifiersLoaded
7330 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7331 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007332 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007333 unsigned NumMacrosLoaded
7334 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7335 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007336 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007337 unsigned NumSelectorsLoaded
7338 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7339 SelectorsLoaded.end(),
7340 Selector());
7341
7342 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7343 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7344 NumSLocEntriesRead, TotalNumSLocEntries,
7345 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7346 if (!TypesLoaded.empty())
7347 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7348 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7349 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7350 if (!DeclsLoaded.empty())
7351 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7352 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7353 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7354 if (!IdentifiersLoaded.empty())
7355 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7356 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7357 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7358 if (!MacrosLoaded.empty())
7359 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7360 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7361 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7362 if (!SelectorsLoaded.empty())
7363 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7364 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7365 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7366 if (TotalNumStatements)
7367 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7368 NumStatementsRead, TotalNumStatements,
7369 ((float)NumStatementsRead/TotalNumStatements * 100));
7370 if (TotalNumMacros)
7371 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7372 NumMacrosRead, TotalNumMacros,
7373 ((float)NumMacrosRead/TotalNumMacros * 100));
7374 if (TotalLexicalDeclContexts)
7375 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7376 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7377 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7378 * 100));
7379 if (TotalVisibleDeclContexts)
7380 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7381 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7382 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7383 * 100));
7384 if (TotalNumMethodPoolEntries) {
7385 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7386 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7387 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7388 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007389 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007390 if (NumMethodPoolLookups) {
7391 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7392 NumMethodPoolHits, NumMethodPoolLookups,
7393 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7394 }
7395 if (NumMethodPoolTableLookups) {
7396 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7397 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7398 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7399 * 100.0));
7400 }
7401
Douglas Gregor00a50f72013-01-25 00:38:33 +00007402 if (NumIdentifierLookupHits) {
7403 std::fprintf(stderr,
7404 " %u / %u identifier table lookups succeeded (%f%%)\n",
7405 NumIdentifierLookupHits, NumIdentifierLookups,
7406 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7407 }
7408
Douglas Gregore060e572013-01-25 01:03:03 +00007409 if (GlobalIndex) {
7410 std::fprintf(stderr, "\n");
7411 GlobalIndex->printStats();
7412 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007413
Guy Benyei11169dd2012-12-18 14:30:41 +00007414 std::fprintf(stderr, "\n");
7415 dump();
7416 std::fprintf(stderr, "\n");
7417}
7418
7419template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007420LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007421dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007422 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007423 InitialCapacity> &Map) {
7424 if (Map.begin() == Map.end())
7425 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007426
Guy Benyei11169dd2012-12-18 14:30:41 +00007427 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7428 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007429 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007430 I != IEnd; ++I) {
7431 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7432 << "\n";
7433 }
7434}
7435
Yaron Kerencdae9412016-01-29 19:38:18 +00007436LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007437 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7438 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7439 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7440 dumpModuleIDMap("Global type map", GlobalTypeMap);
7441 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7442 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7443 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7444 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7445 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007446 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007447 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007448
Guy Benyei11169dd2012-12-18 14:30:41 +00007449 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007450 for (ModuleFile &M : ModuleMgr)
7451 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007452}
7453
7454/// Return the amount of memory used by memory buffers, breaking down
7455/// by heap-backed versus mmap'ed memory.
7456void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007457 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007458 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007459 size_t bytes = buf->getBufferSize();
7460 switch (buf->getBufferKind()) {
7461 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7462 sizes.malloc_bytes += bytes;
7463 break;
7464 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7465 sizes.mmap_bytes += bytes;
7466 break;
7467 }
7468 }
7469 }
7470}
7471
7472void ASTReader::InitializeSema(Sema &S) {
7473 SemaObj = &S;
7474 S.addExternalSource(this);
7475
7476 // Makes sure any declarations that were deserialized "too early"
7477 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007478 for (uint64_t ID : PreloadedDeclIDs) {
7479 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7480 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007481 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007482 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007483
Richard Smith3d8e97e2013-10-18 06:54:39 +00007484 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007485 if (!FPPragmaOptions.empty()) {
7486 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007487 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007488 }
7489
Yaxun Liu5b746652016-12-18 05:18:55 +00007490 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7491 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7492 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007493
7494 UpdateSema();
7495}
7496
7497void ASTReader::UpdateSema() {
7498 assert(SemaObj && "no Sema to update");
7499
7500 // Load the offsets of the declarations that Sema references.
7501 // They will be lazily deserialized when needed.
7502 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007503 assert(SemaDeclRefs.size() % 3 == 0);
7504 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007505 if (!SemaObj->StdNamespace)
7506 SemaObj->StdNamespace = SemaDeclRefs[I];
7507 if (!SemaObj->StdBadAlloc)
7508 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007509 if (!SemaObj->StdAlignValT)
7510 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007511 }
7512 SemaDeclRefs.clear();
7513 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007514
Nico Weber779355f2016-03-02 23:22:00 +00007515 // Update the state of pragmas. Use the same API as if we had encountered the
7516 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007517 if(OptimizeOffPragmaLocation.isValid())
7518 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007519 if (PragmaMSStructState != -1)
7520 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007521 if (PointersToMembersPragmaLocation.isValid()) {
7522 SemaObj->ActOnPragmaMSPointersToMembers(
7523 (LangOptions::PragmaMSPointersToMembersKind)
7524 PragmaMSPointersToMembersState,
7525 PointersToMembersPragmaLocation);
7526 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007527 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007528
7529 if (PragmaPackCurrentValue) {
7530 // The bottom of the stack might have a default value. It must be adjusted
7531 // to the current value to ensure that the packing state is preserved after
7532 // popping entries that were included/imported from a PCH/module.
7533 bool DropFirst = false;
7534 if (!PragmaPackStack.empty() &&
7535 PragmaPackStack.front().Location.isInvalid()) {
7536 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7537 "Expected a default alignment value");
7538 SemaObj->PackStack.Stack.emplace_back(
7539 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
7540 SemaObj->PackStack.CurrentPragmaLocation);
7541 DropFirst = true;
7542 }
7543 for (const auto &Entry :
7544 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7545 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
7546 Entry.Location);
7547 if (PragmaPackCurrentLocation.isInvalid()) {
7548 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7549 "Expected a default alignment value");
7550 // Keep the current values.
7551 } else {
7552 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7553 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7554 }
7555 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007556}
7557
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007558IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007559 // Note that we are loading an identifier.
7560 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007561
Douglas Gregor7211ac12013-01-25 23:32:03 +00007562 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007563 NumIdentifierLookups,
7564 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007565
7566 // We don't need to do identifier table lookups in C++ modules (we preload
7567 // all interesting declarations, and don't need to use the scope for name
7568 // lookups). Perform the lookup in PCH files, though, since we don't build
7569 // a complete initial identifier table if we're carrying on from a PCH.
7570 if (Context.getLangOpts().CPlusPlus) {
7571 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007572 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007573 break;
7574 } else {
7575 // If there is a global index, look there first to determine which modules
7576 // provably do not have any results for this identifier.
7577 GlobalModuleIndex::HitSet Hits;
7578 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7579 if (!loadGlobalIndex()) {
7580 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7581 HitsPtr = &Hits;
7582 }
7583 }
7584
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007585 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007586 }
7587
Guy Benyei11169dd2012-12-18 14:30:41 +00007588 IdentifierInfo *II = Visitor.getIdentifierInfo();
7589 markIdentifierUpToDate(II);
7590 return II;
7591}
7592
7593namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007594
Guy Benyei11169dd2012-12-18 14:30:41 +00007595 /// \brief An identifier-lookup iterator that enumerates all of the
7596 /// identifiers stored within a set of AST files.
7597 class ASTIdentifierIterator : public IdentifierIterator {
7598 /// \brief The AST reader whose identifiers are being enumerated.
7599 const ASTReader &Reader;
7600
7601 /// \brief The current index into the chain of AST files stored in
7602 /// the AST reader.
7603 unsigned Index;
7604
7605 /// \brief The current position within the identifier lookup table
7606 /// of the current AST file.
7607 ASTIdentifierLookupTable::key_iterator Current;
7608
7609 /// \brief The end position within the identifier lookup table of
7610 /// the current AST file.
7611 ASTIdentifierLookupTable::key_iterator End;
7612
Ben Langmuir537c5b52016-05-04 00:53:13 +00007613 /// \brief Whether to skip any modules in the ASTReader.
7614 bool SkipModules;
7615
Guy Benyei11169dd2012-12-18 14:30:41 +00007616 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007617 explicit ASTIdentifierIterator(const ASTReader &Reader,
7618 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007619
Craig Topper3e89dfe2014-03-13 02:13:41 +00007620 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007621 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007622
7623} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007624
Ben Langmuir537c5b52016-05-04 00:53:13 +00007625ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7626 bool SkipModules)
7627 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007628}
7629
7630StringRef ASTIdentifierIterator::Next() {
7631 while (Current == End) {
7632 // If we have exhausted all of our AST files, we're done.
7633 if (Index == 0)
7634 return StringRef();
7635
7636 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007637 ModuleFile &F = Reader.ModuleMgr[Index];
7638 if (SkipModules && F.isModule())
7639 continue;
7640
7641 ASTIdentifierLookupTable *IdTable =
7642 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007643 Current = IdTable->key_begin();
7644 End = IdTable->key_end();
7645 }
7646
7647 // We have any identifiers remaining in the current AST file; return
7648 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007649 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007650 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007651 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007652}
7653
Ben Langmuir537c5b52016-05-04 00:53:13 +00007654namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007655
Ben Langmuir537c5b52016-05-04 00:53:13 +00007656/// A utility for appending two IdentifierIterators.
7657class ChainedIdentifierIterator : public IdentifierIterator {
7658 std::unique_ptr<IdentifierIterator> Current;
7659 std::unique_ptr<IdentifierIterator> Queued;
7660
7661public:
7662 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7663 std::unique_ptr<IdentifierIterator> Second)
7664 : Current(std::move(First)), Queued(std::move(Second)) {}
7665
7666 StringRef Next() override {
7667 if (!Current)
7668 return StringRef();
7669
7670 StringRef result = Current->Next();
7671 if (!result.empty())
7672 return result;
7673
7674 // Try the queued iterator, which may itself be empty.
7675 Current.reset();
7676 std::swap(Current, Queued);
7677 return Next();
7678 }
7679};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007680
Ben Langmuir537c5b52016-05-04 00:53:13 +00007681} // end anonymous namespace.
7682
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007683IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007684 if (!loadGlobalIndex()) {
7685 std::unique_ptr<IdentifierIterator> ReaderIter(
7686 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7687 std::unique_ptr<IdentifierIterator> ModulesIter(
7688 GlobalIndex->createIdentifierIterator());
7689 return new ChainedIdentifierIterator(std::move(ReaderIter),
7690 std::move(ModulesIter));
7691 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007692
Guy Benyei11169dd2012-12-18 14:30:41 +00007693 return new ASTIdentifierIterator(*this);
7694}
7695
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007696namespace clang {
7697namespace serialization {
7698
Guy Benyei11169dd2012-12-18 14:30:41 +00007699 class ReadMethodPoolVisitor {
7700 ASTReader &Reader;
7701 Selector Sel;
7702 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007703 unsigned InstanceBits;
7704 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007705 bool InstanceHasMoreThanOneDecl;
7706 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007707 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7708 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007709
7710 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007711 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007712 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007713 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007714 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7715 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007716
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007717 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007718 if (!M.SelectorLookupTable)
7719 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007720
Guy Benyei11169dd2012-12-18 14:30:41 +00007721 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007722 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007723 return true;
7724
Richard Smithbdf2d932015-07-30 03:37:16 +00007725 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007726 ASTSelectorLookupTable *PoolTable
7727 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007728 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007729 if (Pos == PoolTable->end())
7730 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007731
Richard Smithbdf2d932015-07-30 03:37:16 +00007732 ++Reader.NumMethodPoolTableHits;
7733 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007734 // FIXME: Not quite happy with the statistics here. We probably should
7735 // disable this tracking when called via LoadSelector.
7736 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007737 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007738 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007739 if (Reader.DeserializationListener)
7740 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007741
Richard Smithbdf2d932015-07-30 03:37:16 +00007742 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7743 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7744 InstanceBits = Data.InstanceBits;
7745 FactoryBits = Data.FactoryBits;
7746 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7747 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007748 return true;
7749 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007750
Guy Benyei11169dd2012-12-18 14:30:41 +00007751 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007752 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7753 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007754 }
7755
7756 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007757 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007758 return FactoryMethods;
7759 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007760
7761 unsigned getInstanceBits() const { return InstanceBits; }
7762 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007763 bool instanceHasMoreThanOneDecl() const {
7764 return InstanceHasMoreThanOneDecl;
7765 }
7766 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007767 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007768
7769} // end namespace serialization
7770} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007771
7772/// \brief Add the given set of methods to the method list.
7773static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7774 ObjCMethodList &List) {
7775 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7776 S.addMethodToGlobalList(&List, Methods[I]);
7777 }
7778}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007779
Guy Benyei11169dd2012-12-18 14:30:41 +00007780void ASTReader::ReadMethodPool(Selector Sel) {
7781 // Get the selector generation and update it to the current generation.
7782 unsigned &Generation = SelectorGeneration[Sel];
7783 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007784 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007785 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007786
Guy Benyei11169dd2012-12-18 14:30:41 +00007787 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007788 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007789 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007790 ModuleMgr.visit(Visitor);
7791
Guy Benyei11169dd2012-12-18 14:30:41 +00007792 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007793 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007794 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007795
7796 ++NumMethodPoolHits;
7797
Guy Benyei11169dd2012-12-18 14:30:41 +00007798 if (!getSema())
7799 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007800
Guy Benyei11169dd2012-12-18 14:30:41 +00007801 Sema &S = *getSema();
7802 Sema::GlobalMethodPool::iterator Pos
7803 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007804
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007805 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007806 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007807 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007808 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007809
7810 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7811 // when building a module we keep every method individually and may need to
7812 // update hasMoreThanOneDecl as we add the methods.
7813 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7814 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007815}
7816
Manman Rena0f31a02016-04-29 19:04:05 +00007817void ASTReader::updateOutOfDateSelector(Selector Sel) {
7818 if (SelectorOutOfDate[Sel])
7819 ReadMethodPool(Sel);
7820}
7821
Guy Benyei11169dd2012-12-18 14:30:41 +00007822void ASTReader::ReadKnownNamespaces(
7823 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7824 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007825
Guy Benyei11169dd2012-12-18 14:30:41 +00007826 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007827 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007828 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7829 Namespaces.push_back(Namespace);
7830 }
7831}
7832
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007833void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007834 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007835 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7836 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007837 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007838 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007839 Undefined.insert(std::make_pair(D, Loc));
7840 }
7841}
Nick Lewycky8334af82013-01-26 00:35:08 +00007842
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007843void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7844 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7845 Exprs) {
7846 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7847 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7848 uint64_t Count = DelayedDeleteExprs[Idx++];
7849 for (uint64_t C = 0; C < Count; ++C) {
7850 SourceLocation DeleteLoc =
7851 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7852 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7853 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7854 }
7855 }
7856}
7857
Guy Benyei11169dd2012-12-18 14:30:41 +00007858void ASTReader::ReadTentativeDefinitions(
7859 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7860 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7861 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7862 if (Var)
7863 TentativeDefs.push_back(Var);
7864 }
7865 TentativeDefinitions.clear();
7866}
7867
7868void ASTReader::ReadUnusedFileScopedDecls(
7869 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7870 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7871 DeclaratorDecl *D
7872 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7873 if (D)
7874 Decls.push_back(D);
7875 }
7876 UnusedFileScopedDecls.clear();
7877}
7878
7879void ASTReader::ReadDelegatingConstructors(
7880 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7881 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7882 CXXConstructorDecl *D
7883 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7884 if (D)
7885 Decls.push_back(D);
7886 }
7887 DelegatingCtorDecls.clear();
7888}
7889
7890void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7891 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7892 TypedefNameDecl *D
7893 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7894 if (D)
7895 Decls.push_back(D);
7896 }
7897 ExtVectorDecls.clear();
7898}
7899
Nico Weber72889432014-09-06 01:25:55 +00007900void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7901 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7902 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7903 ++I) {
7904 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7905 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7906 if (D)
7907 Decls.insert(D);
7908 }
7909 UnusedLocalTypedefNameCandidates.clear();
7910}
7911
Guy Benyei11169dd2012-12-18 14:30:41 +00007912void ASTReader::ReadReferencedSelectors(
7913 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
7914 if (ReferencedSelectorsData.empty())
7915 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007916
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 // If there are @selector references added them to its pool. This is for
7918 // implementation of -Wselector.
7919 unsigned int DataSize = ReferencedSelectorsData.size()-1;
7920 unsigned I = 0;
7921 while (I < DataSize) {
7922 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
7923 SourceLocation SelLoc
7924 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
7925 Sels.push_back(std::make_pair(Sel, SelLoc));
7926 }
7927 ReferencedSelectorsData.clear();
7928}
7929
7930void ASTReader::ReadWeakUndeclaredIdentifiers(
7931 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
7932 if (WeakUndeclaredIdentifiers.empty())
7933 return;
7934
7935 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007936 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00007937 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007938 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00007939 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
7940 SourceLocation Loc
7941 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
7942 bool Used = WeakUndeclaredIdentifiers[I++];
7943 WeakInfo WI(AliasId, Loc);
7944 WI.setUsed(Used);
7945 WeakIDs.push_back(std::make_pair(WeakId, WI));
7946 }
7947 WeakUndeclaredIdentifiers.clear();
7948}
7949
7950void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
7951 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
7952 ExternalVTableUse VT;
7953 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
7954 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
7955 VT.DefinitionRequired = VTableUses[Idx++];
7956 VTables.push_back(VT);
7957 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007958
Guy Benyei11169dd2012-12-18 14:30:41 +00007959 VTableUses.clear();
7960}
7961
7962void ASTReader::ReadPendingInstantiations(
7963 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
7964 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
7965 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
7966 SourceLocation Loc
7967 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
7968
7969 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007970 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007971 PendingInstantiations.clear();
7972}
7973
Richard Smithe40f2ba2013-08-07 21:41:30 +00007974void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00007975 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
7976 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00007977 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
7978 /* In loop */) {
7979 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
7980
Justin Lebar28f09c52016-10-10 16:26:08 +00007981 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00007982 LT->D = GetDecl(LateParsedTemplates[Idx++]);
7983
7984 ModuleFile *F = getOwningModuleFile(LT->D);
7985 assert(F && "No module");
7986
7987 unsigned TokN = LateParsedTemplates[Idx++];
7988 LT->Toks.reserve(TokN);
7989 for (unsigned T = 0; T < TokN; ++T)
7990 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
7991
Justin Lebar28f09c52016-10-10 16:26:08 +00007992 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00007993 }
7994
7995 LateParsedTemplates.clear();
7996}
7997
Guy Benyei11169dd2012-12-18 14:30:41 +00007998void ASTReader::LoadSelector(Selector Sel) {
7999 // It would be complicated to avoid reading the methods anyway. So don't.
8000 ReadMethodPool(Sel);
8001}
8002
8003void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8004 assert(ID && "Non-zero identifier ID required");
8005 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8006 IdentifiersLoaded[ID - 1] = II;
8007 if (DeserializationListener)
8008 DeserializationListener->IdentifierRead(ID, II);
8009}
8010
8011/// \brief Set the globally-visible declarations associated with the given
8012/// identifier.
8013///
8014/// If the AST reader is currently in a state where the given declaration IDs
8015/// cannot safely be resolved, they are queued until it is safe to resolve
8016/// them.
8017///
8018/// \param II an IdentifierInfo that refers to one or more globally-visible
8019/// declarations.
8020///
8021/// \param DeclIDs the set of declaration IDs with the name @p II that are
8022/// visible at global scope.
8023///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008024/// \param Decls if non-null, this vector will be populated with the set of
8025/// deserialized declarations. These declarations will not be pushed into
8026/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008027void
8028ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8029 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008030 SmallVectorImpl<Decl *> *Decls) {
8031 if (NumCurrentElementsDeserializing && !Decls) {
8032 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008033 return;
8034 }
8035
8036 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008037 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008038 // Queue this declaration so that it will be added to the
8039 // translation unit scope and identifier's declaration chain
8040 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00008041 PreloadedDeclIDs.push_back(DeclIDs[I]);
8042 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008043 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008044
8045 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8046
8047 // If we're simply supposed to record the declarations, do so now.
8048 if (Decls) {
8049 Decls->push_back(D);
8050 continue;
8051 }
8052
8053 // Introduce this declaration into the translation-unit scope
8054 // and add it to the declaration chain for this identifier, so
8055 // that (unqualified) name lookup will find it.
8056 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008057 }
8058}
8059
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008060IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008061 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008062 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008063
8064 if (IdentifiersLoaded.empty()) {
8065 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008066 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008067 }
8068
8069 ID -= 1;
8070 if (!IdentifiersLoaded[ID]) {
8071 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8072 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8073 ModuleFile *M = I->second;
8074 unsigned Index = ID - M->BaseIdentifierID;
8075 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8076
8077 // All of the strings in the AST file are preceded by a 16-bit length.
8078 // Extract that 16-bit length to avoid having to execute strlen().
8079 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8080 // unsigned integers. This is important to avoid integer overflow when
8081 // we cast them to 'unsigned'.
8082 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8083 unsigned StrLen = (((unsigned) StrLenPtr[0])
8084 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008085 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8086 IdentifiersLoaded[ID] = &II;
8087 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008088 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008089 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008090 }
8091
8092 return IdentifiersLoaded[ID];
8093}
8094
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008095IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8096 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008097}
8098
8099IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8100 if (LocalID < NUM_PREDEF_IDENT_IDS)
8101 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008102
Richard Smith37a93df2017-02-18 00:32:02 +00008103 if (!M.ModuleOffsetMap.empty())
8104 ReadModuleOffsetMap(M);
8105
Guy Benyei11169dd2012-12-18 14:30:41 +00008106 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8107 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008108 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008109 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008110
Guy Benyei11169dd2012-12-18 14:30:41 +00008111 return LocalID + I->second;
8112}
8113
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008114MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008115 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008116 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008117
8118 if (MacrosLoaded.empty()) {
8119 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008120 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008121 }
8122
8123 ID -= NUM_PREDEF_MACRO_IDS;
8124 if (!MacrosLoaded[ID]) {
8125 GlobalMacroMapType::iterator I
8126 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8127 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8128 ModuleFile *M = I->second;
8129 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008130 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008131
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008132 if (DeserializationListener)
8133 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8134 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008135 }
8136
8137 return MacrosLoaded[ID];
8138}
8139
8140MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8141 if (LocalID < NUM_PREDEF_MACRO_IDS)
8142 return LocalID;
8143
Richard Smith37a93df2017-02-18 00:32:02 +00008144 if (!M.ModuleOffsetMap.empty())
8145 ReadModuleOffsetMap(M);
8146
Guy Benyei11169dd2012-12-18 14:30:41 +00008147 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8148 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8149 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8150
8151 return LocalID + I->second;
8152}
8153
8154serialization::SubmoduleID
8155ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8156 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8157 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008158
Richard Smith37a93df2017-02-18 00:32:02 +00008159 if (!M.ModuleOffsetMap.empty())
8160 ReadModuleOffsetMap(M);
8161
Guy Benyei11169dd2012-12-18 14:30:41 +00008162 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8163 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008164 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008165 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008166
Guy Benyei11169dd2012-12-18 14:30:41 +00008167 return LocalID + I->second;
8168}
8169
8170Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8171 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8172 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008173 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008174 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008175
Guy Benyei11169dd2012-12-18 14:30:41 +00008176 if (GlobalID > SubmodulesLoaded.size()) {
8177 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008178 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008179 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008180
Guy Benyei11169dd2012-12-18 14:30:41 +00008181 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8182}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008183
8184Module *ASTReader::getModule(unsigned ID) {
8185 return getSubmodule(ID);
8186}
8187
Richard Smithd88a7f12015-09-01 20:35:42 +00008188ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8189 if (ID & 1) {
8190 // It's a module, look it up by submodule ID.
8191 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8192 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8193 } else {
8194 // It's a prefix (preamble, PCH, ...). Look it up by index.
8195 unsigned IndexFromEnd = ID >> 1;
8196 assert(IndexFromEnd && "got reference to unknown module file");
8197 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8198 }
8199}
8200
8201unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8202 if (!F)
8203 return 1;
8204
8205 // For a file representing a module, use the submodule ID of the top-level
8206 // module as the file ID. For any other kind of file, the number of such
8207 // files loaded beforehand will be the same on reload.
8208 // FIXME: Is this true even if we have an explicit module file and a PCH?
8209 if (F->isModule())
8210 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8211
8212 auto PCHModules = getModuleManager().pch_modules();
8213 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8214 assert(I != PCHModules.end() && "emitting reference to unknown file");
8215 return (I - PCHModules.end()) << 1;
8216}
8217
Adrian Prantl15bcf702015-06-30 17:39:43 +00008218llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8219ASTReader::getSourceDescriptor(unsigned ID) {
8220 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008221 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008222
8223 // If there is only a single PCH, return it instead.
8224 // Chained PCH are not suported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008225 const auto &PCHChain = ModuleMgr.pch_modules();
8226 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008227 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008228 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008229 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8230 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8231 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008232 }
8233 return None;
8234}
8235
David Blaikie1ac9c982017-04-11 21:13:37 +00008236ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
David Blaikiee6b7c282017-04-11 20:46:34 +00008237 auto I = BodySource.find(FD);
8238 if (I == BodySource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008239 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008240 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008241}
8242
Guy Benyei11169dd2012-12-18 14:30:41 +00008243Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8244 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8245}
8246
8247Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8248 if (ID == 0)
8249 return Selector();
8250
8251 if (ID > SelectorsLoaded.size()) {
8252 Error("selector ID out of range in AST file");
8253 return Selector();
8254 }
8255
Craig Toppera13603a2014-05-22 05:54:18 +00008256 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008257 // Load this selector from the selector table.
8258 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8259 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8260 ModuleFile &M = *I->second;
8261 ASTSelectorLookupTrait Trait(*this, M);
8262 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8263 SelectorsLoaded[ID - 1] =
8264 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8265 if (DeserializationListener)
8266 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8267 }
8268
8269 return SelectorsLoaded[ID - 1];
8270}
8271
8272Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8273 return DecodeSelector(ID);
8274}
8275
8276uint32_t ASTReader::GetNumExternalSelectors() {
8277 // ID 0 (the null selector) is considered an external selector.
8278 return getTotalNumSelectors() + 1;
8279}
8280
8281serialization::SelectorID
8282ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8283 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8284 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008285
Richard Smith37a93df2017-02-18 00:32:02 +00008286 if (!M.ModuleOffsetMap.empty())
8287 ReadModuleOffsetMap(M);
8288
Guy Benyei11169dd2012-12-18 14:30:41 +00008289 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8290 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008291 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008292 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008293
Guy Benyei11169dd2012-12-18 14:30:41 +00008294 return LocalID + I->second;
8295}
8296
8297DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008298ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008299 const RecordData &Record, unsigned &Idx) {
8300 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8301 switch (Kind) {
8302 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008303 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008304
8305 case DeclarationName::ObjCZeroArgSelector:
8306 case DeclarationName::ObjCOneArgSelector:
8307 case DeclarationName::ObjCMultiArgSelector:
8308 return DeclarationName(ReadSelector(F, Record, Idx));
8309
8310 case DeclarationName::CXXConstructorName:
8311 return Context.DeclarationNames.getCXXConstructorName(
8312 Context.getCanonicalType(readType(F, Record, Idx)));
8313
8314 case DeclarationName::CXXDestructorName:
8315 return Context.DeclarationNames.getCXXDestructorName(
8316 Context.getCanonicalType(readType(F, Record, Idx)));
8317
Richard Smith35845152017-02-07 01:37:30 +00008318 case DeclarationName::CXXDeductionGuideName:
8319 return Context.DeclarationNames.getCXXDeductionGuideName(
8320 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8321
Guy Benyei11169dd2012-12-18 14:30:41 +00008322 case DeclarationName::CXXConversionFunctionName:
8323 return Context.DeclarationNames.getCXXConversionFunctionName(
8324 Context.getCanonicalType(readType(F, Record, Idx)));
8325
8326 case DeclarationName::CXXOperatorName:
8327 return Context.DeclarationNames.getCXXOperatorName(
8328 (OverloadedOperatorKind)Record[Idx++]);
8329
8330 case DeclarationName::CXXLiteralOperatorName:
8331 return Context.DeclarationNames.getCXXLiteralOperatorName(
8332 GetIdentifierInfo(F, Record, Idx));
8333
8334 case DeclarationName::CXXUsingDirective:
8335 return DeclarationName::getUsingDirectiveName();
8336 }
8337
8338 llvm_unreachable("Invalid NameKind!");
8339}
8340
8341void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8342 DeclarationNameLoc &DNLoc,
8343 DeclarationName Name,
8344 const RecordData &Record, unsigned &Idx) {
8345 switch (Name.getNameKind()) {
8346 case DeclarationName::CXXConstructorName:
8347 case DeclarationName::CXXDestructorName:
8348 case DeclarationName::CXXConversionFunctionName:
8349 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8350 break;
8351
8352 case DeclarationName::CXXOperatorName:
8353 DNLoc.CXXOperatorName.BeginOpNameLoc
8354 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8355 DNLoc.CXXOperatorName.EndOpNameLoc
8356 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8357 break;
8358
8359 case DeclarationName::CXXLiteralOperatorName:
8360 DNLoc.CXXLiteralOperatorName.OpNameLoc
8361 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8362 break;
8363
8364 case DeclarationName::Identifier:
8365 case DeclarationName::ObjCZeroArgSelector:
8366 case DeclarationName::ObjCOneArgSelector:
8367 case DeclarationName::ObjCMultiArgSelector:
8368 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008369 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008370 break;
8371 }
8372}
8373
8374void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8375 DeclarationNameInfo &NameInfo,
8376 const RecordData &Record, unsigned &Idx) {
8377 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8378 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8379 DeclarationNameLoc DNLoc;
8380 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8381 NameInfo.setInfo(DNLoc);
8382}
8383
8384void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8385 const RecordData &Record, unsigned &Idx) {
8386 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8387 unsigned NumTPLists = Record[Idx++];
8388 Info.NumTemplParamLists = NumTPLists;
8389 if (NumTPLists) {
8390 Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008391 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008392 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8393 }
8394}
8395
8396TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008397ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008398 unsigned &Idx) {
8399 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8400 switch (Kind) {
8401 case TemplateName::Template:
8402 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8403
8404 case TemplateName::OverloadedTemplate: {
8405 unsigned size = Record[Idx++];
8406 UnresolvedSet<8> Decls;
8407 while (size--)
8408 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8409
8410 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8411 }
8412
8413 case TemplateName::QualifiedTemplate: {
8414 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8415 bool hasTemplKeyword = Record[Idx++];
8416 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8417 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8418 }
8419
8420 case TemplateName::DependentTemplate: {
8421 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8422 if (Record[Idx++]) // isIdentifier
8423 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008424 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008425 Idx));
8426 return Context.getDependentTemplateName(NNS,
8427 (OverloadedOperatorKind)Record[Idx++]);
8428 }
8429
8430 case TemplateName::SubstTemplateTemplateParm: {
8431 TemplateTemplateParmDecl *param
8432 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8433 if (!param) return TemplateName();
8434 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8435 return Context.getSubstTemplateTemplateParm(param, replacement);
8436 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008437
Guy Benyei11169dd2012-12-18 14:30:41 +00008438 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008439 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008440 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8441 if (!Param)
8442 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008443
Guy Benyei11169dd2012-12-18 14:30:41 +00008444 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8445 if (ArgPack.getKind() != TemplateArgument::Pack)
8446 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008447
Guy Benyei11169dd2012-12-18 14:30:41 +00008448 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8449 }
8450 }
8451
8452 llvm_unreachable("Unhandled template name kind!");
8453}
8454
Richard Smith2bb3c342015-08-09 01:05:31 +00008455TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8456 const RecordData &Record,
8457 unsigned &Idx,
8458 bool Canonicalize) {
8459 if (Canonicalize) {
8460 // The caller wants a canonical template argument. Sometimes the AST only
8461 // wants template arguments in canonical form (particularly as the template
8462 // argument lists of template specializations) so ensure we preserve that
8463 // canonical form across serialization.
8464 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8465 return Context.getCanonicalTemplateArgument(Arg);
8466 }
8467
Guy Benyei11169dd2012-12-18 14:30:41 +00008468 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8469 switch (Kind) {
8470 case TemplateArgument::Null:
8471 return TemplateArgument();
8472 case TemplateArgument::Type:
8473 return TemplateArgument(readType(F, Record, Idx));
8474 case TemplateArgument::Declaration: {
8475 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008476 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008477 }
8478 case TemplateArgument::NullPtr:
8479 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8480 case TemplateArgument::Integral: {
8481 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8482 QualType T = readType(F, Record, Idx);
8483 return TemplateArgument(Context, Value, T);
8484 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008485 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008486 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8487 case TemplateArgument::TemplateExpansion: {
8488 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008489 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008490 if (unsigned NumExpansions = Record[Idx++])
8491 NumTemplateExpansions = NumExpansions - 1;
8492 return TemplateArgument(Name, NumTemplateExpansions);
8493 }
8494 case TemplateArgument::Expression:
8495 return TemplateArgument(ReadExpr(F));
8496 case TemplateArgument::Pack: {
8497 unsigned NumArgs = Record[Idx++];
8498 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8499 for (unsigned I = 0; I != NumArgs; ++I)
8500 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008501 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008502 }
8503 }
8504
8505 llvm_unreachable("Unhandled template argument kind!");
8506}
8507
8508TemplateParameterList *
8509ASTReader::ReadTemplateParameterList(ModuleFile &F,
8510 const RecordData &Record, unsigned &Idx) {
8511 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8512 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8513 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8514
8515 unsigned NumParams = Record[Idx++];
8516 SmallVector<NamedDecl *, 16> Params;
8517 Params.reserve(NumParams);
8518 while (NumParams--)
8519 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8520
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008521 // TODO: Concepts
Guy Benyei11169dd2012-12-18 14:30:41 +00008522 TemplateParameterList* TemplateParams =
8523 TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008524 Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008525 return TemplateParams;
8526}
8527
8528void
8529ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008530ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008531 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008532 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008533 unsigned NumTemplateArgs = Record[Idx++];
8534 TemplArgs.reserve(NumTemplateArgs);
8535 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008536 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008537}
8538
8539/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008540void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008541 const RecordData &Record, unsigned &Idx) {
8542 unsigned NumDecls = Record[Idx++];
8543 Set.reserve(Context, NumDecls);
8544 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008545 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008546 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smitha4ba74c2013-08-30 04:46:40 +00008547 Set.addLazyDecl(Context, ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008548 }
8549}
8550
8551CXXBaseSpecifier
8552ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8553 const RecordData &Record, unsigned &Idx) {
8554 bool isVirtual = static_cast<bool>(Record[Idx++]);
8555 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8556 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8557 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8558 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8559 SourceRange Range = ReadSourceRange(F, Record, Idx);
8560 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008561 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008562 EllipsisLoc);
8563 Result.setInheritConstructors(inheritConstructors);
8564 return Result;
8565}
8566
Richard Smithc2bb8182015-03-24 06:36:48 +00008567CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008568ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8569 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008570 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008571 assert(NumInitializers && "wrote ctor initializers but have no inits");
8572 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8573 for (unsigned i = 0; i != NumInitializers; ++i) {
8574 TypeSourceInfo *TInfo = nullptr;
8575 bool IsBaseVirtual = false;
8576 FieldDecl *Member = nullptr;
8577 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008578
Richard Smithc2bb8182015-03-24 06:36:48 +00008579 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8580 switch (Type) {
8581 case CTOR_INITIALIZER_BASE:
8582 TInfo = GetTypeSourceInfo(F, Record, Idx);
8583 IsBaseVirtual = Record[Idx++];
8584 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008585
Richard Smithc2bb8182015-03-24 06:36:48 +00008586 case CTOR_INITIALIZER_DELEGATING:
8587 TInfo = GetTypeSourceInfo(F, Record, Idx);
8588 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008589
Richard Smithc2bb8182015-03-24 06:36:48 +00008590 case CTOR_INITIALIZER_MEMBER:
8591 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8592 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008593
Richard Smithc2bb8182015-03-24 06:36:48 +00008594 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8595 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8596 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008597 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008598
8599 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8600 Expr *Init = ReadExpr(F);
8601 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8602 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008603
8604 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008605 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008606 BOMInit = new (Context)
8607 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8608 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008609 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008610 BOMInit = new (Context)
8611 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008612 else if (Member)
8613 BOMInit = new (Context)
8614 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8615 Init, RParenLoc);
8616 else
8617 BOMInit = new (Context)
8618 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8619 LParenLoc, Init, RParenLoc);
8620
Richard Smith418ed822016-12-14 19:45:03 +00008621 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008622 unsigned SourceOrder = Record[Idx++];
8623 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008624 }
8625
Richard Smithc2bb8182015-03-24 06:36:48 +00008626 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008627 }
8628
Richard Smithc2bb8182015-03-24 06:36:48 +00008629 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008630}
8631
8632NestedNameSpecifier *
8633ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8634 const RecordData &Record, unsigned &Idx) {
8635 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008636 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008637 for (unsigned I = 0; I != N; ++I) {
8638 NestedNameSpecifier::SpecifierKind Kind
8639 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8640 switch (Kind) {
8641 case NestedNameSpecifier::Identifier: {
8642 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8643 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8644 break;
8645 }
8646
8647 case NestedNameSpecifier::Namespace: {
8648 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8649 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8650 break;
8651 }
8652
8653 case NestedNameSpecifier::NamespaceAlias: {
8654 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8655 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8656 break;
8657 }
8658
8659 case NestedNameSpecifier::TypeSpec:
8660 case NestedNameSpecifier::TypeSpecWithTemplate: {
8661 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8662 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008663 return nullptr;
8664
Guy Benyei11169dd2012-12-18 14:30:41 +00008665 bool Template = Record[Idx++];
8666 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8667 break;
8668 }
8669
8670 case NestedNameSpecifier::Global: {
8671 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8672 // No associated value, and there can't be a prefix.
8673 break;
8674 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008675
8676 case NestedNameSpecifier::Super: {
8677 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8678 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8679 break;
8680 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008681 }
8682 Prev = NNS;
8683 }
8684 return NNS;
8685}
8686
8687NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008688ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008689 unsigned &Idx) {
8690 unsigned N = Record[Idx++];
8691 NestedNameSpecifierLocBuilder Builder;
8692 for (unsigned I = 0; I != N; ++I) {
8693 NestedNameSpecifier::SpecifierKind Kind
8694 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8695 switch (Kind) {
8696 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008697 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008698 SourceRange Range = ReadSourceRange(F, Record, Idx);
8699 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8700 break;
8701 }
8702
8703 case NestedNameSpecifier::Namespace: {
8704 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8705 SourceRange Range = ReadSourceRange(F, Record, Idx);
8706 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8707 break;
8708 }
8709
8710 case NestedNameSpecifier::NamespaceAlias: {
8711 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8712 SourceRange Range = ReadSourceRange(F, Record, Idx);
8713 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8714 break;
8715 }
8716
8717 case NestedNameSpecifier::TypeSpec:
8718 case NestedNameSpecifier::TypeSpecWithTemplate: {
8719 bool Template = Record[Idx++];
8720 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8721 if (!T)
8722 return NestedNameSpecifierLoc();
8723 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8724
8725 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008726 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008727 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8728 T->getTypeLoc(), ColonColonLoc);
8729 break;
8730 }
8731
8732 case NestedNameSpecifier::Global: {
8733 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8734 Builder.MakeGlobal(Context, ColonColonLoc);
8735 break;
8736 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008737
8738 case NestedNameSpecifier::Super: {
8739 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8740 SourceRange Range = ReadSourceRange(F, Record, Idx);
8741 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8742 break;
8743 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008744 }
8745 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008746
Guy Benyei11169dd2012-12-18 14:30:41 +00008747 return Builder.getWithLocInContext(Context);
8748}
8749
8750SourceRange
8751ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8752 unsigned &Idx) {
8753 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8754 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8755 return SourceRange(beg, end);
8756}
8757
8758/// \brief Read an integral value
8759llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8760 unsigned BitWidth = Record[Idx++];
8761 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8762 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8763 Idx += NumWords;
8764 return Result;
8765}
8766
8767/// \brief Read a signed integral value
8768llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8769 bool isUnsigned = Record[Idx++];
8770 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8771}
8772
8773/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008774llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8775 const llvm::fltSemantics &Sem,
8776 unsigned &Idx) {
8777 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008778}
8779
8780// \brief Read a string
8781std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8782 unsigned Len = Record[Idx++];
8783 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8784 Idx += Len;
8785 return Result;
8786}
8787
Richard Smith7ed1bc92014-12-05 22:42:13 +00008788std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8789 unsigned &Idx) {
8790 std::string Filename = ReadString(Record, Idx);
8791 ResolveImportedPath(F, Filename);
8792 return Filename;
8793}
8794
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008795VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008796 unsigned &Idx) {
8797 unsigned Major = Record[Idx++];
8798 unsigned Minor = Record[Idx++];
8799 unsigned Subminor = Record[Idx++];
8800 if (Minor == 0)
8801 return VersionTuple(Major);
8802 if (Subminor == 0)
8803 return VersionTuple(Major, Minor - 1);
8804 return VersionTuple(Major, Minor - 1, Subminor - 1);
8805}
8806
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008807CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008808 const RecordData &Record,
8809 unsigned &Idx) {
8810 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
8811 return CXXTemporary::Create(Context, Decl);
8812}
8813
Richard Smith37a93df2017-02-18 00:32:02 +00008814DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008815 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008816}
8817
Richard Smith37a93df2017-02-18 00:32:02 +00008818DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008819 return Diags.Report(Loc, DiagID);
8820}
8821
8822/// \brief Retrieve the identifier table associated with the
8823/// preprocessor.
8824IdentifierTable &ASTReader::getIdentifierTable() {
8825 return PP.getIdentifierTable();
8826}
8827
8828/// \brief Record that the given ID maps to the given switch-case
8829/// statement.
8830void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008831 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008832 "Already have a SwitchCase with this ID");
8833 (*CurrSwitchCaseStmts)[ID] = SC;
8834}
8835
8836/// \brief Retrieve the switch-case statement with the given ID.
8837SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008838 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008839 return (*CurrSwitchCaseStmts)[ID];
8840}
8841
8842void ASTReader::ClearSwitchCaseIDs() {
8843 CurrSwitchCaseStmts->clear();
8844}
8845
8846void ASTReader::ReadComments() {
8847 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008848 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008849 serialization::ModuleFile *> >::iterator
8850 I = CommentsCursors.begin(),
8851 E = CommentsCursors.end();
8852 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008853 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008854 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008855 serialization::ModuleFile &F = *I->second;
8856 SavedStreamPosition SavedPosition(Cursor);
8857
8858 RecordData Record;
8859 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008860 llvm::BitstreamEntry Entry =
8861 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008862
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008863 switch (Entry.Kind) {
8864 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8865 case llvm::BitstreamEntry::Error:
8866 Error("malformed block record in AST file");
8867 return;
8868 case llvm::BitstreamEntry::EndBlock:
8869 goto NextCursor;
8870 case llvm::BitstreamEntry::Record:
8871 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008872 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008873 }
8874
8875 // Read a record.
8876 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008877 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008878 case COMMENTS_RAW_COMMENT: {
8879 unsigned Idx = 0;
8880 SourceRange SR = ReadSourceRange(F, Record, Idx);
8881 RawComment::CommentKind Kind =
8882 (RawComment::CommentKind) Record[Idx++];
8883 bool IsTrailingComment = Record[Idx++];
8884 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008885 Comments.push_back(new (Context) RawComment(
8886 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8887 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008888 break;
8889 }
8890 }
8891 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008892 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008893 // De-serialized SourceLocations get negative FileIDs for other modules,
8894 // potentially invalidating the original order. Sort it again.
8895 std::sort(Comments.begin(), Comments.end(),
8896 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008897 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008898 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008899}
8900
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008901void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8902 bool IncludeSystem, bool Complain,
8903 llvm::function_ref<void(const serialization::InputFile &IF,
8904 bool isSystem)> Visitor) {
8905 unsigned NumUserInputs = MF.NumUserInputFiles;
8906 unsigned NumInputs = MF.InputFilesLoaded.size();
8907 assert(NumUserInputs <= NumInputs);
8908 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
8909 for (unsigned I = 0; I < N; ++I) {
8910 bool IsSystem = I >= NumUserInputs;
8911 InputFile IF = getInputFile(MF, I+1, Complain);
8912 Visitor(IF, IsSystem);
8913 }
8914}
8915
Richard Smithcd45dbc2014-04-19 03:48:30 +00008916std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
8917 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00008918 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00008919 return M->getFullModuleName();
8920
8921 // Otherwise, use the name of the top-level module the decl is within.
8922 if (ModuleFile *M = getOwningModuleFile(D))
8923 return M->ModuleName;
8924
8925 // Not from a module.
8926 return "";
8927}
8928
Guy Benyei11169dd2012-12-18 14:30:41 +00008929void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00008930 while (!PendingIdentifierInfos.empty() ||
8931 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00008932 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00008933 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008934 // If any identifiers with corresponding top-level declarations have
8935 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00008936 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
8937 TopLevelDeclsMap;
8938 TopLevelDeclsMap TopLevelDecls;
8939
Guy Benyei11169dd2012-12-18 14:30:41 +00008940 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008941 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008942 SmallVector<uint32_t, 4> DeclIDs =
8943 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00008944 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00008945
8946 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008947 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00008948
Richard Smith851072e2014-05-19 20:59:20 +00008949 // For each decl chain that we wanted to complete while deserializing, mark
8950 // it as "still needs to be completed".
8951 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
8952 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
8953 }
8954 PendingIncompleteDeclChains.clear();
8955
Guy Benyei11169dd2012-12-18 14:30:41 +00008956 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00008957 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00008958 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00008959 PendingDeclChains.clear();
8960
Douglas Gregor6168bd22013-02-18 15:53:43 +00008961 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00008962 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
8963 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00008964 IdentifierInfo *II = TLD->first;
8965 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00008966 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00008967 }
8968 }
8969
Guy Benyei11169dd2012-12-18 14:30:41 +00008970 // Load any pending macro definitions.
8971 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008972 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
8973 SmallVector<PendingMacroInfo, 2> GlobalIDs;
8974 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
8975 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008976 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00008977 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008978 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008979 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008980 resolvePendingMacro(II, Info);
8981 }
8982 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00008983 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008984 ++IDIdx) {
8985 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00008986 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008987 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00008988 }
8989 }
8990 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00008991
8992 // Wire up the DeclContexts for Decls that we delayed setting until
8993 // recursive loading is completed.
8994 while (!PendingDeclContextInfos.empty()) {
8995 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
8996 PendingDeclContextInfos.pop_front();
8997 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
8998 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
8999 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9000 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009001
Richard Smithd1c46742014-04-30 02:24:17 +00009002 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009003 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009004 auto Update = PendingUpdateRecords.pop_back_val();
9005 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009006 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009007 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009008 }
Richard Smith8a639892015-01-24 01:07:20 +00009009
9010 // At this point, all update records for loaded decls are in place, so any
9011 // fake class definitions should have become real.
9012 assert(PendingFakeDefinitionData.empty() &&
9013 "faked up a class definition but never saw the real one");
9014
Guy Benyei11169dd2012-12-18 14:30:41 +00009015 // If we deserialized any C++ or Objective-C class definitions, any
9016 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009017 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009018 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00009019 for (Decl *D : PendingDefinitions) {
9020 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00009021 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009022 // Make sure that the TagType points at the definition.
9023 const_cast<TagType*>(TagT)->decl = TD;
9024 }
Richard Smith8ce51082015-03-11 01:44:51 +00009025
Craig Topperc6914d02014-08-25 04:15:02 +00009026 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009027 for (auto *R = getMostRecentExistingDecl(RD); R;
9028 R = R->getPreviousDecl()) {
9029 assert((R == D) ==
9030 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009031 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009032 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009033 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009034 }
9035
9036 continue;
9037 }
Richard Smith8ce51082015-03-11 01:44:51 +00009038
Craig Topperc6914d02014-08-25 04:15:02 +00009039 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009040 // Make sure that the ObjCInterfaceType points at the definition.
9041 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9042 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009043
9044 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9045 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9046
Guy Benyei11169dd2012-12-18 14:30:41 +00009047 continue;
9048 }
Richard Smith8ce51082015-03-11 01:44:51 +00009049
Craig Topperc6914d02014-08-25 04:15:02 +00009050 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009051 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9052 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9053
Guy Benyei11169dd2012-12-18 14:30:41 +00009054 continue;
9055 }
Richard Smith8ce51082015-03-11 01:44:51 +00009056
Craig Topperc6914d02014-08-25 04:15:02 +00009057 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009058 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9059 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009060 }
9061 PendingDefinitions.clear();
9062
9063 // Load the bodies of any functions or methods we've encountered. We do
9064 // this now (delayed) so that we can be sure that the declaration chains
Richard Smithb9fa9962015-08-21 03:04:33 +00009065 // have been fully wired up (hasBody relies on this).
9066 // FIXME: We shouldn't require complete redeclaration chains here.
Guy Benyei11169dd2012-12-18 14:30:41 +00009067 for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
9068 PBEnd = PendingBodies.end();
9069 PB != PBEnd; ++PB) {
9070 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
9071 // FIXME: Check for =delete/=default?
9072 // FIXME: Complain about ODR violations here?
Richard Smith6561f922016-09-12 21:06:40 +00009073 const FunctionDecl *Defn = nullptr;
David Blaikiee6b7c282017-04-11 20:46:34 +00009074 if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009075 FD->setLazyBody(PB->second);
David Blaikiee6b7c282017-04-11 20:46:34 +00009076 } else
Richard Smith6561f922016-09-12 21:06:40 +00009077 mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
Guy Benyei11169dd2012-12-18 14:30:41 +00009078 continue;
9079 }
9080
9081 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
9082 if (!getContext().getLangOpts().Modules || !MD->hasBody())
9083 MD->setLazyBody(PB->second);
9084 }
9085 PendingBodies.clear();
Richard Smith42413142015-05-15 20:05:43 +00009086
9087 // Do some cleanup.
9088 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9089 getContext().deduplicateMergedDefinitonsFor(ND);
9090 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009091}
9092
9093void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00009094 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9095 return;
9096
Richard Smitha0ce9c42014-07-29 23:23:27 +00009097 // Trigger the import of the full definition of each class that had any
9098 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009099 // These updates may in turn find and diagnose some ODR failures, so take
9100 // ownership of the set first.
9101 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9102 PendingOdrMergeFailures.clear();
9103 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009104 Merge.first->buildLookup();
9105 Merge.first->decls_begin();
9106 Merge.first->bases_begin();
9107 Merge.first->vbases_begin();
9108 for (auto *RD : Merge.second) {
9109 RD->decls_begin();
9110 RD->bases_begin();
9111 RD->vbases_begin();
9112 }
9113 }
9114
9115 // For each declaration from a merged context, check that the canonical
9116 // definition of that context also contains a declaration of the same
9117 // entity.
9118 //
9119 // Caution: this loop does things that might invalidate iterators into
9120 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9121 while (!PendingOdrMergeChecks.empty()) {
9122 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9123
9124 // FIXME: Skip over implicit declarations for now. This matters for things
9125 // like implicitly-declared special member functions. This isn't entirely
9126 // correct; we can end up with multiple unmerged declarations of the same
9127 // implicit entity.
9128 if (D->isImplicit())
9129 continue;
9130
9131 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009132
9133 bool Found = false;
9134 const Decl *DCanon = D->getCanonicalDecl();
9135
Richard Smith01bdb7a2014-08-28 05:44:07 +00009136 for (auto RI : D->redecls()) {
9137 if (RI->getLexicalDeclContext() == CanonDef) {
9138 Found = true;
9139 break;
9140 }
9141 }
9142 if (Found)
9143 continue;
9144
Richard Smith0f4e2c42015-08-06 04:23:48 +00009145 // Quick check failed, time to do the slow thing. Note, we can't just
9146 // look up the name of D in CanonDef here, because the member that is
9147 // in CanonDef might not be found by name lookup (it might have been
9148 // replaced by a more recent declaration in the lookup table), and we
9149 // can't necessarily find it in the redeclaration chain because it might
9150 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009151 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009152 for (auto *CanonMember : CanonDef->decls()) {
9153 if (CanonMember->getCanonicalDecl() == DCanon) {
9154 // This can happen if the declaration is merely mergeable and not
9155 // actually redeclarable (we looked for redeclarations earlier).
9156 //
9157 // FIXME: We should be able to detect this more efficiently, without
9158 // pulling in all of the members of CanonDef.
9159 Found = true;
9160 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009161 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009162 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9163 if (ND->getDeclName() == D->getDeclName())
9164 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009165 }
9166
9167 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009168 // The AST doesn't like TagDecls becoming invalid after they've been
9169 // completed. We only really need to mark FieldDecls as invalid here.
9170 if (!isa<TagDecl>(D))
9171 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009172
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009173 // Ensure we don't accidentally recursively enter deserialization while
9174 // we're producing our diagnostic.
9175 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009176
9177 std::string CanonDefModule =
9178 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9179 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9180 << D << getOwningModuleNameForDiagnostic(D)
9181 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9182
9183 if (Candidates.empty())
9184 Diag(cast<Decl>(CanonDef)->getLocation(),
9185 diag::note_module_odr_violation_no_possible_decls) << D;
9186 else {
9187 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9188 Diag(Candidates[I]->getLocation(),
9189 diag::note_module_odr_violation_possible_decl)
9190 << Candidates[I];
9191 }
9192
9193 DiagnosedOdrMergeFailures.insert(CanonDef);
9194 }
9195 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009196
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009197 if (OdrMergeFailures.empty())
9198 return;
9199
9200 // Ensure we don't accidentally recursively enter deserialization while
9201 // we're producing our diagnostics.
9202 Deserializing RecursionGuard(this);
9203
Richard Smithcd45dbc2014-04-19 03:48:30 +00009204 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009205 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009206 // If we've already pointed out a specific problem with this class, don't
9207 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009208 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009209 continue;
9210
9211 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009212 CXXRecordDecl *FirstRecord = Merge.first;
9213 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
9214 for (CXXRecordDecl *SecondRecord : Merge.second) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00009215 // Multiple different declarations got merged together; tell the user
9216 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009217 if (FirstRecord == SecondRecord)
9218 continue;
9219
9220 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
9221 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
9222 DeclHashes FirstHashes;
9223 DeclHashes SecondHashes;
9224 ODRHash Hash;
9225
9226 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9227 CXXRecordDecl *Record) {
9228 for (auto *D : Record->decls()) {
9229 // Due to decl merging, the first CXXRecordDecl is the parent of
9230 // Decls in both records.
9231 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9232 continue;
9233 Hash.clear();
9234 Hash.AddSubDecl(D);
9235 Hashes.emplace_back(D, Hash.CalculateHash());
9236 }
9237 };
9238 PopulateHashes(FirstHashes, FirstRecord);
9239 PopulateHashes(SecondHashes, SecondRecord);
9240
9241 // Used with err_module_odr_violation_mismatch_decl and
9242 // note_module_odr_violation_mismatch_decl
9243 enum {
9244 EndOfClass,
9245 PublicSpecifer,
9246 PrivateSpecifer,
9247 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009248 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009249 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009250 CXXMethod,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009251 Other
9252 } FirstDiffType = Other,
9253 SecondDiffType = Other;
9254
9255 auto DifferenceSelector = [](Decl *D) {
9256 assert(D && "valid Decl required");
9257 switch (D->getKind()) {
9258 default:
9259 return Other;
9260 case Decl::AccessSpec:
9261 switch (D->getAccess()) {
9262 case AS_public:
9263 return PublicSpecifer;
9264 case AS_private:
9265 return PrivateSpecifer;
9266 case AS_protected:
9267 return ProtectedSpecifer;
9268 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009269 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009270 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009271 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009272 case Decl::StaticAssert:
9273 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009274 case Decl::Field:
9275 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009276 case Decl::CXXMethod:
9277 return CXXMethod;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009278 }
9279 };
9280
9281 Decl *FirstDecl = nullptr;
9282 Decl *SecondDecl = nullptr;
9283 auto FirstIt = FirstHashes.begin();
9284 auto SecondIt = SecondHashes.begin();
9285
9286 // If there is a diagnoseable difference, FirstDiffType and
9287 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9288 // filled in if not EndOfClass.
9289 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009290 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9291 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009292 ++FirstIt;
9293 ++SecondIt;
9294 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009295 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009296
Richard Trieue7f7ed22017-02-22 01:11:25 +00009297 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9298 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9299
9300 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9301 SecondDiffType =
9302 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9303
9304 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009305 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009306
9307 if (FirstDiffType == Other || SecondDiffType == Other) {
9308 // Reaching this point means an unexpected Decl was encountered
9309 // or no difference was detected. This causes a generic error
9310 // message to be emitted.
9311 Diag(FirstRecord->getLocation(),
9312 diag::err_module_odr_violation_different_definitions)
9313 << FirstRecord << FirstModule.empty() << FirstModule;
9314
9315 Diag(SecondRecord->getLocation(),
9316 diag::note_module_odr_violation_different_definitions)
9317 << SecondModule;
9318 Diagnosed = true;
9319 break;
9320 }
9321
9322 if (FirstDiffType != SecondDiffType) {
9323 SourceLocation FirstLoc;
9324 SourceRange FirstRange;
9325 if (FirstDiffType == EndOfClass) {
9326 FirstLoc = FirstRecord->getBraceRange().getEnd();
9327 } else {
9328 FirstLoc = FirstIt->first->getLocation();
9329 FirstRange = FirstIt->first->getSourceRange();
9330 }
9331 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9332 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9333 << FirstDiffType;
9334
9335 SourceLocation SecondLoc;
9336 SourceRange SecondRange;
9337 if (SecondDiffType == EndOfClass) {
9338 SecondLoc = SecondRecord->getBraceRange().getEnd();
9339 } else {
9340 SecondLoc = SecondDecl->getLocation();
9341 SecondRange = SecondDecl->getSourceRange();
9342 }
9343 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9344 << SecondModule << SecondRange << SecondDiffType;
9345 Diagnosed = true;
9346 break;
9347 }
9348
Richard Trieu639d7b62017-02-22 22:22:42 +00009349 assert(FirstDiffType == SecondDiffType);
9350
9351 // Used with err_module_odr_violation_mismatch_decl_diff and
9352 // note_module_odr_violation_mismatch_decl_diff
9353 enum ODRDeclDifference{
9354 StaticAssertCondition,
9355 StaticAssertMessage,
9356 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009357 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009358 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009359 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009360 FieldDifferentWidthBitField,
9361 FieldSingleMutable,
9362 FieldSingleInitializer,
9363 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009364 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009365 MethodDeleted,
9366 MethodVirtual,
9367 MethodStatic,
9368 MethodVolatile,
9369 MethodConst,
9370 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009371 MethodNumberParameters,
9372 MethodParameterType,
9373 MethodParameterName,
Richard Trieu639d7b62017-02-22 22:22:42 +00009374 };
9375
9376 // These lambdas have the common portions of the ODR diagnostics. This
9377 // has the same return as Diag(), so addition parameters can be passed
9378 // in with operator<<
9379 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9380 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9381 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9382 << FirstRecord << FirstModule.empty() << FirstModule << Range
9383 << DiffType;
9384 };
9385 auto ODRDiagNote = [&SecondModule, this](
9386 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9387 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9388 << SecondModule << Range << DiffType;
9389 };
9390
9391 auto ComputeODRHash = [&Hash](const Stmt* S) {
9392 assert(S);
9393 Hash.clear();
9394 Hash.AddStmt(S);
9395 return Hash.CalculateHash();
9396 };
9397
Richard Trieu02552272017-05-02 23:58:52 +00009398 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9399 Hash.clear();
9400 Hash.AddQualType(Ty);
9401 return Hash.CalculateHash();
9402 };
9403
Richard Trieu639d7b62017-02-22 22:22:42 +00009404 switch (FirstDiffType) {
9405 case Other:
9406 case EndOfClass:
9407 case PublicSpecifer:
9408 case PrivateSpecifer:
9409 case ProtectedSpecifer:
9410 llvm_unreachable("Invalid diff type");
9411
9412 case StaticAssert: {
9413 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9414 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9415
9416 Expr *FirstExpr = FirstSA->getAssertExpr();
9417 Expr *SecondExpr = SecondSA->getAssertExpr();
9418 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9419 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9420 if (FirstODRHash != SecondODRHash) {
9421 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9422 StaticAssertCondition);
9423 ODRDiagNote(SecondExpr->getLocStart(),
9424 SecondExpr->getSourceRange(), StaticAssertCondition);
9425 Diagnosed = true;
9426 break;
9427 }
9428
9429 StringLiteral *FirstStr = FirstSA->getMessage();
9430 StringLiteral *SecondStr = SecondSA->getMessage();
9431 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9432 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9433 SourceLocation FirstLoc, SecondLoc;
9434 SourceRange FirstRange, SecondRange;
9435 if (FirstStr) {
9436 FirstLoc = FirstStr->getLocStart();
9437 FirstRange = FirstStr->getSourceRange();
9438 } else {
9439 FirstLoc = FirstSA->getLocStart();
9440 FirstRange = FirstSA->getSourceRange();
9441 }
9442 if (SecondStr) {
9443 SecondLoc = SecondStr->getLocStart();
9444 SecondRange = SecondStr->getSourceRange();
9445 } else {
9446 SecondLoc = SecondSA->getLocStart();
9447 SecondRange = SecondSA->getSourceRange();
9448 }
9449 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9450 << (FirstStr == nullptr);
9451 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9452 << (SecondStr == nullptr);
9453 Diagnosed = true;
9454 break;
9455 }
9456
9457 if (FirstStr && SecondStr &&
9458 FirstStr->getString() != SecondStr->getString()) {
9459 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9460 StaticAssertMessage);
9461 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9462 StaticAssertMessage);
9463 Diagnosed = true;
9464 break;
9465 }
9466 break;
9467 }
Richard Trieud0786092017-02-23 00:23:01 +00009468 case Field: {
9469 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9470 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9471 IdentifierInfo *FirstII = FirstField->getIdentifier();
9472 IdentifierInfo *SecondII = SecondField->getIdentifier();
9473 if (FirstII->getName() != SecondII->getName()) {
9474 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9475 FieldName)
9476 << FirstII;
9477 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9478 FieldName)
9479 << SecondII;
9480
9481 Diagnosed = true;
9482 break;
9483 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009484
9485 assert(
9486 Context.hasSameType(FirstField->getType(), SecondField->getType()));
9487
9488 QualType FirstType = FirstField->getType();
9489 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +00009490 if (ComputeQualTypeODRHash(FirstType) !=
9491 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +00009492 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9493 FieldTypeName)
9494 << FirstII << FirstType;
9495 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9496 FieldTypeName)
9497 << SecondII << SecondType;
9498
9499 Diagnosed = true;
9500 break;
9501 }
9502
Richard Trieu93772fc2017-02-24 20:59:28 +00009503 const bool IsFirstBitField = FirstField->isBitField();
9504 const bool IsSecondBitField = SecondField->isBitField();
9505 if (IsFirstBitField != IsSecondBitField) {
9506 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9507 FieldSingleBitField)
9508 << FirstII << IsFirstBitField;
9509 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9510 FieldSingleBitField)
9511 << SecondII << IsSecondBitField;
9512 Diagnosed = true;
9513 break;
9514 }
9515
9516 if (IsFirstBitField && IsSecondBitField) {
9517 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9518 FieldDifferentWidthBitField)
9519 << FirstII << FirstField->getBitWidth()->getSourceRange();
9520 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9521 FieldDifferentWidthBitField)
9522 << SecondII << SecondField->getBitWidth()->getSourceRange();
9523 Diagnosed = true;
9524 break;
9525 }
9526
Richard Trieu8d543e22017-02-24 23:35:37 +00009527 const bool IsFirstMutable = FirstField->isMutable();
9528 const bool IsSecondMutable = SecondField->isMutable();
9529 if (IsFirstMutable != IsSecondMutable) {
9530 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9531 FieldSingleMutable)
9532 << FirstII << IsFirstMutable;
9533 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9534 FieldSingleMutable)
9535 << SecondII << IsSecondMutable;
9536 Diagnosed = true;
9537 break;
9538 }
9539
9540 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9541 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9542 if ((!FirstInitializer && SecondInitializer) ||
9543 (FirstInitializer && !SecondInitializer)) {
9544 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9545 FieldSingleInitializer)
9546 << FirstII << (FirstInitializer != nullptr);
9547 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9548 FieldSingleInitializer)
9549 << SecondII << (SecondInitializer != nullptr);
9550 Diagnosed = true;
9551 break;
9552 }
9553
9554 if (FirstInitializer && SecondInitializer) {
9555 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9556 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9557 if (FirstInitHash != SecondInitHash) {
9558 ODRDiagError(FirstField->getLocation(),
9559 FirstField->getSourceRange(),
9560 FieldDifferentInitializers)
9561 << FirstII << FirstInitializer->getSourceRange();
9562 ODRDiagNote(SecondField->getLocation(),
9563 SecondField->getSourceRange(),
9564 FieldDifferentInitializers)
9565 << SecondII << SecondInitializer->getSourceRange();
9566 Diagnosed = true;
9567 break;
9568 }
9569 }
9570
Richard Trieud0786092017-02-23 00:23:01 +00009571 break;
9572 }
Richard Trieu48143742017-02-28 21:24:38 +00009573 case CXXMethod: {
9574 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
9575 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu583e2c12017-03-04 00:08:58 +00009576 auto FirstName = FirstMethod->getDeclName();
9577 auto SecondName = SecondMethod->getDeclName();
9578 if (FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +00009579 ODRDiagError(FirstMethod->getLocation(),
9580 FirstMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009581 << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +00009582 ODRDiagNote(SecondMethod->getLocation(),
9583 SecondMethod->getSourceRange(), MethodName)
Richard Trieu583e2c12017-03-04 00:08:58 +00009584 << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +00009585
9586 Diagnosed = true;
9587 break;
9588 }
9589
Richard Trieu583e2c12017-03-04 00:08:58 +00009590 const bool FirstDeleted = FirstMethod->isDeleted();
9591 const bool SecondDeleted = SecondMethod->isDeleted();
9592 if (FirstDeleted != SecondDeleted) {
9593 ODRDiagError(FirstMethod->getLocation(),
9594 FirstMethod->getSourceRange(), MethodDeleted)
9595 << FirstName << FirstDeleted;
9596
9597 ODRDiagNote(SecondMethod->getLocation(),
9598 SecondMethod->getSourceRange(), MethodDeleted)
9599 << SecondName << SecondDeleted;
9600 Diagnosed = true;
9601 break;
9602 }
9603
9604 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
9605 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
9606 const bool FirstPure = FirstMethod->isPure();
9607 const bool SecondPure = SecondMethod->isPure();
9608 if ((FirstVirtual || SecondVirtual) &&
9609 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
9610 ODRDiagError(FirstMethod->getLocation(),
9611 FirstMethod->getSourceRange(), MethodVirtual)
9612 << FirstName << FirstPure << FirstVirtual;
9613 ODRDiagNote(SecondMethod->getLocation(),
9614 SecondMethod->getSourceRange(), MethodVirtual)
9615 << SecondName << SecondPure << SecondVirtual;
9616 Diagnosed = true;
9617 break;
9618 }
9619
9620 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
9621 // FirstDecl is the canonical Decl of SecondDecl, so the storage
9622 // class needs to be checked instead.
9623 const auto FirstStorage = FirstMethod->getStorageClass();
9624 const auto SecondStorage = SecondMethod->getStorageClass();
9625 const bool FirstStatic = FirstStorage == SC_Static;
9626 const bool SecondStatic = SecondStorage == SC_Static;
9627 if (FirstStatic != SecondStatic) {
9628 ODRDiagError(FirstMethod->getLocation(),
9629 FirstMethod->getSourceRange(), MethodStatic)
9630 << FirstName << FirstStatic;
9631 ODRDiagNote(SecondMethod->getLocation(),
9632 SecondMethod->getSourceRange(), MethodStatic)
9633 << SecondName << SecondStatic;
9634 Diagnosed = true;
9635 break;
9636 }
9637
9638 const bool FirstVolatile = FirstMethod->isVolatile();
9639 const bool SecondVolatile = SecondMethod->isVolatile();
9640 if (FirstVolatile != SecondVolatile) {
9641 ODRDiagError(FirstMethod->getLocation(),
9642 FirstMethod->getSourceRange(), MethodVolatile)
9643 << FirstName << FirstVolatile;
9644 ODRDiagNote(SecondMethod->getLocation(),
9645 SecondMethod->getSourceRange(), MethodVolatile)
9646 << SecondName << SecondVolatile;
9647 Diagnosed = true;
9648 break;
9649 }
9650
9651 const bool FirstConst = FirstMethod->isConst();
9652 const bool SecondConst = SecondMethod->isConst();
9653 if (FirstConst != SecondConst) {
9654 ODRDiagError(FirstMethod->getLocation(),
9655 FirstMethod->getSourceRange(), MethodConst)
9656 << FirstName << FirstConst;
9657 ODRDiagNote(SecondMethod->getLocation(),
9658 SecondMethod->getSourceRange(), MethodConst)
9659 << SecondName << SecondConst;
9660 Diagnosed = true;
9661 break;
9662 }
9663
9664 const bool FirstInline = FirstMethod->isInlineSpecified();
9665 const bool SecondInline = SecondMethod->isInlineSpecified();
9666 if (FirstInline != SecondInline) {
9667 ODRDiagError(FirstMethod->getLocation(),
9668 FirstMethod->getSourceRange(), MethodInline)
9669 << FirstName << FirstInline;
9670 ODRDiagNote(SecondMethod->getLocation(),
9671 SecondMethod->getSourceRange(), MethodInline)
9672 << SecondName << SecondInline;
9673 Diagnosed = true;
9674 break;
9675 }
9676
Richard Trieu02552272017-05-02 23:58:52 +00009677 const unsigned FirstNumParameters = FirstMethod->param_size();
9678 const unsigned SecondNumParameters = SecondMethod->param_size();
9679 if (FirstNumParameters != SecondNumParameters) {
9680 ODRDiagError(FirstMethod->getLocation(),
9681 FirstMethod->getSourceRange(), MethodNumberParameters)
9682 << FirstName << FirstNumParameters;
9683 ODRDiagNote(SecondMethod->getLocation(),
9684 SecondMethod->getSourceRange(), MethodNumberParameters)
9685 << SecondName << SecondNumParameters;
9686 Diagnosed = true;
9687 break;
9688 }
9689
9690 // Need this status boolean to know when break out of the switch.
9691 bool ParameterMismatch = false;
9692 for (unsigned I = 0; I < FirstNumParameters; ++I) {
9693 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
9694 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
9695
9696 QualType FirstParamType = FirstParam->getType();
9697 QualType SecondParamType = SecondParam->getType();
9698 if (FirstParamType != SecondParamType &&
9699 ComputeQualTypeODRHash(FirstParamType) !=
9700 ComputeQualTypeODRHash(SecondParamType)) {
9701 if (const DecayedType *ParamDecayedType =
9702 FirstParamType->getAs<DecayedType>()) {
9703 ODRDiagError(FirstMethod->getLocation(),
9704 FirstMethod->getSourceRange(), MethodParameterType)
9705 << FirstName << (I + 1) << FirstParamType << true
9706 << ParamDecayedType->getOriginalType();
9707 } else {
9708 ODRDiagError(FirstMethod->getLocation(),
9709 FirstMethod->getSourceRange(), MethodParameterType)
9710 << FirstName << (I + 1) << FirstParamType << false;
9711 }
9712
9713 if (const DecayedType *ParamDecayedType =
9714 SecondParamType->getAs<DecayedType>()) {
9715 ODRDiagNote(SecondMethod->getLocation(),
9716 SecondMethod->getSourceRange(), MethodParameterType)
9717 << SecondName << (I + 1) << SecondParamType << true
9718 << ParamDecayedType->getOriginalType();
9719 } else {
9720 ODRDiagNote(SecondMethod->getLocation(),
9721 SecondMethod->getSourceRange(), MethodParameterType)
9722 << SecondName << (I + 1) << SecondParamType << false;
9723 }
9724 ParameterMismatch = true;
9725 break;
9726 }
9727
9728 DeclarationName FirstParamName = FirstParam->getDeclName();
9729 DeclarationName SecondParamName = SecondParam->getDeclName();
9730 if (FirstParamName != SecondParamName) {
9731 ODRDiagError(FirstMethod->getLocation(),
9732 FirstMethod->getSourceRange(), MethodParameterName)
9733 << FirstName << (I + 1) << FirstParamName;
9734 ODRDiagNote(SecondMethod->getLocation(),
9735 SecondMethod->getSourceRange(), MethodParameterName)
9736 << SecondName << (I + 1) << SecondParamName;
9737 ParameterMismatch = true;
9738 break;
9739 }
9740 }
9741
9742 if (ParameterMismatch) {
9743 Diagnosed = true;
9744 break;
9745 }
9746
Richard Trieu48143742017-02-28 21:24:38 +00009747 break;
9748 }
Richard Trieu639d7b62017-02-22 22:22:42 +00009749 }
9750
Richard Trieue7f7ed22017-02-22 01:11:25 +00009751 if (Diagnosed == true)
9752 continue;
9753
9754 Diag(FirstRecord->getLocation(),
9755 diag::err_module_odr_violation_different_definitions)
9756 << FirstRecord << FirstModule.empty() << FirstModule;
9757
9758 Diag(SecondRecord->getLocation(),
9759 diag::note_module_odr_violation_different_definitions)
9760 << SecondModule;
9761 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009762 }
9763
9764 if (!Diagnosed) {
9765 // All definitions are updates to the same declaration. This happens if a
9766 // module instantiates the declaration of a class template specialization
9767 // and two or more other modules instantiate its definition.
9768 //
9769 // FIXME: Indicate which modules had instantiations of this definition.
9770 // FIXME: How can this even happen?
9771 Diag(Merge.first->getLocation(),
9772 diag::err_module_odr_violation_different_instantiations)
9773 << Merge.first;
9774 }
9775 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009776}
9777
Richard Smithce18a182015-07-14 00:26:00 +00009778void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009779 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +00009780 ReadTimer->startTimer();
9781}
9782
Guy Benyei11169dd2012-12-18 14:30:41 +00009783void ASTReader::FinishedDeserializing() {
9784 assert(NumCurrentElementsDeserializing &&
9785 "FinishedDeserializing not paired with StartedDeserializing");
9786 if (NumCurrentElementsDeserializing == 1) {
9787 // We decrease NumCurrentElementsDeserializing only after pending actions
9788 // are finished, to avoid recursively re-calling finishPendingActions().
9789 finishPendingActions();
9790 }
9791 --NumCurrentElementsDeserializing;
9792
Richard Smitha0ce9c42014-07-29 23:23:27 +00009793 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009794 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +00009795 while (!PendingExceptionSpecUpdates.empty()) {
9796 auto Updates = std::move(PendingExceptionSpecUpdates);
9797 PendingExceptionSpecUpdates.clear();
9798 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +00009799 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +00009800 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +00009801 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithd88a7f12015-09-01 20:35:42 +00009802 if (auto *Listener = Context.getASTMutationListener())
9803 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +00009804 for (auto *Redecl : Update.second->redecls())
9805 Context.adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +00009806 }
Richard Smith9e2341d2015-03-23 03:25:59 +00009807 }
9808
Richard Smithce18a182015-07-14 00:26:00 +00009809 if (ReadTimer)
9810 ReadTimer->stopTimer();
9811
Richard Smith0f4e2c42015-08-06 04:23:48 +00009812 diagnoseOdrViolations();
9813
Richard Smith04d05b52014-03-23 00:27:18 +00009814 // We are not in recursive loading, so it's safe to pass the "interesting"
9815 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009816 if (Consumer)
9817 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +00009818 }
9819}
9820
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009821void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +00009822 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
9823 // Remove any fake results before adding any real ones.
9824 auto It = PendingFakeLookupResults.find(II);
9825 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +00009826 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +00009827 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +00009828 // FIXME: this works around module+PCH performance issue.
9829 // Rather than erase the result from the map, which is O(n), just clear
9830 // the vector of NamedDecls.
9831 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +00009832 }
9833 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009834
9835 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
9836 SemaObj->TUScope->AddDecl(D);
9837 } else if (SemaObj->TUScope) {
9838 // Adding the decl to IdResolver may have failed because it was already in
9839 // (even though it was not added in scope). If it is already in, make sure
9840 // it gets in the scope as well.
9841 if (std::find(SemaObj->IdResolver.begin(Name),
9842 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
9843 SemaObj->TUScope->AddDecl(D);
9844 }
9845}
9846
David Blaikie61137e12017-01-05 18:23:18 +00009847ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
9848 const PCHContainerReader &PCHContainerRdr,
9849 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
9850 StringRef isysroot, bool DisableValidation,
9851 bool AllowASTWithCompilerErrors,
9852 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
9853 bool UseGlobalIndex,
9854 std::unique_ptr<llvm::Timer> ReadTimer)
9855 : Listener(DisableValidation
9856 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
9857 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +00009858 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009859 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00009860 Context(Context),
9861 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr),
9862 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
9863 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +00009864 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +00009865 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
9866 AllowConfigurationMismatch(AllowConfigurationMismatch),
9867 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +00009868 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009869 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +00009870
9871 for (const auto &Ext : Extensions) {
9872 auto BlockName = Ext->getExtensionMetadata().BlockName;
9873 auto Known = ModuleFileExtensions.find(BlockName);
9874 if (Known != ModuleFileExtensions.end()) {
9875 Diags.Report(diag::warn_duplicate_module_file_extension)
9876 << BlockName;
9877 continue;
9878 }
9879
9880 ModuleFileExtensions.insert({BlockName, Ext});
9881 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009882}
9883
9884ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +00009885 if (OwnsDeserializationListener)
9886 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +00009887}
Richard Smith10379092016-05-06 23:14:07 +00009888
9889IdentifierResolver &ASTReader::getIdResolver() {
9890 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
9891}
David L. Jonesbe1557a2016-12-21 00:17:49 +00009892
9893unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
9894 unsigned AbbrevID) {
9895 Idx = 0;
9896 Record.clear();
9897 return Cursor.readRecord(AbbrevID, Record);
9898}