blob: 82bf6e157bb28357f97564ee2835c1a2c193842a [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 Smithdbafb6c2017-06-29 23:23:46 +0000859 (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
Richard Smitha534a312015-07-21 23:54:07 +0000860 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 Smithdbafb6c2017-06-29 23:23:46 +00001151 if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
Richard Smithfb1e7f72015-08-14 05:02:58 +00001152 !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];
Richard Smithdbafb6c2017-06-29 23:23:46 +00001394 if (NumFileDecls && ContextObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 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
Richard Smithf3f84612017-06-29 02:19:42 +00001401 = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
Guy Benyei11169dd2012-12-18 14:30:41 +00001402 if (OverriddenBuffer && !ContentCache->BufferOverridden &&
Richard Smitha8cfffa2015-11-26 02:04:16 +00001403 ContentCache->ContentsEntry == ContentCache->OrigEntry &&
1404 !ContentCache->getRawBuffer()) {
Richard Smithaada85c2016-02-06 02:06:43 +00001405 auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
1406 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 return true;
David Blaikie49cc3182014-08-27 20:54:45 +00001408 SourceMgr.overrideFileContents(File, std::move(Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 }
1410
1411 break;
1412 }
1413
1414 case SM_SLOC_BUFFER_ENTRY: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00001415 const char *Name = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00001416 unsigned Offset = Record[0];
1417 SrcMgr::CharacteristicKind
1418 FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
1419 SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
Manman Ren11f2a472016-08-18 17:42:15 +00001420 if (IncludeLoc.isInvalid() && F->isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001421 IncludeLoc = getImportLocation(F);
1422 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001423
Richard Smithaada85c2016-02-06 02:06:43 +00001424 auto Buffer = ReadBuffer(SLocEntryCursor, Name);
1425 if (!Buffer)
Guy Benyei11169dd2012-12-18 14:30:41 +00001426 return true;
David Blaikie50a5f972014-08-29 07:59:55 +00001427 SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
Rafael Espindolad87f8d72014-08-27 20:03:29 +00001428 BaseOffset + Offset, IncludeLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001429 break;
1430 }
1431
1432 case SM_SLOC_EXPANSION_ENTRY: {
1433 SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
1434 SourceMgr.createExpansionLoc(SpellingLoc,
1435 ReadSourceLocation(*F, Record[2]),
1436 ReadSourceLocation(*F, Record[3]),
1437 Record[4],
1438 ID,
1439 BaseOffset + Record[0]);
1440 break;
1441 }
1442 }
1443
1444 return false;
1445}
1446
1447std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
1448 if (ID == 0)
1449 return std::make_pair(SourceLocation(), "");
1450
1451 if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
1452 Error("source location entry ID out-of-range for AST file");
1453 return std::make_pair(SourceLocation(), "");
1454 }
1455
1456 // Find which module file this entry lands in.
1457 ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
Manman Ren11f2a472016-08-18 17:42:15 +00001458 if (!M->isModule())
Guy Benyei11169dd2012-12-18 14:30:41 +00001459 return std::make_pair(SourceLocation(), "");
1460
1461 // FIXME: Can we map this down to a particular submodule? That would be
1462 // ideal.
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001463 return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
Guy Benyei11169dd2012-12-18 14:30:41 +00001464}
1465
1466/// \brief Find the location where the module F is imported.
1467SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
1468 if (F->ImportLoc.isValid())
1469 return F->ImportLoc;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001470
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 // Otherwise we have a PCH. It's considered to be "imported" at the first
1472 // location of its includer.
1473 if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001474 // Main file is the importer.
Yaron Keren8b563662015-10-03 10:46:20 +00001475 assert(SourceMgr.getMainFileID().isValid() && "missing main file");
Ben Langmuirbeee15e2014-04-14 18:00:01 +00001476 return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001478 return F->ImportedBy[0]->FirstLoc;
1479}
1480
1481/// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1482/// specified cursor. Read the abbreviations that are at the top of the block
1483/// and then leave the cursor pointing into the block.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001484bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
Richard Smith0516b182015-09-08 19:40:14 +00001485 if (Cursor.EnterSubBlock(BlockID))
1486 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001487
1488 while (true) {
1489 uint64_t Offset = Cursor.GetCurrentBitNo();
1490 unsigned Code = Cursor.ReadCode();
1491
1492 // We expect all abbrevs to be at the start of the block.
1493 if (Code != llvm::bitc::DEFINE_ABBREV) {
1494 Cursor.JumpToBit(Offset);
1495 return false;
1496 }
1497 Cursor.ReadAbbrevRecord();
1498 }
1499}
1500
Richard Smithe40f2ba2013-08-07 21:41:30 +00001501Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
John McCallf413f5e2013-05-03 00:10:13 +00001502 unsigned &Idx) {
1503 Token Tok;
1504 Tok.startToken();
1505 Tok.setLocation(ReadSourceLocation(F, Record, Idx));
1506 Tok.setLength(Record[Idx++]);
1507 if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
1508 Tok.setIdentifierInfo(II);
1509 Tok.setKind((tok::TokenKind)Record[Idx++]);
1510 Tok.setFlag((Token::TokenFlags)Record[Idx++]);
1511 return Tok;
1512}
1513
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001514MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001515 BitstreamCursor &Stream = F.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001516
1517 // Keep track of where we are in the stream, then jump back there
1518 // after reading this macro.
1519 SavedStreamPosition SavedPosition(Stream);
1520
1521 Stream.JumpToBit(Offset);
1522 RecordData Record;
Faisal Valiac506d72017-07-17 17:18:43 +00001523 SmallVector<IdentifierInfo*, 16> MacroParams;
Craig Toppera13603a2014-05-22 05:54:18 +00001524 MacroInfo *Macro = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001525
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00001527 // Advance to the next record, but if we get to the end of the block, don't
1528 // pop it (removing all the abbreviations from the cursor) since we want to
1529 // be able to reseek within the block and read entries.
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001530 unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
Chris Lattnerefa77172013-01-20 00:00:22 +00001531 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001532
Chris Lattnerefa77172013-01-20 00:00:22 +00001533 switch (Entry.Kind) {
1534 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1535 case llvm::BitstreamEntry::Error:
1536 Error("malformed block record in AST file");
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001537 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001538 case llvm::BitstreamEntry::EndBlock:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001539 return Macro;
Chris Lattnerefa77172013-01-20 00:00:22 +00001540 case llvm::BitstreamEntry::Record:
1541 // The interesting case.
1542 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 }
1544
1545 // Read a record.
Guy Benyei11169dd2012-12-18 14:30:41 +00001546 Record.clear();
1547 PreprocessorRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00001548 (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 switch (RecType) {
Richard Smithd7329392015-04-21 21:46:32 +00001550 case PP_MODULE_MACRO:
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001551 case PP_MACRO_DIRECTIVE_HISTORY:
1552 return Macro;
1553
Guy Benyei11169dd2012-12-18 14:30:41 +00001554 case PP_MACRO_OBJECT_LIKE:
1555 case PP_MACRO_FUNCTION_LIKE: {
1556 // If we already have a macro, that means that we've hit the end
1557 // of the definition of the macro we were looking for. We're
1558 // done.
1559 if (Macro)
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001560 return Macro;
Guy Benyei11169dd2012-12-18 14:30:41 +00001561
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001562 unsigned NextIndex = 1; // Skip identifier ID.
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
Richard Smith3f6dd7a2017-05-12 23:40:52 +00001564 MacroInfo *MI = PP.AllocateMacroInfo(Loc);
Argyrios Kyrtzidis7572be22013-01-07 19:16:23 +00001565 MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 MI->setIsUsed(Record[NextIndex++]);
Argyrios Kyrtzidis9ef53ce2014-04-09 18:21:23 +00001567 MI->setUsedForHeaderGuard(Record[NextIndex++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00001568
Guy Benyei11169dd2012-12-18 14:30:41 +00001569 if (RecType == PP_MACRO_FUNCTION_LIKE) {
1570 // Decode function-like macro info.
1571 bool isC99VarArgs = Record[NextIndex++];
1572 bool isGNUVarArgs = Record[NextIndex++];
1573 bool hasCommaPasting = Record[NextIndex++];
Faisal Valiac506d72017-07-17 17:18:43 +00001574 MacroParams.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00001575 unsigned NumArgs = Record[NextIndex++];
1576 for (unsigned i = 0; i != NumArgs; ++i)
Faisal Valiac506d72017-07-17 17:18:43 +00001577 MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00001578
1579 // Install function-like macro info.
1580 MI->setIsFunctionLike();
1581 if (isC99VarArgs) MI->setIsC99Varargs();
1582 if (isGNUVarArgs) MI->setIsGNUVarargs();
1583 if (hasCommaPasting) MI->setHasCommaPasting();
Faisal Valiac506d72017-07-17 17:18:43 +00001584 MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
Guy Benyei11169dd2012-12-18 14:30:41 +00001585 }
1586
Guy Benyei11169dd2012-12-18 14:30:41 +00001587 // Remember that we saw this macro last so that we add the tokens that
1588 // form its body to it.
1589 Macro = MI;
1590
1591 if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
1592 Record[NextIndex]) {
1593 // We have a macro definition. Register the association
1594 PreprocessedEntityID
1595 GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
1596 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Richard Smith66a81862015-05-04 02:25:31 +00001597 PreprocessingRecord::PPEntityID PPID =
1598 PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
1599 MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
1600 PPRec.getPreprocessedEntity(PPID));
Argyrios Kyrtzidis832de9f2013-02-22 18:35:59 +00001601 if (PPDef)
1602 PPRec.RegisterMacroDefinition(Macro, PPDef);
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 }
1604
1605 ++NumMacrosRead;
1606 break;
1607 }
1608
1609 case PP_TOKEN: {
1610 // If we see a TOKEN before a PP_MACRO_*, then the file is
1611 // erroneous, just pretend we didn't see this.
Craig Toppera13603a2014-05-22 05:54:18 +00001612 if (!Macro) break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001613
John McCallf413f5e2013-05-03 00:10:13 +00001614 unsigned Idx = 0;
1615 Token Tok = ReadToken(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00001616 Macro->AddTokenToBody(Tok);
1617 break;
1618 }
1619 }
1620 }
1621}
1622
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001623PreprocessedEntityID
Richard Smith37a93df2017-02-18 00:32:02 +00001624ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
1625 unsigned LocalID) const {
1626 if (!M.ModuleOffsetMap.empty())
1627 ReadModuleOffsetMap(M);
1628
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001629 ContinuousRangeMap<uint32_t, int, 2>::const_iterator
Guy Benyei11169dd2012-12-18 14:30:41 +00001630 I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001631 assert(I != M.PreprocessedEntityRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 && "Invalid index into preprocessed entity index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001633
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 return LocalID + I->second;
1635}
1636
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001637unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
1638 return llvm::hash_combine(ikey.Size, ikey.ModTime);
Guy Benyei11169dd2012-12-18 14:30:41 +00001639}
Richard Smith7ed1bc92014-12-05 22:42:13 +00001640
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001641HeaderFileInfoTrait::internal_key_type
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001642HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001643 internal_key_type ikey = {FE->getSize(),
1644 M.HasTimestamps ? FE->getModificationTime() : 0,
1645 FE->getName(), /*Imported*/ false};
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001646 return ikey;
1647}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001648
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001649bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
Richard Smithe75ee0f2015-08-17 07:13:32 +00001650 if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
Guy Benyei11169dd2012-12-18 14:30:41 +00001651 return false;
1652
Mehdi Amini004b9c72016-10-10 22:52:47 +00001653 if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001654 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001655
Guy Benyei11169dd2012-12-18 14:30:41 +00001656 // Determine whether the actual files are equivalent.
Argyrios Kyrtzidis2a513e82013-03-04 20:33:40 +00001657 FileManager &FileMgr = Reader.getFileManager();
Richard Smith7ed1bc92014-12-05 22:42:13 +00001658 auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
1659 if (!Key.Imported)
1660 return FileMgr.getFile(Key.Filename);
1661
1662 std::string Resolved = Key.Filename;
1663 Reader.ResolveImportedPath(M, Resolved);
1664 return FileMgr.getFile(Resolved);
1665 };
1666
1667 const FileEntry *FEA = GetFile(a);
1668 const FileEntry *FEB = GetFile(b);
1669 return FEA && FEA == FEB;
Guy Benyei11169dd2012-12-18 14:30:41 +00001670}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001671
Guy Benyei11169dd2012-12-18 14:30:41 +00001672std::pair<unsigned, unsigned>
1673HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001674 using namespace llvm::support;
1675 unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
Guy Benyei11169dd2012-12-18 14:30:41 +00001676 unsigned DataLen = (unsigned) *d++;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001677 return std::make_pair(KeyLen, DataLen);
Guy Benyei11169dd2012-12-18 14:30:41 +00001678}
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001679
1680HeaderFileInfoTrait::internal_key_type
1681HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001682 using namespace llvm::support;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001683 internal_key_type ikey;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001684 ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
1685 ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001686 ikey.Filename = (const char *)d;
Richard Smith7ed1bc92014-12-05 22:42:13 +00001687 ikey.Imported = true;
Argyrios Kyrtzidis5c2a3452013-03-06 18:12:47 +00001688 return ikey;
1689}
1690
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001691HeaderFileInfoTrait::data_type
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001692HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
Guy Benyei11169dd2012-12-18 14:30:41 +00001693 unsigned DataLen) {
1694 const unsigned char *End = d + DataLen;
Justin Bogner57ba0b22014-03-28 22:03:24 +00001695 using namespace llvm::support;
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 HeaderFileInfo HFI;
1697 unsigned Flags = *d++;
Richard Smith386bb072015-08-18 23:42:23 +00001698 // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
Richard Smithf3f84612017-06-29 02:19:42 +00001699 HFI.isImport |= (Flags >> 5) & 0x01;
1700 HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
1701 HFI.DirInfo = (Flags >> 1) & 0x07;
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 HFI.IndexHeaderMapHeader = Flags & 0x01;
Richard Smith386bb072015-08-18 23:42:23 +00001703 // FIXME: Find a better way to handle this. Maybe just store a
1704 // "has been included" flag?
1705 HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
1706 HFI.NumIncludes);
Justin Bogner57ba0b22014-03-28 22:03:24 +00001707 HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
1708 M, endian::readNext<uint32_t, little, unaligned>(d));
1709 if (unsigned FrameworkOffset =
1710 endian::readNext<uint32_t, little, unaligned>(d)) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001711 // The framework offset is 1 greater than the actual offset,
Guy Benyei11169dd2012-12-18 14:30:41 +00001712 // since 0 is used as an indicator for "no framework name".
1713 StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
1714 HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
1715 }
Richard Smith386bb072015-08-18 23:42:23 +00001716
1717 assert((End - d) % 4 == 0 &&
1718 "Wrong data length in HeaderFileInfo deserialization");
1719 while (d != End) {
Justin Bogner57ba0b22014-03-28 22:03:24 +00001720 uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
Richard Smith386bb072015-08-18 23:42:23 +00001721 auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
1722 LocalSMID >>= 2;
1723
1724 // This header is part of a module. Associate it with the module to enable
1725 // implicit module import.
1726 SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
1727 Module *Mod = Reader.getSubmodule(GlobalSMID);
1728 FileManager &FileMgr = Reader.getFileManager();
1729 ModuleMap &ModMap =
1730 Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
1731
1732 std::string Filename = key.Filename;
1733 if (key.Imported)
1734 Reader.ResolveImportedPath(M, Filename);
1735 // FIXME: This is not always the right filename-as-written, but we're not
1736 // going to use this information to rebuild the module, so it doesn't make
1737 // a lot of difference.
1738 Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
Richard Smithd8879c82015-08-24 21:59:32 +00001739 ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
1740 HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00001741 }
1742
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 // This HeaderFileInfo was externally loaded.
1744 HFI.External = true;
Richard Smithd8879c82015-08-24 21:59:32 +00001745 HFI.IsValid = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00001746 return HFI;
1747}
1748
Richard Smithd7329392015-04-21 21:46:32 +00001749void ASTReader::addPendingMacro(IdentifierInfo *II,
1750 ModuleFile *M,
1751 uint64_t MacroDirectivesOffset) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001752 assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
1753 PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
Guy Benyei11169dd2012-12-18 14:30:41 +00001754}
1755
1756void ASTReader::ReadDefinedMacros() {
1757 // Note that we are loading defined macros.
1758 Deserializing Macros(this);
1759
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001760 for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
1761 BitstreamCursor &MacroCursor = I.MacroCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00001762
1763 // If there was no preprocessor block, skip this file.
Peter Collingbourne77c89b62016-11-08 04:17:11 +00001764 if (MacroCursor.getBitcodeBytes().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00001765 continue;
1766
Chris Lattner7fb3bef2013-01-20 00:56:42 +00001767 BitstreamCursor Cursor = MacroCursor;
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001768 Cursor.JumpToBit(I.MacroStartOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00001769
1770 RecordData Record;
1771 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001772 llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001773
Chris Lattnere7b154b2013-01-19 21:39:22 +00001774 switch (E.Kind) {
1775 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
1776 case llvm::BitstreamEntry::Error:
1777 Error("malformed block record in AST file");
1778 return;
1779 case llvm::BitstreamEntry::EndBlock:
1780 goto NextCursor;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001781
Chris Lattnere7b154b2013-01-19 21:39:22 +00001782 case llvm::BitstreamEntry::Record:
Chris Lattnere7b154b2013-01-19 21:39:22 +00001783 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00001784 switch (Cursor.readRecord(E.ID, Record)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00001785 default: // Default behavior: ignore.
1786 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001787
Chris Lattnere7b154b2013-01-19 21:39:22 +00001788 case PP_MACRO_OBJECT_LIKE:
Sean Callananf3682a72016-05-14 06:24:14 +00001789 case PP_MACRO_FUNCTION_LIKE: {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00001790 IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
Sean Callananf3682a72016-05-14 06:24:14 +00001791 if (II->isOutOfDate())
1792 updateOutOfDateIdentifier(*II);
Chris Lattnere7b154b2013-01-19 21:39:22 +00001793 break;
Sean Callananf3682a72016-05-14 06:24:14 +00001794 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001795
Chris Lattnere7b154b2013-01-19 21:39:22 +00001796 case PP_TOKEN:
1797 // Ignore tokens.
1798 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 break;
1801 }
1802 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00001803 NextCursor: ;
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 }
1805}
1806
1807namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001808
Guy Benyei11169dd2012-12-18 14:30:41 +00001809 /// \brief Visitor class used to look up identifirs in an AST file.
1810 class IdentifierLookupVisitor {
1811 StringRef Name;
Richard Smith3b637412015-07-14 18:42:41 +00001812 unsigned NameHash;
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 unsigned PriorGeneration;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001814 unsigned &NumIdentifierLookups;
1815 unsigned &NumIdentifierLookupHits;
Guy Benyei11169dd2012-12-18 14:30:41 +00001816 IdentifierInfo *Found;
Douglas Gregor00a50f72013-01-25 00:38:33 +00001817
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 public:
Douglas Gregor00a50f72013-01-25 00:38:33 +00001819 IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
1820 unsigned &NumIdentifierLookups,
1821 unsigned &NumIdentifierLookupHits)
Richard Smith3b637412015-07-14 18:42:41 +00001822 : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
1823 PriorGeneration(PriorGeneration),
Douglas Gregor00a50f72013-01-25 00:38:33 +00001824 NumIdentifierLookups(NumIdentifierLookups),
1825 NumIdentifierLookupHits(NumIdentifierLookupHits),
1826 Found()
1827 {
1828 }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001829
1830 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001831 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00001832 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 return true;
Douglas Gregore060e572013-01-25 01:03:03 +00001834
Guy Benyei11169dd2012-12-18 14:30:41 +00001835 ASTIdentifierLookupTable *IdTable
1836 = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
1837 if (!IdTable)
1838 return false;
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001839
1840 ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
Richard Smithbdf2d932015-07-30 03:37:16 +00001841 Found);
1842 ++NumIdentifierLookups;
Richard Smith3b637412015-07-14 18:42:41 +00001843 ASTIdentifierLookupTable::iterator Pos =
Richard Smithbdf2d932015-07-30 03:37:16 +00001844 IdTable->find_hashed(Name, NameHash, &Trait);
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 if (Pos == IdTable->end())
1846 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001847
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 // Dereferencing the iterator has the effect of building the
1849 // IdentifierInfo node and populating it with the various
1850 // declarations it needs.
Richard Smithbdf2d932015-07-30 03:37:16 +00001851 ++NumIdentifierLookupHits;
1852 Found = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853 return true;
1854 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001855
Guy Benyei11169dd2012-12-18 14:30:41 +00001856 // \brief Retrieve the identifier info found within the module
1857 // files.
1858 IdentifierInfo *getIdentifierInfo() const { return Found; }
1859 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001860
1861} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00001862
1863void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
1864 // Note that we are loading an identifier.
1865 Deserializing AnIdentifier(this);
1866
1867 unsigned PriorGeneration = 0;
1868 if (getContext().getLangOpts().Modules)
1869 PriorGeneration = IdentifierGeneration[&II];
Douglas Gregore060e572013-01-25 01:03:03 +00001870
1871 // If there is a global index, look there first to determine which modules
1872 // provably do not have any results for this identifier.
Douglas Gregor7211ac12013-01-25 23:32:03 +00001873 GlobalModuleIndex::HitSet Hits;
Craig Toppera13603a2014-05-22 05:54:18 +00001874 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
Douglas Gregore060e572013-01-25 01:03:03 +00001875 if (!loadGlobalIndex()) {
Douglas Gregor7211ac12013-01-25 23:32:03 +00001876 if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
1877 HitsPtr = &Hits;
Douglas Gregore060e572013-01-25 01:03:03 +00001878 }
1879 }
1880
Douglas Gregor7211ac12013-01-25 23:32:03 +00001881 IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
Douglas Gregor00a50f72013-01-25 00:38:33 +00001882 NumIdentifierLookups,
1883 NumIdentifierLookupHits);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00001884 ModuleMgr.visit(Visitor, HitsPtr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001885 markIdentifierUpToDate(&II);
1886}
1887
1888void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
1889 if (!II)
1890 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00001891
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 II->setOutOfDate(false);
1893
1894 // Update the generation for this identifier.
1895 if (getContext().getLangOpts().Modules)
Richard Smith053f6c62014-05-16 23:01:30 +00001896 IdentifierGeneration[II] = getGeneration();
Guy Benyei11169dd2012-12-18 14:30:41 +00001897}
1898
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001899void ASTReader::resolvePendingMacro(IdentifierInfo *II,
1900 const PendingMacroInfo &PMInfo) {
Richard Smithd7329392015-04-21 21:46:32 +00001901 ModuleFile &M = *PMInfo.M;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001902
1903 BitstreamCursor &Cursor = M.MacroCursor;
1904 SavedStreamPosition SavedPosition(Cursor);
Richard Smithd7329392015-04-21 21:46:32 +00001905 Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001906
Richard Smith713369b2015-04-23 20:40:50 +00001907 struct ModuleMacroRecord {
1908 SubmoduleID SubModID;
1909 MacroInfo *MI;
1910 SmallVector<SubmoduleID, 8> Overrides;
1911 };
1912 llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001913
Richard Smithd7329392015-04-21 21:46:32 +00001914 // We expect to see a sequence of PP_MODULE_MACRO records listing exported
1915 // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
1916 // macro histroy.
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001917 RecordData Record;
Richard Smithd7329392015-04-21 21:46:32 +00001918 while (true) {
1919 llvm::BitstreamEntry Entry =
1920 Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
1921 if (Entry.Kind != llvm::BitstreamEntry::Record) {
1922 Error("malformed block record in AST file");
1923 return;
1924 }
1925
1926 Record.clear();
Aaron Ballmanc75a1922015-04-22 15:25:05 +00001927 switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Richard Smithd7329392015-04-21 21:46:32 +00001928 case PP_MACRO_DIRECTIVE_HISTORY:
1929 break;
1930
1931 case PP_MODULE_MACRO: {
Richard Smith713369b2015-04-23 20:40:50 +00001932 ModuleMacros.push_back(ModuleMacroRecord());
1933 auto &Info = ModuleMacros.back();
Richard Smithe56c8bc2015-04-22 00:26:11 +00001934 Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
1935 Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
Richard Smith713369b2015-04-23 20:40:50 +00001936 for (int I = 2, N = Record.size(); I != N; ++I)
1937 Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
Richard Smithd7329392015-04-21 21:46:32 +00001938 continue;
1939 }
1940
1941 default:
1942 Error("malformed block record in AST file");
1943 return;
1944 }
1945
1946 // We found the macro directive history; that's the last record
1947 // for this macro.
1948 break;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001949 }
1950
Richard Smithd7329392015-04-21 21:46:32 +00001951 // Module macros are listed in reverse dependency order.
Richard Smithe56c8bc2015-04-22 00:26:11 +00001952 {
1953 std::reverse(ModuleMacros.begin(), ModuleMacros.end());
Richard Smithe56c8bc2015-04-22 00:26:11 +00001954 llvm::SmallVector<ModuleMacro*, 8> Overrides;
Richard Smith713369b2015-04-23 20:40:50 +00001955 for (auto &MMR : ModuleMacros) {
Richard Smithe56c8bc2015-04-22 00:26:11 +00001956 Overrides.clear();
Richard Smith713369b2015-04-23 20:40:50 +00001957 for (unsigned ModID : MMR.Overrides) {
Richard Smithb8b2ed62015-04-23 18:18:26 +00001958 Module *Mod = getSubmodule(ModID);
1959 auto *Macro = PP.getModuleMacro(Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001960 assert(Macro && "missing definition for overridden macro");
Richard Smith5dbef922015-04-22 02:09:43 +00001961 Overrides.push_back(Macro);
Richard Smithe56c8bc2015-04-22 00:26:11 +00001962 }
1963
1964 bool Inserted = false;
Richard Smith713369b2015-04-23 20:40:50 +00001965 Module *Owner = getSubmodule(MMR.SubModID);
Richard Smith20e883e2015-04-29 23:20:19 +00001966 PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
Richard Smithd7329392015-04-21 21:46:32 +00001967 }
1968 }
1969
1970 // Don't read the directive history for a module; we don't have anywhere
1971 // to put it.
Manman Ren11f2a472016-08-18 17:42:15 +00001972 if (M.isModule())
Richard Smithd7329392015-04-21 21:46:32 +00001973 return;
1974
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001975 // Deserialize the macro directives history in reverse source-order.
Craig Toppera13603a2014-05-22 05:54:18 +00001976 MacroDirective *Latest = nullptr, *Earliest = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001977 unsigned Idx = 0, N = Record.size();
1978 while (Idx < N) {
Craig Toppera13603a2014-05-22 05:54:18 +00001979 MacroDirective *MD = nullptr;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001980 SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001981 MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
1982 switch (K) {
1983 case MacroDirective::MD_Define: {
Richard Smith713369b2015-04-23 20:40:50 +00001984 MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
Richard Smith3981b172015-04-30 02:16:23 +00001985 MD = PP.AllocateDefMacroDirective(MI, Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001986 break;
1987 }
Richard Smithdaa69e02014-07-25 04:40:03 +00001988 case MacroDirective::MD_Undefine: {
Richard Smith3981b172015-04-30 02:16:23 +00001989 MD = PP.AllocateUndefMacroDirective(Loc);
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001990 break;
Richard Smithdaa69e02014-07-25 04:40:03 +00001991 }
1992 case MacroDirective::MD_Visibility:
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +00001993 bool isPublic = Record[Idx++];
1994 MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
1995 break;
1996 }
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00001997
1998 if (!Latest)
1999 Latest = MD;
2000 if (Earliest)
2001 Earliest->setPrevious(MD);
2002 Earliest = MD;
2003 }
2004
Richard Smithd6e8c0d2015-05-04 19:58:00 +00002005 if (Latest)
Nico Weberfd870702016-12-09 17:32:52 +00002006 PP.setLoadedMacroDirective(II, Earliest, Latest);
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00002007}
2008
Argyrios Kyrtzidisce9b49e2014-03-14 02:26:27 +00002009ASTReader::InputFileInfo
2010ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002011 // Go find this input file.
2012 BitstreamCursor &Cursor = F.InputFilesCursor;
2013 SavedStreamPosition SavedPosition(Cursor);
2014 Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
2015
2016 unsigned Code = Cursor.ReadCode();
2017 RecordData Record;
2018 StringRef Blob;
2019
2020 unsigned Result = Cursor.readRecord(Code, Record, &Blob);
2021 assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
2022 "invalid record type for input file");
2023 (void)Result;
2024
2025 assert(Record[0] == ID && "Bogus stored ID or offset");
Richard Smitha8cfffa2015-11-26 02:04:16 +00002026 InputFileInfo R;
2027 R.StoredSize = static_cast<off_t>(Record[1]);
2028 R.StoredTime = static_cast<time_t>(Record[2]);
2029 R.Overridden = static_cast<bool>(Record[3]);
2030 R.Transient = static_cast<bool>(Record[4]);
Richard Smithf3f84612017-06-29 02:19:42 +00002031 R.TopLevelModuleMap = static_cast<bool>(Record[5]);
Richard Smitha8cfffa2015-11-26 02:04:16 +00002032 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 // If we didn't find the file, resolve it relative to the
2064 // original directory from which this AST file was created.
Manuel Klimek1b29b4f2017-07-25 10:22:06 +00002065 if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
2066 F.OriginalDir != F.BaseDirectory) {
2067 std::string Resolved = resolveFileRelativeToOriginalDir(
2068 Filename, F.OriginalDir, F.BaseDirectory);
Ben Langmuir198c1682014-03-07 07:27:49 +00002069 if (!Resolved.empty())
2070 File = FileMgr.getFile(Resolved);
2071 }
2072
2073 // For an overridden file, create a virtual file with the stored
2074 // size/timestamp.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002075 if ((Overridden || Transient) && File == nullptr)
Ben Langmuir198c1682014-03-07 07:27:49 +00002076 File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
Ben Langmuir198c1682014-03-07 07:27:49 +00002077
Craig Toppera13603a2014-05-22 05:54:18 +00002078 if (File == nullptr) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002079 if (Complain) {
2080 std::string ErrorStr = "could not find file '";
2081 ErrorStr += Filename;
Richard Smith68142212015-10-13 01:26:26 +00002082 ErrorStr += "' referenced by AST file '";
2083 ErrorStr += F.FileName;
2084 ErrorStr += "'";
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002085 Error(ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00002086 }
Ben Langmuir198c1682014-03-07 07:27:49 +00002087 // Record that we didn't find the file.
2088 F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
2089 return InputFile();
2090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002091
Ben Langmuir198c1682014-03-07 07:27:49 +00002092 // Check if there was a request to override the contents of the file
2093 // that was part of the precompiled header. Overridding such a file
2094 // can lead to problems when lexing using the source locations from the
2095 // PCH.
2096 SourceManager &SM = getSourceManager();
Richard Smith64daf7b2015-12-01 03:32:49 +00002097 // FIXME: Reject if the overrides are different.
2098 if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
Ben Langmuir198c1682014-03-07 07:27:49 +00002099 if (Complain)
2100 Error(diag::err_fe_pch_file_overridden, Filename);
2101 // After emitting the diagnostic, recover by disabling the override so
2102 // that the original file will be used.
Richard Smitha8cfffa2015-11-26 02:04:16 +00002103 //
2104 // FIXME: This recovery is just as broken as the original state; there may
2105 // be another precompiled module that's using the overridden contents, or
2106 // we might be half way through parsing it. Instead, we should treat the
2107 // overridden contents as belonging to a separate FileEntry.
Ben Langmuir198c1682014-03-07 07:27:49 +00002108 SM.disableFileContentsOverride(File);
2109 // The FileEntry is a virtual file entry with the size of the contents
2110 // that would override the original contents. Set it to the original's
2111 // size/time.
2112 FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
2113 StoredSize, StoredTime);
2114 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002115
Ben Langmuir198c1682014-03-07 07:27:49 +00002116 bool IsOutOfDate = false;
2117
2118 // For an overridden file, there is nothing to validate.
Richard Smith96fdab62014-10-28 16:24:08 +00002119 if (!Overridden && //
2120 (StoredSize != File->getSize() ||
Richard Smithe75ee0f2015-08-17 07:13:32 +00002121 (StoredTime && StoredTime != File->getModificationTime() &&
2122 !DisableValidation)
Ben Langmuir198c1682014-03-07 07:27:49 +00002123 )) {
2124 if (Complain) {
2125 // Build a list of the PCH imports that got us here (in reverse).
2126 SmallVector<ModuleFile *, 4> ImportStack(1, &F);
2127 while (ImportStack.back()->ImportedBy.size() > 0)
2128 ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
Ben Langmuire82630d2014-01-17 00:19:09 +00002129
Ben Langmuir198c1682014-03-07 07:27:49 +00002130 // The top-level PCH is stale.
2131 StringRef TopLevelPCHName(ImportStack.back()->FileName);
Manman Renc8c94152016-10-21 23:35:03 +00002132 unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
2133 if (DiagnosticKind == 0)
2134 Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
2135 else if (DiagnosticKind == 1)
2136 Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
2137 else
2138 Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
Ben Langmuire82630d2014-01-17 00:19:09 +00002139
Ben Langmuir198c1682014-03-07 07:27:49 +00002140 // Print the import stack.
2141 if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
2142 Diag(diag::note_pch_required_by)
2143 << Filename << ImportStack[0]->FileName;
2144 for (unsigned I = 1; I < ImportStack.size(); ++I)
Ben Langmuire82630d2014-01-17 00:19:09 +00002145 Diag(diag::note_pch_required_by)
Ben Langmuir198c1682014-03-07 07:27:49 +00002146 << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
Douglas Gregor7029ce12013-03-19 00:28:20 +00002147 }
2148
Ben Langmuir198c1682014-03-07 07:27:49 +00002149 if (!Diags.isDiagnosticInFlight())
2150 Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
Guy Benyei11169dd2012-12-18 14:30:41 +00002151 }
2152
Ben Langmuir198c1682014-03-07 07:27:49 +00002153 IsOutOfDate = true;
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 }
Richard Smitha8cfffa2015-11-26 02:04:16 +00002155 // FIXME: If the file is overridden and we've already opened it,
2156 // issue an error (or split it into a separate FileEntry).
Guy Benyei11169dd2012-12-18 14:30:41 +00002157
Richard Smitha8cfffa2015-11-26 02:04:16 +00002158 InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
Ben Langmuir198c1682014-03-07 07:27:49 +00002159
2160 // Note that we've loaded this input file.
2161 F.InputFilesLoaded[ID-1] = IF;
2162 return IF;
Guy Benyei11169dd2012-12-18 14:30:41 +00002163}
2164
Richard Smith7ed1bc92014-12-05 22:42:13 +00002165/// \brief If we are loading a relocatable PCH or module file, and the filename
2166/// is not an absolute path, add the system or module root to the beginning of
2167/// the file name.
2168void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
2169 // Resolve relative to the base directory, if we have one.
2170 if (!M.BaseDirectory.empty())
2171 return ResolveImportedPath(Filename, M.BaseDirectory);
Guy Benyei11169dd2012-12-18 14:30:41 +00002172}
2173
Richard Smith7ed1bc92014-12-05 22:42:13 +00002174void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002175 if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
2176 return;
2177
Richard Smith7ed1bc92014-12-05 22:42:13 +00002178 SmallString<128> Buffer;
2179 llvm::sys::path::append(Buffer, Prefix, Filename);
2180 Filename.assign(Buffer.begin(), Buffer.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00002181}
2182
Richard Smith0f99d6a2015-08-09 08:48:41 +00002183static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
2184 switch (ARR) {
2185 case ASTReader::Failure: return true;
2186 case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
2187 case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
2188 case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
2189 case ASTReader::ConfigurationMismatch:
2190 return !(Caps & ASTReader::ARR_ConfigurationMismatch);
2191 case ASTReader::HadErrors: return true;
2192 case ASTReader::Success: return false;
2193 }
2194
2195 llvm_unreachable("unknown ASTReadResult");
2196}
2197
Richard Smith0516b182015-09-08 19:40:14 +00002198ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
2199 BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
2200 bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002201 std::string &SuggestedPredefines) {
Richard Smith0516b182015-09-08 19:40:14 +00002202 if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
2203 return Failure;
2204
2205 // Read all of the records in the options block.
2206 RecordData Record;
2207 ASTReadResult Result = Success;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002208 while (true) {
Richard Smith0516b182015-09-08 19:40:14 +00002209 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002210
Richard Smith0516b182015-09-08 19:40:14 +00002211 switch (Entry.Kind) {
2212 case llvm::BitstreamEntry::Error:
2213 case llvm::BitstreamEntry::SubBlock:
2214 return Failure;
2215
2216 case llvm::BitstreamEntry::EndBlock:
2217 return Result;
2218
2219 case llvm::BitstreamEntry::Record:
2220 // The interesting case.
2221 break;
2222 }
2223
2224 // Read and process a record.
2225 Record.clear();
2226 switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
2227 case LANGUAGE_OPTIONS: {
2228 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2229 if (ParseLanguageOptions(Record, Complain, Listener,
2230 AllowCompatibleConfigurationMismatch))
2231 Result = ConfigurationMismatch;
2232 break;
2233 }
2234
2235 case TARGET_OPTIONS: {
2236 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2237 if (ParseTargetOptions(Record, Complain, Listener,
2238 AllowCompatibleConfigurationMismatch))
2239 Result = ConfigurationMismatch;
2240 break;
2241 }
2242
Richard Smith0516b182015-09-08 19:40:14 +00002243 case FILE_SYSTEM_OPTIONS: {
2244 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2245 if (!AllowCompatibleConfigurationMismatch &&
2246 ParseFileSystemOptions(Record, Complain, Listener))
2247 Result = ConfigurationMismatch;
2248 break;
2249 }
2250
2251 case HEADER_SEARCH_OPTIONS: {
2252 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2253 if (!AllowCompatibleConfigurationMismatch &&
2254 ParseHeaderSearchOptions(Record, Complain, Listener))
2255 Result = ConfigurationMismatch;
2256 break;
2257 }
2258
2259 case PREPROCESSOR_OPTIONS:
2260 bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
2261 if (!AllowCompatibleConfigurationMismatch &&
2262 ParsePreprocessorOptions(Record, Complain, Listener,
2263 SuggestedPredefines))
2264 Result = ConfigurationMismatch;
2265 break;
2266 }
2267 }
2268}
2269
Guy Benyei11169dd2012-12-18 14:30:41 +00002270ASTReader::ASTReadResult
2271ASTReader::ReadControlBlock(ModuleFile &F,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002272 SmallVectorImpl<ImportedModule> &Loaded,
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002273 const ModuleFile *ImportedBy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002275 BitstreamCursor &Stream = F.Stream;
Richard Smith8a308ec2015-11-05 00:54:55 +00002276 ASTReadResult Result = Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002277
2278 if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
2279 Error("malformed block record in AST file");
2280 return Failure;
2281 }
2282
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002283 // Lambda to read the unhashed control block the first time it's called.
2284 //
2285 // For PCM files, the unhashed control block cannot be read until after the
2286 // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
2287 // need to look ahead before reading the IMPORTS record. For consistency,
2288 // this block is always read somehow (see BitstreamEntry::EndBlock).
2289 bool HasReadUnhashedControlBlock = false;
2290 auto readUnhashedControlBlockOnce = [&]() {
2291 if (!HasReadUnhashedControlBlock) {
2292 HasReadUnhashedControlBlock = true;
2293 if (ASTReadResult Result =
2294 readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
2295 return Result;
2296 }
2297 return Success;
2298 };
2299
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 // Read all of the records and blocks in the control block.
2301 RecordData Record;
Richard Smitha1825302014-10-23 22:18:29 +00002302 unsigned NumInputs = 0;
2303 unsigned NumUserInputs = 0;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002304 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002305 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002306
Chris Lattnere7b154b2013-01-19 21:39:22 +00002307 switch (Entry.Kind) {
2308 case llvm::BitstreamEntry::Error:
2309 Error("malformed block record in AST file");
2310 return Failure;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002311 case llvm::BitstreamEntry::EndBlock: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002312 // Validate the module before returning. This call catches an AST with
2313 // no module name and no imports.
2314 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2315 return Result;
2316
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002317 // Validate input files.
2318 const HeaderSearchOptions &HSOpts =
2319 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Ben Langmuircb69b572014-03-07 06:40:32 +00002320
Richard Smitha1825302014-10-23 22:18:29 +00002321 // All user input files reside at the index range [0, NumUserInputs), and
Richard Smith0f99d6a2015-08-09 08:48:41 +00002322 // system input files reside at [NumUserInputs, NumInputs). For explicitly
2323 // loaded module files, ignore missing inputs.
Manman Ren11f2a472016-08-18 17:42:15 +00002324 if (!DisableValidation && F.Kind != MK_ExplicitModule &&
2325 F.Kind != MK_PrebuiltModule) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002326 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
Ben Langmuircb69b572014-03-07 06:40:32 +00002327
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002328 // If we are reading a module, we will create a verification timestamp,
2329 // so we verify all input files. Otherwise, verify only user input
2330 // files.
Ben Langmuircb69b572014-03-07 06:40:32 +00002331
2332 unsigned N = NumUserInputs;
2333 if (ValidateSystemInputs ||
Richard Smithe842a472014-10-22 02:05:46 +00002334 (HSOpts.ModulesValidateOncePerBuildSession &&
Ben Langmuiracb803e2014-11-10 22:13:10 +00002335 F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
Richard Smithe842a472014-10-22 02:05:46 +00002336 F.Kind == MK_ImplicitModule))
Ben Langmuircb69b572014-03-07 06:40:32 +00002337 N = NumInputs;
2338
Ben Langmuir3d4417c2014-02-07 17:31:11 +00002339 for (unsigned I = 0; I < N; ++I) {
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002340 InputFile IF = getInputFile(F, I+1, Complain);
2341 if (!IF.getFile() || IF.isOutOfDate())
Guy Benyei11169dd2012-12-18 14:30:41 +00002342 return OutOfDate;
Argyrios Kyrtzidis61c3d872013-03-01 03:26:04 +00002343 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002344 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002345
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002346 if (Listener)
Richard Smith216a3bd2015-08-13 17:57:10 +00002347 Listener->visitModuleFile(F.FileName, F.Kind);
Argyrios Kyrtzidis6d0753d2014-03-14 03:07:38 +00002348
Ben Langmuircb69b572014-03-07 06:40:32 +00002349 if (Listener && Listener->needsInputFileVisitation()) {
2350 unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
2351 : NumUserInputs;
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002352 for (unsigned I = 0; I < N; ++I) {
2353 bool IsSystem = I >= NumUserInputs;
2354 InputFileInfo FI = readInputFileInfo(F, I+1);
Richard Smith216a3bd2015-08-13 17:57:10 +00002355 Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
Manman Ren11f2a472016-08-18 17:42:15 +00002356 F.Kind == MK_ExplicitModule ||
2357 F.Kind == MK_PrebuiltModule);
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00002358 }
Ben Langmuircb69b572014-03-07 06:40:32 +00002359 }
2360
Richard Smith8a308ec2015-11-05 00:54:55 +00002361 return Result;
Dmitri Gribenkof430da42014-02-12 10:33:14 +00002362 }
2363
Chris Lattnere7b154b2013-01-19 21:39:22 +00002364 case llvm::BitstreamEntry::SubBlock:
2365 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 case INPUT_FILES_BLOCK_ID:
2367 F.InputFilesCursor = Stream;
2368 if (Stream.SkipBlock() || // Skip with the main cursor
2369 // Read the abbreviations
2370 ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
2371 Error("malformed block record in AST file");
2372 return Failure;
2373 }
2374 continue;
Richard Smith0516b182015-09-08 19:40:14 +00002375
2376 case OPTIONS_BLOCK_ID:
2377 // If we're reading the first module for this group, check its options
2378 // are compatible with ours. For modules it imports, no further checking
2379 // is required, because we checked them when we built it.
2380 if (Listener && !ImportedBy) {
2381 // Should we allow the configuration of the module file to differ from
2382 // the configuration of the current translation unit in a compatible
2383 // way?
2384 //
2385 // FIXME: Allow this for files explicitly specified with -include-pch.
2386 bool AllowCompatibleConfigurationMismatch =
Manman Ren11f2a472016-08-18 17:42:15 +00002387 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
Richard Smith0516b182015-09-08 19:40:14 +00002388
Richard Smith8a308ec2015-11-05 00:54:55 +00002389 Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
2390 AllowCompatibleConfigurationMismatch,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002391 *Listener, SuggestedPredefines);
Richard Smith0516b182015-09-08 19:40:14 +00002392 if (Result == Failure) {
2393 Error("malformed block record in AST file");
2394 return Result;
2395 }
2396
Richard Smith8a308ec2015-11-05 00:54:55 +00002397 if (DisableValidation ||
2398 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
2399 Result = Success;
2400
Ben Langmuir9b1e442e2016-02-11 18:54:02 +00002401 // If we can't load the module, exit early since we likely
2402 // will rebuild the module anyway. The stream may be in the
2403 // middle of a block.
2404 if (Result != Success)
Richard Smith0516b182015-09-08 19:40:14 +00002405 return Result;
2406 } else if (Stream.SkipBlock()) {
2407 Error("malformed block record in AST file");
2408 return Failure;
2409 }
2410 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002411
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002413 if (Stream.SkipBlock()) {
2414 Error("malformed block record in AST file");
2415 return Failure;
2416 }
2417 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00002418 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002419
Chris Lattnere7b154b2013-01-19 21:39:22 +00002420 case llvm::BitstreamEntry::Record:
2421 // The interesting case.
2422 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 }
2424
2425 // Read and process a record.
2426 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002427 StringRef Blob;
2428 switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 case METADATA: {
2430 if (Record[0] != VERSION_MAJOR && !DisableValidation) {
2431 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002432 Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
2433 : diag::err_pch_version_too_new);
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 return VersionMismatch;
2435 }
2436
Richard Smithe75ee0f2015-08-17 07:13:32 +00002437 bool hasErrors = Record[6];
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
2439 Diag(diag::err_pch_with_compiler_errors);
2440 return HadErrors;
2441 }
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002442 if (hasErrors) {
2443 Diags.ErrorOccurred = true;
2444 Diags.UncompilableErrorOccurred = true;
2445 Diags.UnrecoverableErrorOccurred = true;
2446 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002447
2448 F.RelocatablePCH = Record[4];
Richard Smith7ed1bc92014-12-05 22:42:13 +00002449 // Relative paths in a relocatable PCH are relative to our sysroot.
2450 if (F.RelocatablePCH)
2451 F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452
Richard Smithe75ee0f2015-08-17 07:13:32 +00002453 F.HasTimestamps = Record[5];
2454
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 const std::string &CurBranch = getClangFullRepositoryVersion();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002456 StringRef ASTBranch = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
2458 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00002459 Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
Guy Benyei11169dd2012-12-18 14:30:41 +00002460 return VersionMismatch;
2461 }
2462 break;
2463 }
2464
2465 case IMPORTS: {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002466 // Validate the AST before processing any imports (otherwise, untangling
2467 // them can be error-prone and expensive). A module will have a name and
2468 // will already have been validated, but this catches the PCH case.
2469 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2470 return Result;
2471
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002472 // Load each of the imported PCH files.
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 unsigned Idx = 0, N = Record.size();
2474 while (Idx < N) {
2475 // Read information about the AST file.
2476 ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
2477 // The import location will be the local one for now; we will adjust
2478 // all import locations of module imports after the global source
Richard Smithb22a1d12016-03-27 20:13:24 +00002479 // location info are setup, in ReadAST.
Guy Benyei11169dd2012-12-18 14:30:41 +00002480 SourceLocation ImportLoc =
Richard Smithb22a1d12016-03-27 20:13:24 +00002481 ReadUntranslatedSourceLocation(Record[Idx++]);
Douglas Gregor7029ce12013-03-19 00:28:20 +00002482 off_t StoredSize = (off_t)Record[Idx++];
2483 time_t StoredModTime = (time_t)Record[Idx++];
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002484 ASTFileSignature StoredSignature = {
2485 {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2486 (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
2487 (uint32_t)Record[Idx++]}}};
Boris Kolpackovd30446f2017-08-31 06:26:43 +00002488
2489 std::string ImportedName = ReadString(Record, Idx);
2490 std::string ImportedFile;
2491
2492 // For prebuilt and explicit modules first consult the file map for
2493 // an override. Note that here we don't search prebuilt module
2494 // directories, only the explicit name to file mappings. Also, we will
2495 // still verify the size/signature making sure it is essentially the
2496 // same file but perhaps in a different location.
2497 if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
2498 ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
2499 ImportedName, /*FileMapOnly*/ true);
2500
2501 if (ImportedFile.empty())
2502 ImportedFile = ReadPath(F, Record, Idx);
2503 else
2504 SkipPath(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00002505
Richard Smith0f99d6a2015-08-09 08:48:41 +00002506 // If our client can't cope with us being out of date, we can't cope with
2507 // our dependency being missing.
2508 unsigned Capabilities = ClientLoadCapabilities;
2509 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2510 Capabilities &= ~ARR_Missing;
2511
Guy Benyei11169dd2012-12-18 14:30:41 +00002512 // Load the AST file.
Richard Smith0f99d6a2015-08-09 08:48:41 +00002513 auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
2514 Loaded, StoredSize, StoredModTime,
2515 StoredSignature, Capabilities);
2516
2517 // If we diagnosed a problem, produce a backtrace.
2518 if (isDiagnosedResult(Result, Capabilities))
2519 Diag(diag::note_module_file_imported_by)
2520 << F.FileName << !F.ModuleName.empty() << F.ModuleName;
2521
2522 switch (Result) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002523 case Failure: return Failure;
2524 // If we have to ignore the dependency, we'll have to ignore this too.
Douglas Gregor2f1806e2013-03-19 00:38:50 +00002525 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00002526 case OutOfDate: return OutOfDate;
2527 case VersionMismatch: return VersionMismatch;
2528 case ConfigurationMismatch: return ConfigurationMismatch;
2529 case HadErrors: return HadErrors;
2530 case Success: break;
2531 }
2532 }
2533 break;
2534 }
2535
Guy Benyei11169dd2012-12-18 14:30:41 +00002536 case ORIGINAL_FILE:
2537 F.OriginalSourceFileID = FileID::get(Record[0]);
Chris Lattner0e6c9402013-01-20 02:38:54 +00002538 F.ActualOriginalSourceFileName = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
Richard Smith7ed1bc92014-12-05 22:42:13 +00002540 ResolveImportedPath(F, F.OriginalSourceFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002541 break;
2542
2543 case ORIGINAL_FILE_ID:
2544 F.OriginalSourceFileID = FileID::get(Record[0]);
2545 break;
2546
2547 case ORIGINAL_PCH_DIR:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002548 F.OriginalDir = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00002549 break;
2550
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002551 case MODULE_NAME:
2552 F.ModuleName = Blob;
Ben Langmuir4f5212a2014-04-14 22:12:44 +00002553 if (Listener)
2554 Listener->ReadModuleName(F.ModuleName);
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00002555
2556 // Validate the AST as soon as we have a name so we can exit early on
2557 // failure.
2558 if (ASTReadResult Result = readUnhashedControlBlockOnce())
2559 return Result;
2560
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002561 break;
2562
Richard Smith223d3f22014-12-06 03:21:08 +00002563 case MODULE_DIRECTORY: {
2564 assert(!F.ModuleName.empty() &&
2565 "MODULE_DIRECTORY found before MODULE_NAME");
2566 // If we've already loaded a module map file covering this module, we may
2567 // have a better path for it (relative to the current build).
2568 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
2569 if (M && M->Directory) {
2570 // If we're implicitly loading a module, the base directory can't
2571 // change between the build and use.
Manman Ren11f2a472016-08-18 17:42:15 +00002572 if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
Richard Smith223d3f22014-12-06 03:21:08 +00002573 const DirectoryEntry *BuildDir =
2574 PP.getFileManager().getDirectory(Blob);
2575 if (!BuildDir || BuildDir != M->Directory) {
2576 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
2577 Diag(diag::err_imported_module_relocated)
2578 << F.ModuleName << Blob << M->Directory->getName();
2579 return OutOfDate;
2580 }
2581 }
2582 F.BaseDirectory = M->Directory->getName();
2583 } else {
2584 F.BaseDirectory = Blob;
2585 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002586 break;
Richard Smith223d3f22014-12-06 03:21:08 +00002587 }
Richard Smith7ed1bc92014-12-05 22:42:13 +00002588
Ben Langmuirbeee15e2014-04-14 18:00:01 +00002589 case MODULE_MAP_FILE:
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00002590 if (ASTReadResult Result =
2591 ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
2592 return Result;
Ben Langmuir264ea152014-11-08 00:06:39 +00002593 break;
2594
Justin Bognerca9c0cc2015-06-21 20:32:36 +00002595 case INPUT_FILE_OFFSETS:
Richard Smitha1825302014-10-23 22:18:29 +00002596 NumInputs = Record[0];
2597 NumUserInputs = Record[1];
Justin Bogner4c183242015-06-21 20:32:40 +00002598 F.InputFileOffsets =
2599 (const llvm::support::unaligned_uint64_t *)Blob.data();
Richard Smitha1825302014-10-23 22:18:29 +00002600 F.InputFilesLoaded.resize(NumInputs);
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00002601 F.NumUserInputFiles = NumUserInputs;
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 break;
2603 }
2604 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002605}
2606
Ben Langmuir2c9af442014-04-10 17:57:43 +00002607ASTReader::ASTReadResult
2608ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002609 BitstreamCursor &Stream = F.Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002610
2611 if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
2612 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002613 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002614 }
2615
2616 // Read all of the records and blocks for the AST file.
2617 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00002618 while (true) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002619 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002620
Chris Lattnere7b154b2013-01-19 21:39:22 +00002621 switch (Entry.Kind) {
2622 case llvm::BitstreamEntry::Error:
2623 Error("error at end of module block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002624 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002625 case llvm::BitstreamEntry::EndBlock: {
Richard Smithc0fbba72013-04-03 22:49:41 +00002626 // Outside of C++, we do not store a lookup map for the translation unit.
2627 // Instead, mark it as needing a lookup map to be built if this module
2628 // contains any declarations lexically within it (which it always does!).
2629 // This usually has no cost, since we very rarely need the lookup map for
2630 // the translation unit outside C++.
Richard Smithdbafb6c2017-06-29 23:23:46 +00002631 if (ASTContext *Ctx = ContextObj) {
2632 DeclContext *DC = Ctx->getTranslationUnitDecl();
2633 if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
2634 DC->setMustBuildLookupTable();
2635 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002636
Ben Langmuir2c9af442014-04-10 17:57:43 +00002637 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00002638 }
Chris Lattnere7b154b2013-01-19 21:39:22 +00002639 case llvm::BitstreamEntry::SubBlock:
2640 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002641 case DECLTYPES_BLOCK_ID:
2642 // We lazily load the decls block, but we want to set up the
2643 // DeclsCursor cursor to point into it. Clone our current bitcode
2644 // cursor to it, enter the block and read the abbrevs in that block.
2645 // With the main cursor, we just skip over it.
2646 F.DeclsCursor = Stream;
2647 if (Stream.SkipBlock() || // Skip with the main cursor.
2648 // Read the abbrevs.
2649 ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
2650 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002651 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002652 }
2653 break;
Richard Smithb9eab6d2014-03-20 19:44:17 +00002654
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 case PREPROCESSOR_BLOCK_ID:
2656 F.MacroCursor = Stream;
2657 if (!PP.getExternalSource())
2658 PP.setExternalSource(this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002659
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 if (Stream.SkipBlock() ||
2661 ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
2662 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002663 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 }
2665 F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
2666 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002667
Guy Benyei11169dd2012-12-18 14:30:41 +00002668 case PREPROCESSOR_DETAIL_BLOCK_ID:
2669 F.PreprocessorDetailCursor = Stream;
2670 if (Stream.SkipBlock() ||
Chris Lattnere7b154b2013-01-19 21:39:22 +00002671 ReadBlockAbbrevs(F.PreprocessorDetailCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00002672 PREPROCESSOR_DETAIL_BLOCK_ID)) {
Chris Lattnere7b154b2013-01-19 21:39:22 +00002673 Error("malformed preprocessor detail record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002674 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002675 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002676 F.PreprocessorDetailStartOffset
Chris Lattnere7b154b2013-01-19 21:39:22 +00002677 = F.PreprocessorDetailCursor.GetCurrentBitNo();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002678
Guy Benyei11169dd2012-12-18 14:30:41 +00002679 if (!PP.getPreprocessingRecord())
2680 PP.createPreprocessingRecord();
2681 if (!PP.getPreprocessingRecord()->getExternalSource())
2682 PP.getPreprocessingRecord()->SetExternalSource(*this);
2683 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002684
Guy Benyei11169dd2012-12-18 14:30:41 +00002685 case SOURCE_MANAGER_BLOCK_ID:
2686 if (ReadSourceManagerBlock(F))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002687 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002689
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 case SUBMODULE_BLOCK_ID:
David Blaikie9ffe5a32017-01-30 05:00:26 +00002691 if (ASTReadResult Result =
2692 ReadSubmoduleBlock(F, ClientLoadCapabilities))
Ben Langmuir2c9af442014-04-10 17:57:43 +00002693 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002695
Guy Benyei11169dd2012-12-18 14:30:41 +00002696 case COMMENTS_BLOCK_ID: {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00002697 BitstreamCursor C = Stream;
Guy Benyei11169dd2012-12-18 14:30:41 +00002698 if (Stream.SkipBlock() ||
2699 ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
2700 Error("malformed comments block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002701 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002702 }
2703 CommentsCursors.push_back(std::make_pair(C, &F));
2704 break;
2705 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002706
Guy Benyei11169dd2012-12-18 14:30:41 +00002707 default:
Chris Lattnere7b154b2013-01-19 21:39:22 +00002708 if (Stream.SkipBlock()) {
2709 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002710 return Failure;
Chris Lattnere7b154b2013-01-19 21:39:22 +00002711 }
2712 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002713 }
2714 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002715
Chris Lattnere7b154b2013-01-19 21:39:22 +00002716 case llvm::BitstreamEntry::Record:
2717 // The interesting case.
2718 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 }
2720
2721 // Read and process a record.
2722 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00002723 StringRef Blob;
Richard Smithdbafb6c2017-06-29 23:23:46 +00002724 auto RecordType =
2725 (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
2726
2727 // If we're not loading an AST context, we don't care about most records.
2728 if (!ContextObj) {
2729 switch (RecordType) {
2730 case IDENTIFIER_TABLE:
2731 case IDENTIFIER_OFFSET:
2732 case INTERESTING_IDENTIFIERS:
2733 case STATISTICS:
2734 case PP_CONDITIONAL_STACK:
2735 case PP_COUNTER_VALUE:
2736 case SOURCE_LOCATION_OFFSETS:
2737 case MODULE_OFFSET_MAP:
2738 case SOURCE_MANAGER_LINE_TABLE:
2739 case SOURCE_LOCATION_PRELOADS:
2740 case PPD_ENTITIES_OFFSETS:
2741 case HEADER_SEARCH_TABLE:
2742 case IMPORTED_MODULES:
2743 case MACRO_OFFSET:
2744 break;
2745 default:
2746 continue;
2747 }
2748 }
2749
2750 switch (RecordType) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002751 default: // Default behavior: ignore.
2752 break;
2753
2754 case TYPE_OFFSET: {
2755 if (F.LocalNumTypes != 0) {
2756 Error("duplicate TYPE_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002757 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002759 F.TypeOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 F.LocalNumTypes = Record[0];
2761 unsigned LocalBaseTypeIndex = Record[1];
2762 F.BaseTypeIndex = getTotalNumTypes();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002763
Guy Benyei11169dd2012-12-18 14:30:41 +00002764 if (F.LocalNumTypes > 0) {
2765 // Introduce the global -> local mapping for types within this module.
2766 GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002767
Guy Benyei11169dd2012-12-18 14:30:41 +00002768 // Introduce the local -> global mapping for types within this module.
2769 F.TypeRemap.insertOrReplace(
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002770 std::make_pair(LocalBaseTypeIndex,
Guy Benyei11169dd2012-12-18 14:30:41 +00002771 F.BaseTypeIndex - LocalBaseTypeIndex));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002772
2773 TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 }
2775 break;
2776 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002777
Guy Benyei11169dd2012-12-18 14:30:41 +00002778 case DECL_OFFSET: {
2779 if (F.LocalNumDecls != 0) {
2780 Error("duplicate DECL_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002781 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002782 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002783 F.DeclOffsets = (const DeclOffset *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 F.LocalNumDecls = Record[0];
2785 unsigned LocalBaseDeclID = Record[1];
2786 F.BaseDeclID = getTotalNumDecls();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002787
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 if (F.LocalNumDecls > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002789 // Introduce the global -> local mapping for declarations within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 // module.
2791 GlobalDeclMap.insert(
2792 std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002793
Guy Benyei11169dd2012-12-18 14:30:41 +00002794 // Introduce the local -> global mapping for declarations within this
2795 // module.
2796 F.DeclRemap.insertOrReplace(
2797 std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002798
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 // Introduce the global -> local mapping for declarations within this
2800 // module.
2801 F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
Ben Langmuirfe971d92014-08-16 04:54:18 +00002802
Ben Langmuir52ca6782014-10-20 16:27:32 +00002803 DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
2804 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002805 break;
2806 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002807
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 case TU_UPDATE_LEXICAL: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00002809 DeclContext *TU = ContextObj->getTranslationUnitDecl();
Richard Smith82f8fcd2015-08-06 22:07:25 +00002810 LexicalContents Contents(
2811 reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
2812 Blob.data()),
2813 static_cast<unsigned int>(Blob.size() / 4));
2814 TULexicalDecls.push_back(std::make_pair(&F, Contents));
Guy Benyei11169dd2012-12-18 14:30:41 +00002815 TU->setHasExternalLexicalStorage(true);
2816 break;
2817 }
2818
2819 case UPDATE_VISIBLE: {
2820 unsigned Idx = 0;
2821 serialization::DeclID ID = ReadDeclID(F, Record, Idx);
Richard Smith0f4e2c42015-08-06 04:23:48 +00002822 auto *Data = (const unsigned char*)Blob.data();
Richard Smithd88a7f12015-09-01 20:35:42 +00002823 PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
Richard Smith0f4e2c42015-08-06 04:23:48 +00002824 // If we've already loaded the decl, perform the updates when we finish
2825 // loading this block.
2826 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00002827 PendingUpdateRecords.push_back(
2828 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 break;
2830 }
2831
2832 case IDENTIFIER_TABLE:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002833 F.IdentifierTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002834 if (Record[0]) {
Justin Bognerda4e6502014-04-14 16:34:29 +00002835 F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
2836 (const unsigned char *)F.IdentifierTableData + Record[0],
2837 (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
2838 (const unsigned char *)F.IdentifierTableData,
2839 ASTIdentifierLookupTrait(*this, F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002840
Guy Benyei11169dd2012-12-18 14:30:41 +00002841 PP.getIdentifierTable().setExternalIdentifierLookup(this);
2842 }
2843 break;
2844
2845 case IDENTIFIER_OFFSET: {
2846 if (F.LocalNumIdentifiers != 0) {
2847 Error("duplicate IDENTIFIER_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002848 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002849 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00002850 F.IdentifierOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 F.LocalNumIdentifiers = Record[0];
2852 unsigned LocalBaseIdentifierID = Record[1];
2853 F.BaseIdentifierID = getTotalNumIdentifiers();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002854
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 if (F.LocalNumIdentifiers > 0) {
2856 // Introduce the global -> local mapping for identifiers within this
2857 // module.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002858 GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
Guy Benyei11169dd2012-12-18 14:30:41 +00002859 &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002860
Guy Benyei11169dd2012-12-18 14:30:41 +00002861 // Introduce the local -> global mapping for identifiers within this
2862 // module.
2863 F.IdentifierRemap.insertOrReplace(
2864 std::make_pair(LocalBaseIdentifierID,
2865 F.BaseIdentifierID - LocalBaseIdentifierID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00002866
Ben Langmuir52ca6782014-10-20 16:27:32 +00002867 IdentifiersLoaded.resize(IdentifiersLoaded.size()
2868 + F.LocalNumIdentifiers);
2869 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002870 break;
2871 }
2872
Richard Smith33e0f7e2015-07-22 02:08:40 +00002873 case INTERESTING_IDENTIFIERS:
2874 F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
2875 break;
2876
Ben Langmuir332aafe2014-01-31 01:06:56 +00002877 case EAGERLY_DESERIALIZED_DECLS:
Richard Smith9e2341d2015-03-23 03:25:59 +00002878 // FIXME: Skip reading this record if our ASTConsumer doesn't care
2879 // about "interesting" decls (for instance, if we're building a module).
Guy Benyei11169dd2012-12-18 14:30:41 +00002880 for (unsigned I = 0, N = Record.size(); I != N; ++I)
Ben Langmuir332aafe2014-01-31 01:06:56 +00002881 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
Guy Benyei11169dd2012-12-18 14:30:41 +00002882 break;
2883
David Blaikie9ffe5a32017-01-30 05:00:26 +00002884 case MODULAR_CODEGEN_DECLS:
2885 // FIXME: Skip reading this record if our ASTConsumer doesn't care about
2886 // them (ie: if we're not codegenerating this module).
2887 if (F.Kind == MK_MainFile)
2888 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2889 EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
2890 break;
2891
Guy Benyei11169dd2012-12-18 14:30:41 +00002892 case SPECIAL_TYPES:
Douglas Gregor44180f82013-02-01 23:45:03 +00002893 if (SpecialTypes.empty()) {
2894 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2895 SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
2896 break;
2897 }
2898
2899 if (SpecialTypes.size() != Record.size()) {
2900 Error("invalid special-types record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002901 return Failure;
Douglas Gregor44180f82013-02-01 23:45:03 +00002902 }
2903
2904 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
2905 serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
2906 if (!SpecialTypes[I])
2907 SpecialTypes[I] = ID;
2908 // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
2909 // merge step?
2910 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 break;
2912
2913 case STATISTICS:
2914 TotalNumStatements += Record[0];
2915 TotalNumMacros += Record[1];
2916 TotalLexicalDeclContexts += Record[2];
2917 TotalVisibleDeclContexts += Record[3];
2918 break;
2919
2920 case UNUSED_FILESCOPED_DECLS:
2921 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2922 UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
2923 break;
2924
2925 case DELEGATING_CTORS:
2926 for (unsigned I = 0, N = Record.size(); I != N; ++I)
2927 DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
2928 break;
2929
2930 case WEAK_UNDECLARED_IDENTIFIERS:
2931 if (Record.size() % 4 != 0) {
2932 Error("invalid weak identifiers record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00002933 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002935
2936 // FIXME: Ignore weak undeclared identifiers from non-original PCH
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 // files. This isn't the way to do it :)
2938 WeakUndeclaredIdentifiers.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002939
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 // Translate the weak, undeclared identifiers into global IDs.
2941 for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
2942 WeakUndeclaredIdentifiers.push_back(
2943 getGlobalIdentifierID(F, Record[I++]));
2944 WeakUndeclaredIdentifiers.push_back(
2945 getGlobalIdentifierID(F, Record[I++]));
2946 WeakUndeclaredIdentifiers.push_back(
2947 ReadSourceLocation(F, Record, I).getRawEncoding());
2948 WeakUndeclaredIdentifiers.push_back(Record[I++]);
2949 }
2950 break;
2951
Guy Benyei11169dd2012-12-18 14:30:41 +00002952 case SELECTOR_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00002953 F.SelectorOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 F.LocalNumSelectors = Record[0];
2955 unsigned LocalBaseSelectorID = Record[1];
2956 F.BaseSelectorID = getTotalNumSelectors();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002957
Guy Benyei11169dd2012-12-18 14:30:41 +00002958 if (F.LocalNumSelectors > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002959 // Introduce the global -> local mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 // module.
2961 GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002962
2963 // Introduce the local -> global mapping for selectors within this
Guy Benyei11169dd2012-12-18 14:30:41 +00002964 // module.
2965 F.SelectorRemap.insertOrReplace(
2966 std::make_pair(LocalBaseSelectorID,
2967 F.BaseSelectorID - LocalBaseSelectorID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00002968
2969 SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
Guy Benyei11169dd2012-12-18 14:30:41 +00002970 }
2971 break;
2972 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002973
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 case METHOD_POOL:
Chris Lattner0e6c9402013-01-20 02:38:54 +00002975 F.SelectorLookupTableData = (const unsigned char *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 if (Record[0])
2977 F.SelectorLookupTable
2978 = ASTSelectorLookupTable::Create(
2979 F.SelectorLookupTableData + Record[0],
2980 F.SelectorLookupTableData,
2981 ASTSelectorLookupTrait(*this, F));
2982 TotalNumMethodPoolEntries += Record[1];
2983 break;
2984
2985 case REFERENCED_SELECTOR_POOL:
2986 if (!Record.empty()) {
2987 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00002988 ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
Guy Benyei11169dd2012-12-18 14:30:41 +00002989 Record[Idx++]));
2990 ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
2991 getRawEncoding());
2992 }
2993 }
2994 break;
2995
Erik Verbruggenb34c79f2017-05-30 11:54:55 +00002996 case PP_CONDITIONAL_STACK:
2997 if (!Record.empty()) {
2998 SmallVector<PPConditionalInfo, 4> ConditionalStack;
2999 for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
3000 auto Loc = ReadSourceLocation(F, Record, Idx);
3001 bool WasSkipping = Record[Idx++];
3002 bool FoundNonSkip = Record[Idx++];
3003 bool FoundElse = Record[Idx++];
3004 ConditionalStack.push_back(
3005 {Loc, WasSkipping, FoundNonSkip, FoundElse});
3006 }
3007 PP.setReplayablePreambleConditionalStack(ConditionalStack);
3008 }
3009 break;
3010
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 case PP_COUNTER_VALUE:
3012 if (!Record.empty() && Listener)
3013 Listener->ReadCounter(F, Record[0]);
3014 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003015
Guy Benyei11169dd2012-12-18 14:30:41 +00003016 case FILE_SORTED_DECLS:
Chris Lattner0e6c9402013-01-20 02:38:54 +00003017 F.FileSortedDecls = (const DeclID *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003018 F.NumFileSortedDecls = Record[0];
3019 break;
3020
3021 case SOURCE_LOCATION_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003022 F.SLocEntryOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 F.LocalNumSLocEntries = Record[0];
3024 unsigned SLocSpaceSize = Record[1];
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003025 std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
Ben Langmuir52ca6782014-10-20 16:27:32 +00003026 SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 SLocSpaceSize);
Richard Smith78d81ec2015-08-12 22:25:24 +00003028 if (!F.SLocEntryBaseID) {
3029 Error("ran out of source locations");
3030 break;
3031 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003032 // Make our entry in the range map. BaseID is negative and growing, so
3033 // we invert it. Because we invert it, though, we need the other end of
3034 // the range.
3035 unsigned RangeStart =
3036 unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
3037 GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
3038 F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
3039
3040 // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
3041 assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
3042 GlobalSLocOffsetMap.insert(
3043 std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
3044 - SLocSpaceSize,&F));
3045
3046 // Initialize the remapping table.
3047 // Invalid stays invalid.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003048 F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 // This module. Base was 2 when being compiled.
Richard Smithb9eab6d2014-03-20 19:44:17 +00003050 F.SLocRemap.insertOrReplace(std::make_pair(2U,
Guy Benyei11169dd2012-12-18 14:30:41 +00003051 static_cast<int>(F.SLocEntryBaseOffset - 2)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003052
Guy Benyei11169dd2012-12-18 14:30:41 +00003053 TotalNumSLocEntries += F.LocalNumSLocEntries;
3054 break;
3055 }
3056
Richard Smith37a93df2017-02-18 00:32:02 +00003057 case MODULE_OFFSET_MAP:
3058 F.ModuleOffsetMap = Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003060
3061 case SOURCE_MANAGER_LINE_TABLE:
3062 if (ParseLineTable(F, Record))
Ben Langmuir2c9af442014-04-10 17:57:43 +00003063 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003064 break;
3065
3066 case SOURCE_LOCATION_PRELOADS: {
3067 // Need to transform from the local view (1-based IDs) to the global view,
3068 // which is based off F.SLocEntryBaseID.
3069 if (!F.PreloadSLocEntries.empty()) {
3070 Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003071 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003072 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003073
Guy Benyei11169dd2012-12-18 14:30:41 +00003074 F.PreloadSLocEntries.swap(Record);
3075 break;
3076 }
3077
3078 case EXT_VECTOR_DECLS:
3079 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3080 ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
3081 break;
3082
3083 case VTABLE_USES:
3084 if (Record.size() % 3 != 0) {
3085 Error("Invalid VTABLE_USES record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003086 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003087 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003088
Guy Benyei11169dd2012-12-18 14:30:41 +00003089 // Later tables overwrite earlier ones.
3090 // FIXME: Modules will have some trouble with this. This is clearly not
3091 // the right way to do this.
3092 VTableUses.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003093
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
3095 VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
3096 VTableUses.push_back(
3097 ReadSourceLocation(F, Record, Idx).getRawEncoding());
3098 VTableUses.push_back(Record[Idx++]);
3099 }
3100 break;
3101
Guy Benyei11169dd2012-12-18 14:30:41 +00003102 case PENDING_IMPLICIT_INSTANTIATIONS:
3103 if (PendingInstantiations.size() % 2 != 0) {
3104 Error("Invalid existing PendingInstantiations");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003105 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 }
3107
3108 if (Record.size() % 2 != 0) {
3109 Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003110 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003111 }
3112
3113 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
3114 PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
3115 PendingInstantiations.push_back(
3116 ReadSourceLocation(F, Record, I).getRawEncoding());
3117 }
3118 break;
3119
3120 case SEMA_DECL_REFS:
Richard Smith96269c52016-09-29 22:49:46 +00003121 if (Record.size() != 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00003122 Error("Invalid SEMA_DECL_REFS block");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003123 return Failure;
Richard Smith3d8e97e2013-10-18 06:54:39 +00003124 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3126 SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3127 break;
3128
3129 case PPD_ENTITIES_OFFSETS: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003130 F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
3131 assert(Blob.size() % sizeof(PPEntityOffset) == 0);
3132 F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003133
3134 unsigned LocalBasePreprocessedEntityID = Record[0];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003135
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 unsigned StartingID;
3137 if (!PP.getPreprocessingRecord())
3138 PP.createPreprocessingRecord();
3139 if (!PP.getPreprocessingRecord()->getExternalSource())
3140 PP.getPreprocessingRecord()->SetExternalSource(*this);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003141 StartingID
Guy Benyei11169dd2012-12-18 14:30:41 +00003142 = PP.getPreprocessingRecord()
Ben Langmuir52ca6782014-10-20 16:27:32 +00003143 ->allocateLoadedEntities(F.NumPreprocessedEntities);
Guy Benyei11169dd2012-12-18 14:30:41 +00003144 F.BasePreprocessedEntityID = StartingID;
3145
3146 if (F.NumPreprocessedEntities > 0) {
3147 // Introduce the global -> local mapping for preprocessed entities in
3148 // this module.
3149 GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003150
Guy Benyei11169dd2012-12-18 14:30:41 +00003151 // Introduce the local -> global mapping for preprocessed entities in
3152 // this module.
3153 F.PreprocessedEntityRemap.insertOrReplace(
3154 std::make_pair(LocalBasePreprocessedEntityID,
3155 F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
3156 }
3157
3158 break;
3159 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003160
Guy Benyei11169dd2012-12-18 14:30:41 +00003161 case DECL_UPDATE_OFFSETS: {
3162 if (Record.size() % 2 != 0) {
3163 Error("invalid DECL_UPDATE_OFFSETS block in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003164 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003165 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00003166 for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
3167 GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
3168 DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
3169
3170 // If we've already loaded the decl, perform the updates when we finish
3171 // loading this block.
3172 if (Decl *D = GetExistingDecl(ID))
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00003173 PendingUpdateRecords.push_back(
3174 PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
Richard Smithcd45dbc2014-04-19 03:48:30 +00003175 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003176 break;
3177 }
3178
Guy Benyei11169dd2012-12-18 14:30:41 +00003179 case OBJC_CATEGORIES_MAP: {
3180 if (F.LocalNumObjCCategoriesInMap != 0) {
3181 Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003182 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003183 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003184
Guy Benyei11169dd2012-12-18 14:30:41 +00003185 F.LocalNumObjCCategoriesInMap = Record[0];
Chris Lattner0e6c9402013-01-20 02:38:54 +00003186 F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 break;
3188 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003189
Guy Benyei11169dd2012-12-18 14:30:41 +00003190 case OBJC_CATEGORIES:
3191 F.ObjCCategories.swap(Record);
3192 break;
Richard Smithc2bb8182015-03-24 06:36:48 +00003193
Guy Benyei11169dd2012-12-18 14:30:41 +00003194 case CUDA_SPECIAL_DECL_REFS:
3195 // Later tables overwrite earlier ones.
3196 // FIXME: Modules will have trouble with this.
3197 CUDASpecialDeclRefs.clear();
3198 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3199 CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
3200 break;
3201
3202 case HEADER_SEARCH_TABLE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00003203 F.HeaderFileInfoTableData = Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 F.LocalNumHeaderFileInfos = Record[1];
Guy Benyei11169dd2012-12-18 14:30:41 +00003205 if (Record[0]) {
3206 F.HeaderFileInfoTable
3207 = HeaderFileInfoLookupTable::Create(
3208 (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
3209 (const unsigned char *)F.HeaderFileInfoTableData,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003210 HeaderFileInfoTrait(*this, F,
Guy Benyei11169dd2012-12-18 14:30:41 +00003211 &PP.getHeaderSearchInfo(),
Chris Lattner0e6c9402013-01-20 02:38:54 +00003212 Blob.data() + Record[2]));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003213
Guy Benyei11169dd2012-12-18 14:30:41 +00003214 PP.getHeaderSearchInfo().SetExternalSource(this);
3215 if (!PP.getHeaderSearchInfo().getExternalLookup())
3216 PP.getHeaderSearchInfo().SetExternalLookup(this);
3217 }
3218 break;
3219 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003220
Guy Benyei11169dd2012-12-18 14:30:41 +00003221 case FP_PRAGMA_OPTIONS:
3222 // Later tables overwrite earlier ones.
3223 FPPragmaOptions.swap(Record);
3224 break;
3225
3226 case OPENCL_EXTENSIONS:
Yaxun Liu5b746652016-12-18 05:18:55 +00003227 for (unsigned I = 0, E = Record.size(); I != E; ) {
3228 auto Name = ReadString(Record, I);
3229 auto &Opt = OpenCLExtensions.OptMap[Name];
Yaxun Liucc2741c2016-12-18 06:35:06 +00003230 Opt.Supported = Record[I++] != 0;
3231 Opt.Enabled = Record[I++] != 0;
Yaxun Liu5b746652016-12-18 05:18:55 +00003232 Opt.Avail = Record[I++];
3233 Opt.Core = Record[I++];
3234 }
3235 break;
3236
3237 case OPENCL_EXTENSION_TYPES:
3238 for (unsigned I = 0, E = Record.size(); I != E;) {
3239 auto TypeID = static_cast<::TypeID>(Record[I++]);
3240 auto *Type = GetType(TypeID).getTypePtr();
3241 auto NumExt = static_cast<unsigned>(Record[I++]);
3242 for (unsigned II = 0; II != NumExt; ++II) {
3243 auto Ext = ReadString(Record, I);
3244 OpenCLTypeExtMap[Type].insert(Ext);
3245 }
3246 }
3247 break;
3248
3249 case OPENCL_EXTENSION_DECLS:
3250 for (unsigned I = 0, E = Record.size(); I != E;) {
3251 auto DeclID = static_cast<::DeclID>(Record[I++]);
3252 auto *Decl = GetDecl(DeclID);
3253 auto NumExt = static_cast<unsigned>(Record[I++]);
3254 for (unsigned II = 0; II != NumExt; ++II) {
3255 auto Ext = ReadString(Record, I);
3256 OpenCLDeclExtMap[Decl].insert(Ext);
3257 }
3258 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 break;
3260
3261 case TENTATIVE_DEFINITIONS:
3262 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3263 TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
3264 break;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003265
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 case KNOWN_NAMESPACES:
3267 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3268 KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
3269 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003270
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003271 case UNDEFINED_BUT_USED:
3272 if (UndefinedButUsed.size() % 2 != 0) {
3273 Error("Invalid existing UndefinedButUsed");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003274 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003275 }
3276
3277 if (Record.size() % 2 != 0) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003278 Error("invalid undefined-but-used record");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003279 return Failure;
Nick Lewycky8334af82013-01-26 00:35:08 +00003280 }
3281 for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00003282 UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
3283 UndefinedButUsed.push_back(
Nick Lewycky8334af82013-01-26 00:35:08 +00003284 ReadSourceLocation(F, Record, I).getRawEncoding());
3285 }
3286 break;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003287 case DELETE_EXPRS_TO_ANALYZE:
3288 for (unsigned I = 0, N = Record.size(); I != N;) {
3289 DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
3290 const uint64_t Count = Record[I++];
3291 DelayedDeleteExprs.push_back(Count);
3292 for (uint64_t C = 0; C < Count; ++C) {
3293 DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
3294 bool IsArrayForm = Record[I++] == 1;
3295 DelayedDeleteExprs.push_back(IsArrayForm);
3296 }
3297 }
3298 break;
Nick Lewycky8334af82013-01-26 00:35:08 +00003299
Guy Benyei11169dd2012-12-18 14:30:41 +00003300 case IMPORTED_MODULES: {
Manman Ren11f2a472016-08-18 17:42:15 +00003301 if (!F.isModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003302 // If we aren't loading a module (which has its own exports), make
3303 // all of the imported modules visible.
3304 // FIXME: Deal with macros-only imports.
Richard Smith56be7542014-03-21 00:33:59 +00003305 for (unsigned I = 0, N = Record.size(); I != N; /**/) {
3306 unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
3307 SourceLocation Loc = ReadSourceLocation(F, Record, I);
Graydon Hoare9c982442017-01-18 20:36:59 +00003308 if (GlobalID) {
Aaron Ballman4f45b712014-03-21 15:22:56 +00003309 ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
Graydon Hoare9c982442017-01-18 20:36:59 +00003310 if (DeserializationListener)
3311 DeserializationListener->ModuleImportRead(GlobalID, Loc);
3312 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003313 }
3314 }
3315 break;
3316 }
3317
Guy Benyei11169dd2012-12-18 14:30:41 +00003318 case MACRO_OFFSET: {
3319 if (F.LocalNumMacros != 0) {
3320 Error("duplicate MACRO_OFFSET record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00003321 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00003322 }
Chris Lattner0e6c9402013-01-20 02:38:54 +00003323 F.MacroOffsets = (const uint32_t *)Blob.data();
Guy Benyei11169dd2012-12-18 14:30:41 +00003324 F.LocalNumMacros = Record[0];
3325 unsigned LocalBaseMacroID = Record[1];
3326 F.BaseMacroID = getTotalNumMacros();
3327
3328 if (F.LocalNumMacros > 0) {
3329 // Introduce the global -> local mapping for macros within this module.
3330 GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
3331
3332 // Introduce the local -> global mapping for macros within this module.
3333 F.MacroRemap.insertOrReplace(
3334 std::make_pair(LocalBaseMacroID,
3335 F.BaseMacroID - LocalBaseMacroID));
Ben Langmuir52ca6782014-10-20 16:27:32 +00003336
3337 MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
Guy Benyei11169dd2012-12-18 14:30:41 +00003338 }
3339 break;
3340 }
3341
Richard Smithe40f2ba2013-08-07 21:41:30 +00003342 case LATE_PARSED_TEMPLATE: {
3343 LateParsedTemplates.append(Record.begin(), Record.end());
3344 break;
3345 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00003346
3347 case OPTIMIZE_PRAGMA_OPTIONS:
3348 if (Record.size() != 1) {
3349 Error("invalid pragma optimize record");
3350 return Failure;
3351 }
3352 OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
3353 break;
Nico Weber72889432014-09-06 01:25:55 +00003354
Nico Weber779355f2016-03-02 23:22:00 +00003355 case MSSTRUCT_PRAGMA_OPTIONS:
3356 if (Record.size() != 1) {
3357 Error("invalid pragma ms_struct record");
3358 return Failure;
3359 }
3360 PragmaMSStructState = Record[0];
3361 break;
3362
Nico Weber42932312016-03-03 00:17:35 +00003363 case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
3364 if (Record.size() != 2) {
3365 Error("invalid pragma ms_struct record");
3366 return Failure;
3367 }
3368 PragmaMSPointersToMembersState = Record[0];
3369 PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
3370 break;
3371
Nico Weber72889432014-09-06 01:25:55 +00003372 case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
3373 for (unsigned I = 0, N = Record.size(); I != N; ++I)
3374 UnusedLocalTypedefNameCandidates.push_back(
3375 getGlobalDeclID(F, Record[I]));
3376 break;
Justin Lebar67a78a62016-10-08 22:15:58 +00003377
3378 case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
3379 if (Record.size() != 1) {
3380 Error("invalid cuda pragma options record");
3381 return Failure;
3382 }
3383 ForceCUDAHostDeviceDepth = Record[0];
3384 break;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003385
3386 case PACK_PRAGMA_OPTIONS: {
3387 if (Record.size() < 3) {
3388 Error("invalid pragma pack record");
3389 return Failure;
3390 }
3391 PragmaPackCurrentValue = Record[0];
3392 PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
3393 unsigned NumStackEntries = Record[2];
3394 unsigned Idx = 3;
3395 // Reset the stack when importing a new module.
3396 PragmaPackStack.clear();
3397 for (unsigned I = 0; I < NumStackEntries; ++I) {
3398 PragmaPackStackEntry Entry;
3399 Entry.Value = Record[Idx++];
3400 Entry.Location = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz45b40142017-07-28 14:41:21 +00003401 Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00003402 PragmaPackStrings.push_back(ReadString(Record, Idx));
3403 Entry.SlotLabel = PragmaPackStrings.back();
3404 PragmaPackStack.push_back(Entry);
3405 }
3406 break;
3407 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003408 }
3409 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003410}
3411
Richard Smith37a93df2017-02-18 00:32:02 +00003412void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
3413 assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
3414
3415 // Additional remapping information.
3416 const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
3417 const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
3418 F.ModuleOffsetMap = StringRef();
3419
3420 // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
3421 if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
3422 F.SLocRemap.insert(std::make_pair(0U, 0));
3423 F.SLocRemap.insert(std::make_pair(2U, 1));
3424 }
3425
3426 // Continuous range maps we may be updating in our module.
3427 typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
3428 RemapBuilder;
3429 RemapBuilder SLocRemap(F.SLocRemap);
3430 RemapBuilder IdentifierRemap(F.IdentifierRemap);
3431 RemapBuilder MacroRemap(F.MacroRemap);
3432 RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
3433 RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
3434 RemapBuilder SelectorRemap(F.SelectorRemap);
3435 RemapBuilder DeclRemap(F.DeclRemap);
3436 RemapBuilder TypeRemap(F.TypeRemap);
3437
3438 while (Data < DataEnd) {
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003439 // FIXME: Looking up dependency modules by filename is horrible. Let's
3440 // start fixing this with prebuilt and explicit modules and see how it
3441 // goes...
Richard Smith37a93df2017-02-18 00:32:02 +00003442 using namespace llvm::support;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003443 ModuleKind Kind = static_cast<ModuleKind>(
3444 endian::readNext<uint8_t, little, unaligned>(Data));
Richard Smith37a93df2017-02-18 00:32:02 +00003445 uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
3446 StringRef Name = StringRef((const char*)Data, Len);
3447 Data += Len;
Boris Kolpackovd30446f2017-08-31 06:26:43 +00003448 ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
3449 ? ModuleMgr.lookupByModuleName(Name)
3450 : ModuleMgr.lookupByFileName(Name));
Richard Smith37a93df2017-02-18 00:32:02 +00003451 if (!OM) {
3452 std::string Msg =
3453 "SourceLocation remap refers to unknown module, cannot find ";
3454 Msg.append(Name);
3455 Error(Msg);
3456 return;
3457 }
3458
3459 uint32_t SLocOffset =
3460 endian::readNext<uint32_t, little, unaligned>(Data);
3461 uint32_t IdentifierIDOffset =
3462 endian::readNext<uint32_t, little, unaligned>(Data);
3463 uint32_t MacroIDOffset =
3464 endian::readNext<uint32_t, little, unaligned>(Data);
3465 uint32_t PreprocessedEntityIDOffset =
3466 endian::readNext<uint32_t, little, unaligned>(Data);
3467 uint32_t SubmoduleIDOffset =
3468 endian::readNext<uint32_t, little, unaligned>(Data);
3469 uint32_t SelectorIDOffset =
3470 endian::readNext<uint32_t, little, unaligned>(Data);
3471 uint32_t DeclIDOffset =
3472 endian::readNext<uint32_t, little, unaligned>(Data);
3473 uint32_t TypeIndexOffset =
3474 endian::readNext<uint32_t, little, unaligned>(Data);
3475
3476 uint32_t None = std::numeric_limits<uint32_t>::max();
3477
3478 auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
3479 RemapBuilder &Remap) {
3480 if (Offset != None)
3481 Remap.insert(std::make_pair(Offset,
3482 static_cast<int>(BaseOffset - Offset)));
3483 };
3484 mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
3485 mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
3486 mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
3487 mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
3488 PreprocessedEntityRemap);
3489 mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
3490 mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
3491 mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
3492 mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
3493
3494 // Global -> local mappings.
3495 F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
3496 }
3497}
3498
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003499ASTReader::ASTReadResult
3500ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
3501 const ModuleFile *ImportedBy,
3502 unsigned ClientLoadCapabilities) {
3503 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00003504 F.ModuleMapPath = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003505
3506 // Try to resolve ModuleName in the current header search context and
3507 // verify that it is found in the same module map file as we saved. If the
3508 // top-level AST file is a main file, skip this check because there is no
3509 // usable header search context.
3510 assert(!F.ModuleName.empty() &&
Richard Smithe842a472014-10-22 02:05:46 +00003511 "MODULE_NAME should come before MODULE_MAP_FILE");
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00003512 if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
Richard Smithe842a472014-10-22 02:05:46 +00003513 // An implicitly-loaded module file should have its module listed in some
3514 // module map file that we've already loaded.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003515 Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
Richard Smithe842a472014-10-22 02:05:46 +00003516 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
3517 const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
3518 if (!ModMap) {
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003519 assert(ImportedBy && "top-level import should be verified");
Richard Smith0f99d6a2015-08-09 08:48:41 +00003520 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
3521 if (auto *ASTFE = M ? M->getASTFile() : nullptr)
3522 // This module was defined by an imported (explicit) module.
3523 Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
3524 << ASTFE->getName();
3525 else
3526 // This module was built with a different module map.
3527 Diag(diag::err_imported_module_not_found)
3528 << F.ModuleName << F.FileName << ImportedBy->FileName
3529 << F.ModuleMapPath;
3530 }
3531 return OutOfDate;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003532 }
3533
Richard Smithe842a472014-10-22 02:05:46 +00003534 assert(M->Name == F.ModuleName && "found module with different name");
3535
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003536 // Check the primary module map file.
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003537 const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003538 if (StoredModMap == nullptr || StoredModMap != ModMap) {
3539 assert(ModMap && "found module is missing module map file");
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003540 assert(ImportedBy && "top-level import should be verified");
3541 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3542 Diag(diag::err_imported_module_modmap_changed)
3543 << F.ModuleName << ImportedBy->FileName
3544 << ModMap->getName() << F.ModuleMapPath;
3545 return OutOfDate;
3546 }
3547
3548 llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
3549 for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
3550 // FIXME: we should use input files rather than storing names.
Richard Smith7ed1bc92014-12-05 22:42:13 +00003551 std::string Filename = ReadPath(F, Record, Idx);
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00003552 const FileEntry *F =
3553 FileMgr.getFile(Filename, false, false);
3554 if (F == nullptr) {
3555 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3556 Error("could not find file '" + Filename +"' referenced by AST file");
3557 return OutOfDate;
3558 }
3559 AdditionalStoredMaps.insert(F);
3560 }
3561
3562 // Check any additional module map files (e.g. module.private.modulemap)
3563 // that are not in the pcm.
3564 if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
3565 for (const FileEntry *ModMap : *AdditionalModuleMaps) {
3566 // Remove files that match
3567 // Note: SmallPtrSet::erase is really remove
3568 if (!AdditionalStoredMaps.erase(ModMap)) {
3569 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3570 Diag(diag::err_module_different_modmap)
3571 << F.ModuleName << /*new*/0 << ModMap->getName();
3572 return OutOfDate;
3573 }
3574 }
3575 }
3576
3577 // Check any additional module map files that are in the pcm, but not
3578 // found in header search. Cases that match are already removed.
3579 for (const FileEntry *ModMap : AdditionalStoredMaps) {
3580 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
3581 Diag(diag::err_module_different_modmap)
3582 << F.ModuleName << /*not new*/1 << ModMap->getName();
3583 return OutOfDate;
3584 }
3585 }
3586
3587 if (Listener)
3588 Listener->ReadModuleMapFile(F.ModuleMapPath);
3589 return Success;
3590}
3591
3592
Douglas Gregorc1489562013-02-12 23:36:21 +00003593/// \brief Move the given method to the back of the global list of methods.
3594static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
3595 // Find the entry for this selector in the method pool.
3596 Sema::GlobalMethodPool::iterator Known
3597 = S.MethodPool.find(Method->getSelector());
3598 if (Known == S.MethodPool.end())
3599 return;
3600
3601 // Retrieve the appropriate method list.
3602 ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
3603 : Known->second.second;
3604 bool Found = false;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003605 for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003606 if (!Found) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003607 if (List->getMethod() == Method) {
Douglas Gregorc1489562013-02-12 23:36:21 +00003608 Found = true;
3609 } else {
3610 // Keep searching.
3611 continue;
3612 }
3613 }
3614
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003615 if (List->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003616 List->setMethod(List->getNext()->getMethod());
Douglas Gregorc1489562013-02-12 23:36:21 +00003617 else
Nico Weber2e0c8f72014-12-27 03:58:08 +00003618 List->setMethod(Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003619 }
3620}
3621
Richard Smithde711422015-04-23 21:20:19 +00003622void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
Richard Smith10434f32015-05-02 02:08:26 +00003623 assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
Richard Smith20e883e2015-04-29 23:20:19 +00003624 for (Decl *D : Names) {
Richard Smith90dc5252017-06-23 01:04:34 +00003625 bool wasHidden = D->isHidden();
3626 D->setVisibleDespiteOwningModule();
Guy Benyei11169dd2012-12-18 14:30:41 +00003627
Richard Smith49f906a2014-03-01 00:08:04 +00003628 if (wasHidden && SemaObj) {
3629 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
3630 moveMethodToBackOfGlobalList(*SemaObj, Method);
Douglas Gregorc1489562013-02-12 23:36:21 +00003631 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 }
3633 }
3634}
3635
Richard Smith49f906a2014-03-01 00:08:04 +00003636void ASTReader::makeModuleVisible(Module *Mod,
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00003637 Module::NameVisibilityKind NameVisibility,
Richard Smitha7e2cc62015-05-01 01:53:09 +00003638 SourceLocation ImportLoc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003639 llvm::SmallPtrSet<Module *, 4> Visited;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003640 SmallVector<Module *, 4> Stack;
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003641 Stack.push_back(Mod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003642 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003643 Mod = Stack.pop_back_val();
Guy Benyei11169dd2012-12-18 14:30:41 +00003644
3645 if (NameVisibility <= Mod->NameVisibility) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00003646 // This module already has this level of visibility (or greater), so
Guy Benyei11169dd2012-12-18 14:30:41 +00003647 // there is nothing more to do.
3648 continue;
3649 }
Richard Smith49f906a2014-03-01 00:08:04 +00003650
Guy Benyei11169dd2012-12-18 14:30:41 +00003651 if (!Mod->isAvailable()) {
3652 // Modules that aren't available cannot be made visible.
3653 continue;
3654 }
3655
3656 // Update the module's name visibility.
3657 Mod->NameVisibility = NameVisibility;
Richard Smith49f906a2014-03-01 00:08:04 +00003658
Guy Benyei11169dd2012-12-18 14:30:41 +00003659 // If we've already deserialized any names from this module,
3660 // mark them as visible.
3661 HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
3662 if (Hidden != HiddenNamesMap.end()) {
Richard Smith57721ac2014-07-21 04:10:40 +00003663 auto HiddenNames = std::move(*Hidden);
Guy Benyei11169dd2012-12-18 14:30:41 +00003664 HiddenNamesMap.erase(Hidden);
Richard Smithde711422015-04-23 21:20:19 +00003665 makeNamesVisible(HiddenNames.second, HiddenNames.first);
Richard Smith57721ac2014-07-21 04:10:40 +00003666 assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
3667 "making names visible added hidden names");
Guy Benyei11169dd2012-12-18 14:30:41 +00003668 }
Dmitri Gribenkoe9bcf5b2013-11-04 21:51:33 +00003669
Guy Benyei11169dd2012-12-18 14:30:41 +00003670 // Push any exported modules onto the stack to be marked as visible.
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003671 SmallVector<Module *, 16> Exports;
3672 Mod->getExportedModules(Exports);
3673 for (SmallVectorImpl<Module *>::iterator
3674 I = Exports.begin(), E = Exports.end(); I != E; ++I) {
3675 Module *Exported = *I;
David Blaikie82e95a32014-11-19 07:49:47 +00003676 if (Visited.insert(Exported).second)
Argyrios Kyrtzidis8739f7b2013-02-19 19:34:40 +00003677 Stack.push_back(Exported);
Guy Benyei11169dd2012-12-18 14:30:41 +00003678 }
3679 }
3680}
3681
Richard Smith6561f922016-09-12 21:06:40 +00003682/// We've merged the definition \p MergedDef into the existing definition
3683/// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
3684/// visible.
3685void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
3686 NamedDecl *MergedDef) {
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003687 // FIXME: This doesn't correctly handle the case where MergedDef is visible
3688 // in modules other than its owning module. We should instead give the
3689 // ASTContext a list of merged definitions for Def.
Richard Smith6561f922016-09-12 21:06:40 +00003690 if (Def->isHidden()) {
3691 // If MergedDef is visible or becomes visible, make the definition visible.
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003692 if (!MergedDef->isHidden())
Richard Smith90dc5252017-06-23 01:04:34 +00003693 Def->setVisibleDespiteOwningModule();
Benjamin Kramera72a70a2016-10-17 13:00:44 +00003694 else if (getContext().getLangOpts().ModulesLocalVisibility) {
3695 getContext().mergeDefinitionIntoModule(
3696 Def, MergedDef->getImportedOwningModule(),
3697 /*NotifyListeners*/ false);
3698 PendingMergedDefinitionsToDeduplicate.insert(Def);
3699 } else {
3700 auto SubmoduleID = MergedDef->getOwningModuleID();
3701 assert(SubmoduleID && "hidden definition in no module");
3702 HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
3703 }
Richard Smith6561f922016-09-12 21:06:40 +00003704 }
3705}
3706
Douglas Gregore060e572013-01-25 01:03:03 +00003707bool ASTReader::loadGlobalIndex() {
3708 if (GlobalIndex)
3709 return false;
3710
3711 if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
Richard Smithdbafb6c2017-06-29 23:23:46 +00003712 !PP.getLangOpts().Modules)
Douglas Gregore060e572013-01-25 01:03:03 +00003713 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003714
Douglas Gregore060e572013-01-25 01:03:03 +00003715 // Try to load the global index.
3716 TriedLoadingGlobalIndex = true;
3717 StringRef ModuleCachePath
3718 = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
3719 std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
Douglas Gregor7029ce12013-03-19 00:28:20 +00003720 = GlobalModuleIndex::readIndex(ModuleCachePath);
Douglas Gregore060e572013-01-25 01:03:03 +00003721 if (!Result.first)
3722 return true;
3723
3724 GlobalIndex.reset(Result.first);
Douglas Gregor7211ac12013-01-25 23:32:03 +00003725 ModuleMgr.setGlobalIndex(GlobalIndex.get());
Douglas Gregore060e572013-01-25 01:03:03 +00003726 return false;
3727}
3728
3729bool ASTReader::isGlobalIndexUnavailable() const {
Richard Smithdbafb6c2017-06-29 23:23:46 +00003730 return PP.getLangOpts().Modules && UseGlobalIndex &&
Douglas Gregore060e572013-01-25 01:03:03 +00003731 !hasGlobalIndex() && TriedLoadingGlobalIndex;
3732}
3733
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003734static void updateModuleTimestamp(ModuleFile &MF) {
3735 // Overwrite the timestamp file contents so that file's mtime changes.
3736 std::string TimestampFilename = MF.getTimestampFilename();
Rafael Espindoladae941a2014-08-25 18:17:04 +00003737 std::error_code EC;
3738 llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
3739 if (EC)
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003740 return;
3741 OS << "Timestamp file\n";
Alex Lorenz0bafa022017-06-02 10:36:56 +00003742 OS.close();
3743 OS.clear_error(); // Avoid triggering a fatal error.
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003744}
3745
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003746/// \brief Given a cursor at the start of an AST file, scan ahead and drop the
3747/// cursor into the start of the given block ID, returning false on success and
3748/// true on failure.
3749static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00003750 while (true) {
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003751 llvm::BitstreamEntry Entry = Cursor.advance();
3752 switch (Entry.Kind) {
3753 case llvm::BitstreamEntry::Error:
3754 case llvm::BitstreamEntry::EndBlock:
3755 return true;
3756
3757 case llvm::BitstreamEntry::Record:
3758 // Ignore top-level records.
3759 Cursor.skipRecord(Entry.ID);
3760 break;
3761
3762 case llvm::BitstreamEntry::SubBlock:
3763 if (Entry.ID == BlockID) {
3764 if (Cursor.EnterSubBlock(BlockID))
3765 return true;
3766 // Found it!
3767 return false;
3768 }
3769
3770 if (Cursor.SkipBlock())
3771 return true;
3772 }
3773 }
3774}
3775
Benjamin Kramer0772c422016-02-13 13:42:54 +00003776ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
Guy Benyei11169dd2012-12-18 14:30:41 +00003777 ModuleKind Type,
3778 SourceLocation ImportLoc,
Graydon Hoaree7196af2016-12-09 21:45:49 +00003779 unsigned ClientLoadCapabilities,
3780 SmallVectorImpl<ImportedSubmodule> *Imported) {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00003781 llvm::SaveAndRestore<SourceLocation>
3782 SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
3783
Richard Smithd1c46742014-04-30 02:24:17 +00003784 // Defer any pending actions until we get to the end of reading the AST file.
3785 Deserializing AnASTFile(this);
3786
Guy Benyei11169dd2012-12-18 14:30:41 +00003787 // Bump the generation number.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003788 unsigned PreviousGeneration = 0;
3789 if (ContextObj)
3790 PreviousGeneration = incrementGeneration(*ContextObj);
Guy Benyei11169dd2012-12-18 14:30:41 +00003791
3792 unsigned NumModules = ModuleMgr.size();
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003793 SmallVector<ImportedModule, 4> Loaded;
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00003794 switch (ASTReadResult ReadResult =
3795 ReadASTCore(FileName, Type, ImportLoc,
3796 /*ImportedBy=*/nullptr, Loaded, 0, 0,
3797 ASTFileSignature(), ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 case Failure:
Douglas Gregor7029ce12013-03-19 00:28:20 +00003799 case Missing:
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 case OutOfDate:
3801 case VersionMismatch:
3802 case ConfigurationMismatch:
Ben Langmuir9801b252014-06-20 00:24:56 +00003803 case HadErrors: {
3804 llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
3805 for (const ImportedModule &IM : Loaded)
3806 LoadedSet.insert(IM.Mod);
3807
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003808 ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
Richard Smithdbafb6c2017-06-29 23:23:46 +00003809 PP.getLangOpts().Modules
Duncan P. N. Exon Smith8e6bc1972017-01-28 23:02:12 +00003810 ? &PP.getHeaderSearchInfo().getModuleMap()
3811 : nullptr);
Douglas Gregore060e572013-01-25 01:03:03 +00003812
3813 // If we find that any modules are unusable, the global index is going
3814 // to be out-of-date. Just remove it.
3815 GlobalIndex.reset();
Craig Toppera13603a2014-05-22 05:54:18 +00003816 ModuleMgr.setGlobalIndex(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00003817 return ReadResult;
Ben Langmuir9801b252014-06-20 00:24:56 +00003818 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003819 case Success:
3820 break;
3821 }
3822
3823 // Here comes stuff that we only do once the entire chain is loaded.
3824
3825 // Load the AST blocks of all of the modules that we loaded.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003826 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3827 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 M != MEnd; ++M) {
3829 ModuleFile &F = *M->Mod;
3830
3831 // Read the AST block.
Ben Langmuir2c9af442014-04-10 17:57:43 +00003832 if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
3833 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00003834
Douglas Gregor6623e1f2015-11-03 18:33:07 +00003835 // Read the extension blocks.
3836 while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
3837 if (ASTReadResult Result = ReadExtensionBlock(F))
3838 return Result;
3839 }
3840
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003841 // Once read, set the ModuleFile bit base offset and update the size in
Guy Benyei11169dd2012-12-18 14:30:41 +00003842 // bits of all files we've seen.
3843 F.GlobalBitOffset = TotalModulesSizeInBits;
3844 TotalModulesSizeInBits += F.SizeInBits;
3845 GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003846
Guy Benyei11169dd2012-12-18 14:30:41 +00003847 // Preload SLocEntries.
3848 for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
3849 int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
3850 // Load it through the SourceManager and don't call ReadSLocEntry()
3851 // directly because the entry may have already been loaded in which case
3852 // calling ReadSLocEntry() directly would trigger an assertion in
3853 // SourceManager.
3854 SourceMgr.getLoadedSLocEntryByID(Index);
3855 }
Richard Smith33e0f7e2015-07-22 02:08:40 +00003856
Richard Smithea741482017-05-01 22:10:47 +00003857 // Map the original source file ID into the ID space of the current
3858 // compilation.
3859 if (F.OriginalSourceFileID.isValid()) {
3860 F.OriginalSourceFileID = FileID::get(
3861 F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
3862 }
3863
Richard Smith33e0f7e2015-07-22 02:08:40 +00003864 // Preload all the pending interesting identifiers by marking them out of
3865 // date.
3866 for (auto Offset : F.PreloadIdentifierOffsets) {
3867 const unsigned char *Data = reinterpret_cast<const unsigned char *>(
3868 F.IdentifierTableData + Offset);
3869
3870 ASTIdentifierLookupTrait Trait(*this, F);
3871 auto KeyDataLen = Trait.ReadKeyDataLength(Data);
3872 auto Key = Trait.ReadKey(Data, KeyDataLen.first);
Richard Smith79bf9202015-08-24 03:33:22 +00003873 auto &II = PP.getIdentifierTable().getOwn(Key);
3874 II.setOutOfDate(true);
3875
3876 // Mark this identifier as being from an AST file so that we can track
3877 // whether we need to serialize it.
Richard Smitheb4b58f62016-02-05 01:40:54 +00003878 markIdentifierFromAST(*this, II);
Richard Smith79bf9202015-08-24 03:33:22 +00003879
3880 // Associate the ID with the identifier so that the writer can reuse it.
3881 auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
3882 SetIdentifierInfo(ID, &II);
Richard Smith33e0f7e2015-07-22 02:08:40 +00003883 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003884 }
3885
Douglas Gregor603cd862013-03-22 18:50:14 +00003886 // Setup the import locations and notify the module manager that we've
3887 // committed to these module files.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003888 for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
3889 MEnd = Loaded.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 M != MEnd; ++M) {
3891 ModuleFile &F = *M->Mod;
Douglas Gregor603cd862013-03-22 18:50:14 +00003892
3893 ModuleMgr.moduleFileAccepted(&F);
3894
3895 // Set the import location.
Argyrios Kyrtzidis71c1af82013-02-01 16:36:14 +00003896 F.DirectImportLoc = ImportLoc;
Richard Smithb22a1d12016-03-27 20:13:24 +00003897 // FIXME: We assume that locations from PCH / preamble do not need
3898 // any translation.
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 if (!M->ImportedBy)
3900 F.ImportLoc = M->ImportLoc;
3901 else
Richard Smithb22a1d12016-03-27 20:13:24 +00003902 F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
Guy Benyei11169dd2012-12-18 14:30:41 +00003903 }
3904
Richard Smithdbafb6c2017-06-29 23:23:46 +00003905 if (!PP.getLangOpts().CPlusPlus ||
Manman Ren11f2a472016-08-18 17:42:15 +00003906 (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
3907 Type != MK_PrebuiltModule)) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00003908 // Mark all of the identifiers in the identifier table as being out of date,
3909 // so that various accessors know to check the loaded modules when the
3910 // identifier is used.
3911 //
3912 // For C++ modules, we don't need information on many identifiers (just
3913 // those that provide macros or are poisoned), so we mark all of
3914 // the interesting ones via PreloadIdentifierOffsets.
3915 for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
3916 IdEnd = PP.getIdentifierTable().end();
3917 Id != IdEnd; ++Id)
3918 Id->second->setOutOfDate(true);
3919 }
Manman Rena0f31a02016-04-29 19:04:05 +00003920 // Mark selectors as out of date.
3921 for (auto Sel : SelectorGeneration)
3922 SelectorOutOfDate[Sel.first] = true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003923
Guy Benyei11169dd2012-12-18 14:30:41 +00003924 // Resolve any unresolved module exports.
Douglas Gregorfb912652013-03-20 21:10:35 +00003925 for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
3926 UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
Guy Benyei11169dd2012-12-18 14:30:41 +00003927 SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
3928 Module *ResolvedMod = getSubmodule(GlobalID);
Douglas Gregorfb912652013-03-20 21:10:35 +00003929
3930 switch (Unresolved.Kind) {
3931 case UnresolvedModuleRef::Conflict:
3932 if (ResolvedMod) {
3933 Module::Conflict Conflict;
3934 Conflict.Other = ResolvedMod;
3935 Conflict.Message = Unresolved.String.str();
3936 Unresolved.Mod->Conflicts.push_back(Conflict);
3937 }
3938 continue;
3939
3940 case UnresolvedModuleRef::Import:
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 if (ResolvedMod)
Richard Smith38477db2015-05-02 00:45:56 +00003942 Unresolved.Mod->Imports.insert(ResolvedMod);
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00003944
Douglas Gregorfb912652013-03-20 21:10:35 +00003945 case UnresolvedModuleRef::Export:
3946 if (ResolvedMod || Unresolved.IsWildcard)
3947 Unresolved.Mod->Exports.push_back(
3948 Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
3949 continue;
3950 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003951 }
Douglas Gregorfb912652013-03-20 21:10:35 +00003952 UnresolvedModuleRefs.clear();
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003953
Graydon Hoaree7196af2016-12-09 21:45:49 +00003954 if (Imported)
3955 Imported->append(ImportedModules.begin(),
3956 ImportedModules.end());
3957
Daniel Jasperba7f2f72013-09-24 09:14:14 +00003958 // FIXME: How do we load the 'use'd modules? They may not be submodules.
3959 // Might be unnecessary as use declarations are only used to build the
3960 // module itself.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003961
Richard Smithdbafb6c2017-06-29 23:23:46 +00003962 if (ContextObj)
3963 InitializeContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00003964
Richard Smith3d8e97e2013-10-18 06:54:39 +00003965 if (SemaObj)
3966 UpdateSema();
3967
Guy Benyei11169dd2012-12-18 14:30:41 +00003968 if (DeserializationListener)
3969 DeserializationListener->ReaderInitialized(this);
3970
3971 ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
Yaron Keren8b563662015-10-03 10:46:20 +00003972 if (PrimaryModule.OriginalSourceFileID.isValid()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003973 // If this AST file is a precompiled preamble, then set the
3974 // preamble file ID of the source manager to the file source file
3975 // from which the preamble was built.
3976 if (Type == MK_Preamble) {
3977 SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
3978 } else if (Type == MK_MainFile) {
3979 SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
3980 }
3981 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00003982
Guy Benyei11169dd2012-12-18 14:30:41 +00003983 // For any Objective-C class definitions we have already loaded, make sure
3984 // that we load any additional categories.
Richard Smithdbafb6c2017-06-29 23:23:46 +00003985 if (ContextObj) {
3986 for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
3987 loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
3988 ObjCClassesLoaded[I],
3989 PreviousGeneration);
3990 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003991 }
Douglas Gregore060e572013-01-25 01:03:03 +00003992
Dmitri Gribenkof430da42014-02-12 10:33:14 +00003993 if (PP.getHeaderSearchInfo()
3994 .getHeaderSearchOpts()
3995 .ModulesValidateOncePerBuildSession) {
3996 // Now we are certain that the module and all modules it depends on are
3997 // up to date. Create or update timestamp files for modules that are
3998 // located in the module cache (not for PCH files that could be anywhere
3999 // in the filesystem).
4000 for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
4001 ImportedModule &M = Loaded[I];
Richard Smithe842a472014-10-22 02:05:46 +00004002 if (M.Mod->Kind == MK_ImplicitModule) {
Dmitri Gribenkof430da42014-02-12 10:33:14 +00004003 updateModuleTimestamp(*M.Mod);
4004 }
4005 }
4006 }
4007
Guy Benyei11169dd2012-12-18 14:30:41 +00004008 return Success;
4009}
4010
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004011static ASTFileSignature readASTFileSignature(StringRef PCH);
Ben Langmuir487ea142014-10-23 18:05:36 +00004012
Ben Langmuir70a1b812015-03-24 04:43:52 +00004013/// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
4014static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
Peter Collingbourne028eb5a2016-11-02 00:08:19 +00004015 return Stream.canSkipToPos(4) &&
4016 Stream.Read(8) == 'C' &&
Ben Langmuir70a1b812015-03-24 04:43:52 +00004017 Stream.Read(8) == 'P' &&
4018 Stream.Read(8) == 'C' &&
4019 Stream.Read(8) == 'H';
4020}
4021
Richard Smith0f99d6a2015-08-09 08:48:41 +00004022static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
4023 switch (Kind) {
4024 case MK_PCH:
4025 return 0; // PCH
4026 case MK_ImplicitModule:
4027 case MK_ExplicitModule:
Manman Ren11f2a472016-08-18 17:42:15 +00004028 case MK_PrebuiltModule:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004029 return 1; // module
4030 case MK_MainFile:
4031 case MK_Preamble:
4032 return 2; // main source file
4033 }
4034 llvm_unreachable("unknown module kind");
4035}
4036
Guy Benyei11169dd2012-12-18 14:30:41 +00004037ASTReader::ASTReadResult
4038ASTReader::ReadASTCore(StringRef FileName,
4039 ModuleKind Type,
4040 SourceLocation ImportLoc,
4041 ModuleFile *ImportedBy,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004042 SmallVectorImpl<ImportedModule> &Loaded,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004043 off_t ExpectedSize, time_t ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004044 ASTFileSignature ExpectedSignature,
Guy Benyei11169dd2012-12-18 14:30:41 +00004045 unsigned ClientLoadCapabilities) {
4046 ModuleFile *M;
Guy Benyei11169dd2012-12-18 14:30:41 +00004047 std::string ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004048 ModuleManager::AddModuleResult AddResult
4049 = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
Richard Smith053f6c62014-05-16 23:01:30 +00004050 getGeneration(), ExpectedSize, ExpectedModTime,
Ben Langmuir487ea142014-10-23 18:05:36 +00004051 ExpectedSignature, readASTFileSignature,
Douglas Gregor7029ce12013-03-19 00:28:20 +00004052 M, ErrorStr);
Guy Benyei11169dd2012-12-18 14:30:41 +00004053
Douglas Gregor7029ce12013-03-19 00:28:20 +00004054 switch (AddResult) {
4055 case ModuleManager::AlreadyLoaded:
4056 return Success;
4057
4058 case ModuleManager::NewlyLoaded:
4059 // Load module file below.
4060 break;
4061
4062 case ModuleManager::Missing:
Richard Smithe842a472014-10-22 02:05:46 +00004063 // The module file was missing; if the client can handle that, return
Douglas Gregor7029ce12013-03-19 00:28:20 +00004064 // it.
4065 if (ClientLoadCapabilities & ARR_Missing)
4066 return Missing;
4067
4068 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004069 Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
Adrian Prantlb3b5a732016-08-29 20:46:59 +00004070 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004071 << ErrorStr;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004072 return Failure;
4073
4074 case ModuleManager::OutOfDate:
4075 // We couldn't load the module file because it is out-of-date. If the
4076 // client can handle out-of-date, return it.
4077 if (ClientLoadCapabilities & ARR_OutOfDate)
4078 return OutOfDate;
4079
4080 // Otherwise, return an error.
Richard Smith0f99d6a2015-08-09 08:48:41 +00004081 Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
Adrian Prantl9a06a882016-08-29 20:46:56 +00004082 << FileName << !ErrorStr.empty()
Richard Smith0f99d6a2015-08-09 08:48:41 +00004083 << ErrorStr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004084 return Failure;
4085 }
4086
Douglas Gregor7029ce12013-03-19 00:28:20 +00004087 assert(M && "Missing module file");
Guy Benyei11169dd2012-12-18 14:30:41 +00004088
Guy Benyei11169dd2012-12-18 14:30:41 +00004089 ModuleFile &F = *M;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004090 BitstreamCursor &Stream = F.Stream;
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004091 Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
Adrian Prantlcbc368c2015-02-25 02:44:04 +00004092 F.SizeInBits = F.Buffer->getBufferSize() * 8;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004093
Guy Benyei11169dd2012-12-18 14:30:41 +00004094 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004095 if (!startsWithASTFileMagic(Stream)) {
Richard Smith0f99d6a2015-08-09 08:48:41 +00004096 Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
4097 << FileName;
Guy Benyei11169dd2012-12-18 14:30:41 +00004098 return Failure;
4099 }
4100
4101 // This is used for compatibility with older PCH formats.
4102 bool HaveReadControlBlock = false;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004103 while (true) {
Chris Lattnerefa77172013-01-20 00:00:22 +00004104 llvm::BitstreamEntry Entry = Stream.advance();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004105
Chris Lattnerefa77172013-01-20 00:00:22 +00004106 switch (Entry.Kind) {
4107 case llvm::BitstreamEntry::Error:
Chris Lattnerefa77172013-01-20 00:00:22 +00004108 case llvm::BitstreamEntry::Record:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004109 case llvm::BitstreamEntry::EndBlock:
Guy Benyei11169dd2012-12-18 14:30:41 +00004110 Error("invalid record at top-level of AST file");
4111 return Failure;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004112
Chris Lattnerefa77172013-01-20 00:00:22 +00004113 case llvm::BitstreamEntry::SubBlock:
4114 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004115 }
4116
Chris Lattnerefa77172013-01-20 00:00:22 +00004117 switch (Entry.ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004118 case CONTROL_BLOCK_ID:
4119 HaveReadControlBlock = true;
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004120 switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004121 case Success:
Richard Smith0f99d6a2015-08-09 08:48:41 +00004122 // Check that we didn't try to load a non-module AST file as a module.
4123 //
4124 // FIXME: Should we also perform the converse check? Loading a module as
4125 // a PCH file sort of works, but it's a bit wonky.
Manman Ren11f2a472016-08-18 17:42:15 +00004126 if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
4127 Type == MK_PrebuiltModule) &&
Richard Smith0f99d6a2015-08-09 08:48:41 +00004128 F.ModuleName.empty()) {
4129 auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
4130 if (Result != OutOfDate ||
4131 (ClientLoadCapabilities & ARR_OutOfDate) == 0)
4132 Diag(diag::err_module_file_not_module) << FileName;
4133 return Result;
4134 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004135 break;
4136
4137 case Failure: return Failure;
Douglas Gregor7029ce12013-03-19 00:28:20 +00004138 case Missing: return Missing;
Guy Benyei11169dd2012-12-18 14:30:41 +00004139 case OutOfDate: return OutOfDate;
4140 case VersionMismatch: return VersionMismatch;
4141 case ConfigurationMismatch: return ConfigurationMismatch;
4142 case HadErrors: return HadErrors;
4143 }
4144 break;
Richard Smithf8c32552015-09-02 17:45:54 +00004145
Guy Benyei11169dd2012-12-18 14:30:41 +00004146 case AST_BLOCK_ID:
4147 if (!HaveReadControlBlock) {
4148 if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
Dmitri Gribenko2228cd32014-02-11 15:40:09 +00004149 Diag(diag::err_pch_version_too_old);
Guy Benyei11169dd2012-12-18 14:30:41 +00004150 return VersionMismatch;
4151 }
4152
4153 // Record that we've loaded this module.
4154 Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
4155 return Success;
4156
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004157 case UNHASHED_CONTROL_BLOCK_ID:
4158 // This block is handled using look-ahead during ReadControlBlock. We
4159 // shouldn't get here!
4160 Error("malformed block record in AST file");
4161 return Failure;
4162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 default:
4164 if (Stream.SkipBlock()) {
4165 Error("malformed block record in AST file");
4166 return Failure;
4167 }
4168 break;
4169 }
4170 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004171
4172 return Success;
4173}
4174
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004175ASTReader::ASTReadResult
4176ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
4177 unsigned ClientLoadCapabilities) {
4178 const HeaderSearchOptions &HSOpts =
4179 PP.getHeaderSearchInfo().getHeaderSearchOpts();
4180 bool AllowCompatibleConfigurationMismatch =
4181 F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
4182
4183 ASTReadResult Result = readUnhashedControlBlockImpl(
4184 &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
4185 Listener.get(),
4186 WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
4187
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004188 // If F was directly imported by another module, it's implicitly validated by
4189 // the importing module.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004190 if (DisableValidation || WasImportedBy ||
4191 (AllowConfigurationMismatch && Result == ConfigurationMismatch))
4192 return Success;
4193
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004194 if (Result == Failure) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004195 Error("malformed block record in AST file");
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004196 return Failure;
4197 }
4198
4199 if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
4200 // If this module has already been finalized in the PCMCache, we're stuck
4201 // with it; we can only load a single version of each module.
4202 //
4203 // This can happen when a module is imported in two contexts: in one, as a
4204 // user module; in another, as a system module (due to an import from
4205 // another module marked with the [system] flag). It usually indicates a
4206 // bug in the module map: this module should also be marked with [system].
4207 //
4208 // If -Wno-system-headers (the default), and the first import is as a
4209 // system module, then validation will fail during the as-user import,
4210 // since -Werror flags won't have been validated. However, it's reasonable
4211 // to treat this consistently as a system module.
4212 //
4213 // If -Wsystem-headers, the PCM on disk was built with
4214 // -Wno-system-headers, and the first import is as a user module, then
4215 // validation will fail during the as-system import since the PCM on disk
4216 // doesn't guarantee that -Werror was respected. However, the -Werror
4217 // flags were checked during the initial as-user import.
4218 if (PCMCache.isBufferFinal(F.FileName)) {
4219 Diag(diag::warn_module_system_bit_conflict) << F.FileName;
4220 return Success;
4221 }
4222 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004223
4224 return Result;
4225}
4226
4227ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
4228 ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
4229 bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
4230 bool ValidateDiagnosticOptions) {
4231 // Initialize a stream.
4232 BitstreamCursor Stream(StreamData);
4233
4234 // Sniff for the signature.
4235 if (!startsWithASTFileMagic(Stream))
4236 return Failure;
4237
4238 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4239 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4240 return Failure;
4241
4242 // Read all of the records in the options block.
4243 RecordData Record;
4244 ASTReadResult Result = Success;
4245 while (1) {
4246 llvm::BitstreamEntry Entry = Stream.advance();
4247
4248 switch (Entry.Kind) {
4249 case llvm::BitstreamEntry::Error:
4250 case llvm::BitstreamEntry::SubBlock:
4251 return Failure;
4252
4253 case llvm::BitstreamEntry::EndBlock:
4254 return Result;
4255
4256 case llvm::BitstreamEntry::Record:
4257 // The interesting case.
4258 break;
4259 }
4260
4261 // Read and process a record.
4262 Record.clear();
4263 switch (
4264 (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
4265 case SIGNATURE: {
4266 if (F)
4267 std::copy(Record.begin(), Record.end(), F->Signature.data());
4268 break;
4269 }
4270 case DIAGNOSTIC_OPTIONS: {
4271 bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
4272 if (Listener && ValidateDiagnosticOptions &&
4273 !AllowCompatibleConfigurationMismatch &&
4274 ParseDiagnosticOptions(Record, Complain, *Listener))
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00004275 Result = OutOfDate; // Don't return early. Read the signature.
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004276 break;
4277 }
4278 case DIAG_PRAGMA_MAPPINGS:
4279 if (!F)
4280 break;
4281 if (F->PragmaDiagMappings.empty())
4282 F->PragmaDiagMappings.swap(Record);
4283 else
4284 F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
4285 Record.begin(), Record.end());
4286 break;
4287 }
4288 }
4289}
4290
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004291/// Parse a record and blob containing module file extension metadata.
4292static bool parseModuleFileExtensionMetadata(
4293 const SmallVectorImpl<uint64_t> &Record,
4294 StringRef Blob,
4295 ModuleFileExtensionMetadata &Metadata) {
4296 if (Record.size() < 4) return true;
4297
4298 Metadata.MajorVersion = Record[0];
4299 Metadata.MinorVersion = Record[1];
4300
4301 unsigned BlockNameLen = Record[2];
4302 unsigned UserInfoLen = Record[3];
4303
4304 if (BlockNameLen + UserInfoLen > Blob.size()) return true;
4305
4306 Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
4307 Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
4308 Blob.data() + BlockNameLen + UserInfoLen);
4309 return false;
4310}
4311
4312ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
4313 BitstreamCursor &Stream = F.Stream;
4314
4315 RecordData Record;
4316 while (true) {
4317 llvm::BitstreamEntry Entry = Stream.advance();
4318 switch (Entry.Kind) {
4319 case llvm::BitstreamEntry::SubBlock:
4320 if (Stream.SkipBlock())
4321 return Failure;
4322
4323 continue;
4324
4325 case llvm::BitstreamEntry::EndBlock:
4326 return Success;
4327
4328 case llvm::BitstreamEntry::Error:
4329 return HadErrors;
4330
4331 case llvm::BitstreamEntry::Record:
4332 break;
4333 }
4334
4335 Record.clear();
4336 StringRef Blob;
4337 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4338 switch (RecCode) {
4339 case EXTENSION_METADATA: {
4340 ModuleFileExtensionMetadata Metadata;
4341 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4342 return Failure;
4343
4344 // Find a module file extension with this block name.
4345 auto Known = ModuleFileExtensions.find(Metadata.BlockName);
4346 if (Known == ModuleFileExtensions.end()) break;
4347
4348 // Form a reader.
4349 if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
4350 F, Stream)) {
4351 F.ExtensionReaders.push_back(std::move(Reader));
4352 }
4353
4354 break;
4355 }
4356 }
4357 }
4358
4359 return Success;
Guy Benyei11169dd2012-12-18 14:30:41 +00004360}
4361
Richard Smitha7e2cc62015-05-01 01:53:09 +00004362void ASTReader::InitializeContext() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00004363 assert(ContextObj && "no context to initialize");
4364 ASTContext &Context = *ContextObj;
4365
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 // If there's a listener, notify them that we "read" the translation unit.
4367 if (DeserializationListener)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004368 DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 Context.getTranslationUnitDecl());
4370
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 // FIXME: Find a better way to deal with collisions between these
4372 // built-in types. Right now, we just ignore the problem.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004373
Guy Benyei11169dd2012-12-18 14:30:41 +00004374 // Load the special types.
4375 if (SpecialTypes.size() >= NumSpecialTypeIDs) {
4376 if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
4377 if (!Context.CFConstantStringTypeDecl)
4378 Context.setCFConstantStringType(GetType(String));
4379 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004380
Guy Benyei11169dd2012-12-18 14:30:41 +00004381 if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
4382 QualType FileType = GetType(File);
4383 if (FileType.isNull()) {
4384 Error("FILE type is NULL");
4385 return;
4386 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004387
Guy Benyei11169dd2012-12-18 14:30:41 +00004388 if (!Context.FILEDecl) {
4389 if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
4390 Context.setFILEDecl(Typedef->getDecl());
4391 else {
4392 const TagType *Tag = FileType->getAs<TagType>();
4393 if (!Tag) {
4394 Error("Invalid FILE type in AST file");
4395 return;
4396 }
4397 Context.setFILEDecl(Tag->getDecl());
4398 }
4399 }
4400 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004401
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
4403 QualType Jmp_bufType = GetType(Jmp_buf);
4404 if (Jmp_bufType.isNull()) {
4405 Error("jmp_buf type is NULL");
4406 return;
4407 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004408
Guy Benyei11169dd2012-12-18 14:30:41 +00004409 if (!Context.jmp_bufDecl) {
4410 if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
4411 Context.setjmp_bufDecl(Typedef->getDecl());
4412 else {
4413 const TagType *Tag = Jmp_bufType->getAs<TagType>();
4414 if (!Tag) {
4415 Error("Invalid jmp_buf type in AST file");
4416 return;
4417 }
4418 Context.setjmp_bufDecl(Tag->getDecl());
4419 }
4420 }
4421 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004422
Guy Benyei11169dd2012-12-18 14:30:41 +00004423 if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
4424 QualType Sigjmp_bufType = GetType(Sigjmp_buf);
4425 if (Sigjmp_bufType.isNull()) {
4426 Error("sigjmp_buf type is NULL");
4427 return;
4428 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004429
Guy Benyei11169dd2012-12-18 14:30:41 +00004430 if (!Context.sigjmp_bufDecl) {
4431 if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
4432 Context.setsigjmp_bufDecl(Typedef->getDecl());
4433 else {
4434 const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
4435 assert(Tag && "Invalid sigjmp_buf type in AST file");
4436 Context.setsigjmp_bufDecl(Tag->getDecl());
4437 }
4438 }
4439 }
4440
4441 if (unsigned ObjCIdRedef
4442 = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
4443 if (Context.ObjCIdRedefinitionType.isNull())
4444 Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
4445 }
4446
4447 if (unsigned ObjCClassRedef
4448 = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
4449 if (Context.ObjCClassRedefinitionType.isNull())
4450 Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
4451 }
4452
4453 if (unsigned ObjCSelRedef
4454 = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
4455 if (Context.ObjCSelRedefinitionType.isNull())
4456 Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
4457 }
4458
4459 if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
4460 QualType Ucontext_tType = GetType(Ucontext_t);
4461 if (Ucontext_tType.isNull()) {
4462 Error("ucontext_t type is NULL");
4463 return;
4464 }
4465
4466 if (!Context.ucontext_tDecl) {
4467 if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
4468 Context.setucontext_tDecl(Typedef->getDecl());
4469 else {
4470 const TagType *Tag = Ucontext_tType->getAs<TagType>();
4471 assert(Tag && "Invalid ucontext_t type in AST file");
4472 Context.setucontext_tDecl(Tag->getDecl());
4473 }
4474 }
4475 }
4476 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004477
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 ReadPragmaDiagnosticMappings(Context.getDiagnostics());
4479
4480 // If there were any CUDA special declarations, deserialize them.
4481 if (!CUDASpecialDeclRefs.empty()) {
4482 assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
4483 Context.setcudaConfigureCallDecl(
4484 cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
4485 }
Richard Smith56be7542014-03-21 00:33:59 +00004486
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 // Re-export any modules that were imported by a non-module AST file.
Richard Smitha7e2cc62015-05-01 01:53:09 +00004488 // FIXME: This does not make macro-only imports visible again.
Richard Smith56be7542014-03-21 00:33:59 +00004489 for (auto &Import : ImportedModules) {
Richard Smitha7e2cc62015-05-01 01:53:09 +00004490 if (Module *Imported = getSubmodule(Import.ID)) {
Argyrios Kyrtzidis125df052013-02-01 16:36:12 +00004491 makeModuleVisible(Imported, Module::AllVisible,
Richard Smitha7e2cc62015-05-01 01:53:09 +00004492 /*ImportLoc=*/Import.ImportLoc);
Ben Langmuir6d25fdc2016-02-11 17:04:42 +00004493 if (Import.ImportLoc.isValid())
4494 PP.makeModuleVisible(Imported, Import.ImportLoc);
4495 // FIXME: should we tell Sema to make the module visible too?
Richard Smitha7e2cc62015-05-01 01:53:09 +00004496 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004497 }
4498 ImportedModules.clear();
4499}
4500
4501void ASTReader::finalizeForWriting() {
Richard Smithde711422015-04-23 21:20:19 +00004502 // Nothing to do for now.
Guy Benyei11169dd2012-12-18 14:30:41 +00004503}
4504
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004505/// \brief Reads and return the signature record from \p PCH's control block, or
4506/// else returns 0.
4507static ASTFileSignature readASTFileSignature(StringRef PCH) {
4508 BitstreamCursor Stream(PCH);
Ben Langmuir70a1b812015-03-24 04:43:52 +00004509 if (!startsWithASTFileMagic(Stream))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004510 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004511
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004512 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4513 if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
4514 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004515
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004516 // Scan for SIGNATURE inside the diagnostic options block.
Ben Langmuir487ea142014-10-23 18:05:36 +00004517 ASTReader::RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004518 while (true) {
Ben Langmuir487ea142014-10-23 18:05:36 +00004519 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Simon Pilgrim0b33f112016-11-16 16:11:08 +00004520 if (Entry.Kind != llvm::BitstreamEntry::Record)
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004521 return ASTFileSignature();
Ben Langmuir487ea142014-10-23 18:05:36 +00004522
4523 Record.clear();
4524 StringRef Blob;
4525 if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004526 return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
4527 (uint32_t)Record[3], (uint32_t)Record[4]}}};
Ben Langmuir487ea142014-10-23 18:05:36 +00004528 }
4529}
4530
Guy Benyei11169dd2012-12-18 14:30:41 +00004531/// \brief Retrieve the name of the original source file name
4532/// directly from the AST file, without actually loading the AST
4533/// file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004534std::string ASTReader::getOriginalSourceFile(
4535 const std::string &ASTFileName, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004536 const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004537 // Open the AST file.
Benjamin Kramera8857962014-10-26 22:44:13 +00004538 auto Buffer = FileMgr.getBufferForFile(ASTFileName);
Guy Benyei11169dd2012-12-18 14:30:41 +00004539 if (!Buffer) {
Benjamin Kramera8857962014-10-26 22:44:13 +00004540 Diags.Report(diag::err_fe_unable_to_read_pch_file)
4541 << ASTFileName << Buffer.getError().message();
Guy Benyei11169dd2012-12-18 14:30:41 +00004542 return std::string();
4543 }
4544
4545 // Initialize the stream
Peter Collingbourne77c89b62016-11-08 04:17:11 +00004546 BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
Guy Benyei11169dd2012-12-18 14:30:41 +00004547
4548 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004549 if (!startsWithASTFileMagic(Stream)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004550 Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
4551 return std::string();
4552 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004553
Chris Lattnere7b154b2013-01-19 21:39:22 +00004554 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004555 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004556 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4557 return std::string();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004558 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004559
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004560 // Scan for ORIGINAL_FILE inside the control block.
4561 RecordData Record;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004562 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004563 llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Chris Lattnere7b154b2013-01-19 21:39:22 +00004564 if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
4565 return std::string();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004566
Chris Lattnere7b154b2013-01-19 21:39:22 +00004567 if (Entry.Kind != llvm::BitstreamEntry::Record) {
4568 Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
4569 return std::string();
Guy Benyei11169dd2012-12-18 14:30:41 +00004570 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004571
Guy Benyei11169dd2012-12-18 14:30:41 +00004572 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004573 StringRef Blob;
4574 if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
4575 return Blob.str();
Guy Benyei11169dd2012-12-18 14:30:41 +00004576 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004577}
4578
4579namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004580
Guy Benyei11169dd2012-12-18 14:30:41 +00004581 class SimplePCHValidator : public ASTReaderListener {
4582 const LangOptions &ExistingLangOpts;
4583 const TargetOptions &ExistingTargetOpts;
4584 const PreprocessorOptions &ExistingPPOpts;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004585 std::string ExistingModuleCachePath;
Guy Benyei11169dd2012-12-18 14:30:41 +00004586 FileManager &FileMgr;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004587
Guy Benyei11169dd2012-12-18 14:30:41 +00004588 public:
4589 SimplePCHValidator(const LangOptions &ExistingLangOpts,
4590 const TargetOptions &ExistingTargetOpts,
4591 const PreprocessorOptions &ExistingPPOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004592 StringRef ExistingModuleCachePath,
Guy Benyei11169dd2012-12-18 14:30:41 +00004593 FileManager &FileMgr)
4594 : ExistingLangOpts(ExistingLangOpts),
4595 ExistingTargetOpts(ExistingTargetOpts),
4596 ExistingPPOpts(ExistingPPOpts),
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004597 ExistingModuleCachePath(ExistingModuleCachePath),
Guy Benyei11169dd2012-12-18 14:30:41 +00004598 FileMgr(FileMgr)
4599 {
4600 }
4601
Richard Smith1e2cf0d2014-10-31 02:28:58 +00004602 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
4603 bool AllowCompatibleDifferences) override {
4604 return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
4605 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004606 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004607
Chandler Carruth0d745bc2015-03-14 04:47:43 +00004608 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
4609 bool AllowCompatibleDifferences) override {
4610 return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
4611 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00004612 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004613
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004614 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
4615 StringRef SpecificModuleCachePath,
4616 bool Complain) override {
4617 return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
4618 ExistingModuleCachePath,
4619 nullptr, ExistingLangOpts);
4620 }
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004621
Craig Topper3e89dfe2014-03-13 02:13:41 +00004622 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
4623 bool Complain,
4624 std::string &SuggestedPredefines) override {
Craig Toppera13603a2014-05-22 05:54:18 +00004625 return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00004626 SuggestedPredefines, ExistingLangOpts);
Guy Benyei11169dd2012-12-18 14:30:41 +00004627 }
4628 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00004629
4630} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00004631
Adrian Prantlbb165fb2015-06-20 18:53:08 +00004632bool ASTReader::readASTFileControlBlock(
4633 StringRef Filename, FileManager &FileMgr,
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004634 const PCHContainerReader &PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004635 bool FindModuleFileExtensions,
Manman Ren47a44452016-07-26 17:12:17 +00004636 ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004637 // Open the AST file.
Richard Smith7f330cd2015-03-18 01:42:29 +00004638 // FIXME: This allows use of the VFS; we do not allow use of the
4639 // VFS when actually loading a module.
Benjamin Kramera8857962014-10-26 22:44:13 +00004640 auto Buffer = FileMgr.getBufferForFile(Filename);
Guy Benyei11169dd2012-12-18 14:30:41 +00004641 if (!Buffer) {
4642 return true;
4643 }
4644
4645 // Initialize the stream
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004646 StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
4647 BitstreamCursor Stream(Bytes);
Guy Benyei11169dd2012-12-18 14:30:41 +00004648
4649 // Sniff for the signature.
Ben Langmuir70a1b812015-03-24 04:43:52 +00004650 if (!startsWithASTFileMagic(Stream))
Guy Benyei11169dd2012-12-18 14:30:41 +00004651 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004652
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004653 // Scan for the CONTROL_BLOCK_ID block.
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004654 if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004655 return true;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004656
4657 bool NeedsInputFiles = Listener.needsInputFileVisitation();
Ben Langmuircb69b572014-03-07 06:40:32 +00004658 bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
Richard Smithd4b230b2014-10-27 23:01:16 +00004659 bool NeedsImports = Listener.needsImportVisitation();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004660 BitstreamCursor InputFilesCursor;
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004661
Guy Benyei11169dd2012-12-18 14:30:41 +00004662 RecordData Record;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004663 std::string ModuleDir;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004664 bool DoneWithControlBlock = false;
4665 while (!DoneWithControlBlock) {
Richard Smith0516b182015-09-08 19:40:14 +00004666 llvm::BitstreamEntry Entry = Stream.advance();
4667
4668 switch (Entry.Kind) {
4669 case llvm::BitstreamEntry::SubBlock: {
4670 switch (Entry.ID) {
4671 case OPTIONS_BLOCK_ID: {
4672 std::string IgnoredSuggestedPredefines;
4673 if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
4674 /*AllowCompatibleConfigurationMismatch*/ false,
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004675 Listener, IgnoredSuggestedPredefines) != Success)
Richard Smith0516b182015-09-08 19:40:14 +00004676 return true;
4677 break;
4678 }
4679
4680 case INPUT_FILES_BLOCK_ID:
4681 InputFilesCursor = Stream;
4682 if (Stream.SkipBlock() ||
4683 (NeedsInputFiles &&
4684 ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
4685 return true;
4686 break;
4687
4688 default:
4689 if (Stream.SkipBlock())
4690 return true;
4691 break;
4692 }
4693
4694 continue;
4695 }
4696
4697 case llvm::BitstreamEntry::EndBlock:
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004698 DoneWithControlBlock = true;
4699 break;
Richard Smith0516b182015-09-08 19:40:14 +00004700
4701 case llvm::BitstreamEntry::Error:
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004702 return true;
Richard Smith0516b182015-09-08 19:40:14 +00004703
4704 case llvm::BitstreamEntry::Record:
4705 break;
4706 }
4707
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004708 if (DoneWithControlBlock) break;
4709
Guy Benyei11169dd2012-12-18 14:30:41 +00004710 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00004711 StringRef Blob;
4712 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004713 switch ((ControlRecordTypes)RecCode) {
4714 case METADATA: {
4715 if (Record[0] != VERSION_MAJOR)
4716 return true;
Guy Benyei11169dd2012-12-18 14:30:41 +00004717
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +00004718 if (Listener.ReadFullVersionInformation(Blob))
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004719 return true;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004720
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004721 break;
4722 }
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004723 case MODULE_NAME:
4724 Listener.ReadModuleName(Blob);
4725 break;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004726 case MODULE_DIRECTORY:
4727 ModuleDir = Blob;
4728 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004729 case MODULE_MAP_FILE: {
4730 unsigned Idx = 0;
Richard Smith7ed1bc92014-12-05 22:42:13 +00004731 auto Path = ReadString(Record, Idx);
4732 ResolveImportedPath(Path, ModuleDir);
4733 Listener.ReadModuleMapFile(Path);
Ben Langmuir4f5212a2014-04-14 22:12:44 +00004734 break;
Ben Langmuir4b8a9e92014-08-12 16:42:33 +00004735 }
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004736 case INPUT_FILE_OFFSETS: {
4737 if (!NeedsInputFiles)
4738 break;
4739
4740 unsigned NumInputFiles = Record[0];
4741 unsigned NumUserFiles = Record[1];
Richard Smithec216502015-02-13 19:48:37 +00004742 const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004743 for (unsigned I = 0; I != NumInputFiles; ++I) {
4744 // Go find this input file.
4745 bool isSystemFile = I >= NumUserFiles;
Ben Langmuircb69b572014-03-07 06:40:32 +00004746
4747 if (isSystemFile && !NeedsSystemInputFiles)
4748 break; // the rest are system input files
4749
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004750 BitstreamCursor &Cursor = InputFilesCursor;
4751 SavedStreamPosition SavedPosition(Cursor);
4752 Cursor.JumpToBit(InputFileOffs[I]);
4753
4754 unsigned Code = Cursor.ReadCode();
4755 RecordData Record;
4756 StringRef Blob;
4757 bool shouldContinue = false;
4758 switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
4759 case INPUT_FILE:
Argyrios Kyrtzidis68ccbe02014-03-14 02:26:31 +00004760 bool Overridden = static_cast<bool>(Record[3]);
Richard Smith7ed1bc92014-12-05 22:42:13 +00004761 std::string Filename = Blob;
4762 ResolveImportedPath(Filename, ModuleDir);
Richard Smith216a3bd2015-08-13 17:57:10 +00004763 shouldContinue = Listener.visitInputFile(
4764 Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
Argyrios Kyrtzidisc4cd2c42013-05-06 19:23:40 +00004765 break;
4766 }
4767 if (!shouldContinue)
4768 break;
4769 }
4770 break;
4771 }
4772
Richard Smithd4b230b2014-10-27 23:01:16 +00004773 case IMPORTS: {
4774 if (!NeedsImports)
4775 break;
4776
4777 unsigned Idx = 0, N = Record.size();
4778 while (Idx < N) {
4779 // Read information about the AST file.
Richard Smith79c98cc2014-10-27 23:25:15 +00004780 Idx += 5; // ImportLoc, Size, ModTime, Signature
Boris Kolpackovd30446f2017-08-31 06:26:43 +00004781 SkipString(Record, Idx); // Module name; FIXME: pass to listener?
Richard Smith7ed1bc92014-12-05 22:42:13 +00004782 std::string Filename = ReadString(Record, Idx);
4783 ResolveImportedPath(Filename, ModuleDir);
4784 Listener.visitImport(Filename);
Richard Smithd4b230b2014-10-27 23:01:16 +00004785 }
4786 break;
4787 }
4788
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004789 default:
4790 // No other validation to perform.
4791 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004792 }
4793 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004794
4795 // Look for module file extension blocks, if requested.
4796 if (FindModuleFileExtensions) {
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004797 BitstreamCursor SavedStream = Stream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004798 while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
4799 bool DoneWithExtensionBlock = false;
4800 while (!DoneWithExtensionBlock) {
4801 llvm::BitstreamEntry Entry = Stream.advance();
4802
4803 switch (Entry.Kind) {
4804 case llvm::BitstreamEntry::SubBlock:
4805 if (Stream.SkipBlock())
4806 return true;
4807
4808 continue;
4809
4810 case llvm::BitstreamEntry::EndBlock:
4811 DoneWithExtensionBlock = true;
4812 continue;
4813
4814 case llvm::BitstreamEntry::Error:
4815 return true;
4816
4817 case llvm::BitstreamEntry::Record:
4818 break;
4819 }
4820
4821 Record.clear();
4822 StringRef Blob;
4823 unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
4824 switch (RecCode) {
4825 case EXTENSION_METADATA: {
4826 ModuleFileExtensionMetadata Metadata;
4827 if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
4828 return true;
4829
4830 Listener.readModuleFileExtension(Metadata);
4831 break;
4832 }
4833 }
4834 }
4835 }
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004836 Stream = SavedStream;
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004837 }
4838
Duncan P. N. Exon Smith60fa2882017-03-13 18:45:08 +00004839 // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
4840 if (readUnhashedControlBlockImpl(
4841 nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
4842 /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
4843 ValidateDiagnosticOptions) != Success)
4844 return true;
4845
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004846 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00004847}
4848
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00004849bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
4850 const PCHContainerReader &PCHContainerRdr,
4851 const LangOptions &LangOpts,
4852 const TargetOptions &TargetOpts,
4853 const PreprocessorOptions &PPOpts,
4854 StringRef ExistingModuleCachePath) {
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00004855 SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
4856 ExistingModuleCachePath, FileMgr);
Adrian Prantlfb2398d2015-07-17 01:19:54 +00004857 return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
Douglas Gregor6623e1f2015-11-03 18:33:07 +00004858 /*FindModuleFileExtensions=*/false,
Manman Ren47a44452016-07-26 17:12:17 +00004859 validator,
4860 /*ValidateDiagnosticOptions=*/true);
Guy Benyei11169dd2012-12-18 14:30:41 +00004861}
4862
Ben Langmuir2c9af442014-04-10 17:57:43 +00004863ASTReader::ASTReadResult
4864ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004865 // Enter the submodule block.
4866 if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
4867 Error("malformed submodule block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004868 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 }
4870
4871 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
4872 bool First = true;
Craig Toppera13603a2014-05-22 05:54:18 +00004873 Module *CurrentModule = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 RecordData Record;
4875 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004876 llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004877
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004878 switch (Entry.Kind) {
4879 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
4880 case llvm::BitstreamEntry::Error:
4881 Error("malformed block record in AST file");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004882 return Failure;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004883 case llvm::BitstreamEntry::EndBlock:
Ben Langmuir2c9af442014-04-10 17:57:43 +00004884 return Success;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004885 case llvm::BitstreamEntry::Record:
4886 // The interesting case.
4887 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004888 }
Chris Lattner7fb3bef2013-01-20 00:56:42 +00004889
Guy Benyei11169dd2012-12-18 14:30:41 +00004890 // Read a record.
Chris Lattner0e6c9402013-01-20 02:38:54 +00004891 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00004892 Record.clear();
Richard Smith03478d92014-10-23 22:12:14 +00004893 auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
4894
4895 if ((Kind == SUBMODULE_METADATA) != First) {
4896 Error("submodule metadata record should be at beginning of block");
4897 return Failure;
4898 }
4899 First = false;
4900
4901 // Submodule information is only valid if we have a current module.
4902 // FIXME: Should we error on these cases?
4903 if (!CurrentModule && Kind != SUBMODULE_METADATA &&
4904 Kind != SUBMODULE_DEFINITION)
4905 continue;
4906
4907 switch (Kind) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004908 default: // Default behavior: ignore.
4909 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004910
Richard Smith03478d92014-10-23 22:12:14 +00004911 case SUBMODULE_DEFINITION: {
Douglas Gregor8d932422013-03-20 03:59:18 +00004912 if (Record.size() < 8) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 Error("malformed module definition");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004914 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004915 }
Richard Smith03478d92014-10-23 22:12:14 +00004916
Chris Lattner0e6c9402013-01-20 02:38:54 +00004917 StringRef Name = Blob;
Richard Smith9bca2982014-03-08 00:03:56 +00004918 unsigned Idx = 0;
4919 SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
4920 SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
Richard Smithdd8b5332017-09-04 05:37:53 +00004921 Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
Richard Smith9bca2982014-03-08 00:03:56 +00004922 bool IsFramework = Record[Idx++];
4923 bool IsExplicit = Record[Idx++];
4924 bool IsSystem = Record[Idx++];
4925 bool IsExternC = Record[Idx++];
4926 bool InferSubmodules = Record[Idx++];
4927 bool InferExplicitSubmodules = Record[Idx++];
4928 bool InferExportWildcard = Record[Idx++];
4929 bool ConfigMacrosExhaustive = Record[Idx++];
Douglas Gregor8d932422013-03-20 03:59:18 +00004930
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004931 Module *ParentModule = nullptr;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004932 if (Parent)
Guy Benyei11169dd2012-12-18 14:30:41 +00004933 ParentModule = getSubmodule(Parent);
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004934
Guy Benyei11169dd2012-12-18 14:30:41 +00004935 // Retrieve this (sub)module from the module map, creating it if
4936 // necessary.
David Blaikie9ffe5a32017-01-30 05:00:26 +00004937 CurrentModule =
4938 ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
4939 .first;
Ben Langmuir9d6448b2014-08-09 00:57:23 +00004940
4941 // FIXME: set the definition loc for CurrentModule, or call
4942 // ModMap.setInferredModuleAllowedBy()
4943
Guy Benyei11169dd2012-12-18 14:30:41 +00004944 SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
4945 if (GlobalIndex >= SubmodulesLoaded.size() ||
4946 SubmodulesLoaded[GlobalIndex]) {
4947 Error("too many submodules");
Ben Langmuir2c9af442014-04-10 17:57:43 +00004948 return Failure;
Guy Benyei11169dd2012-12-18 14:30:41 +00004949 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004950
Douglas Gregor7029ce12013-03-19 00:28:20 +00004951 if (!ParentModule) {
4952 if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
4953 if (CurFile != F.File) {
4954 if (!Diags.isDiagnosticInFlight()) {
4955 Diag(diag::err_module_file_conflict)
4956 << CurrentModule->getTopLevelModuleName()
4957 << CurFile->getName()
4958 << F.File->getName();
4959 }
Ben Langmuir2c9af442014-04-10 17:57:43 +00004960 return Failure;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004961 }
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004962 }
Douglas Gregor7029ce12013-03-19 00:28:20 +00004963
4964 CurrentModule->setASTFile(F.File);
Richard Smithab755972017-06-05 18:10:11 +00004965 CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
Douglas Gregor8a114ab2013-02-06 22:40:31 +00004966 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +00004967
Richard Smithdd8b5332017-09-04 05:37:53 +00004968 CurrentModule->Kind = Kind;
Adrian Prantl15bcf702015-06-30 17:39:43 +00004969 CurrentModule->Signature = F.Signature;
Guy Benyei11169dd2012-12-18 14:30:41 +00004970 CurrentModule->IsFromModuleFile = true;
4971 CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
Richard Smith9bca2982014-03-08 00:03:56 +00004972 CurrentModule->IsExternC = IsExternC;
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 CurrentModule->InferSubmodules = InferSubmodules;
4974 CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
4975 CurrentModule->InferExportWildcard = InferExportWildcard;
Douglas Gregor8d932422013-03-20 03:59:18 +00004976 CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
Guy Benyei11169dd2012-12-18 14:30:41 +00004977 if (DeserializationListener)
4978 DeserializationListener->ModuleRead(GlobalID, CurrentModule);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00004979
Guy Benyei11169dd2012-12-18 14:30:41 +00004980 SubmodulesLoaded[GlobalIndex] = CurrentModule;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004981
Richard Smith8a3e39a2016-03-28 21:31:09 +00004982 // Clear out data that will be replaced by what is in the module file.
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004983 CurrentModule->LinkLibraries.clear();
Douglas Gregor8d932422013-03-20 03:59:18 +00004984 CurrentModule->ConfigMacros.clear();
Douglas Gregorfb912652013-03-20 21:10:35 +00004985 CurrentModule->UnresolvedConflicts.clear();
4986 CurrentModule->Conflicts.clear();
Richard Smith8a3e39a2016-03-28 21:31:09 +00004987
4988 // The module is available unless it's missing a requirement; relevant
4989 // requirements will be (re-)added by SUBMODULE_REQUIRES records.
4990 // Missing headers that were present when the module was built do not
4991 // make it unavailable -- if we got this far, this must be an explicitly
4992 // imported module file.
4993 CurrentModule->Requirements.clear();
4994 CurrentModule->MissingHeaders.clear();
4995 CurrentModule->IsMissingRequirement =
4996 ParentModule && ParentModule->IsMissingRequirement;
4997 CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
Guy Benyei11169dd2012-12-18 14:30:41 +00004998 break;
4999 }
Richard Smith8a3e39a2016-03-28 21:31:09 +00005000
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 case SUBMODULE_UMBRELLA_HEADER: {
Richard Smith2b63d152015-05-16 02:28:53 +00005002 std::string Filename = Blob;
5003 ResolveImportedPath(F, Filename);
5004 if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005005 if (!CurrentModule->getUmbrellaHeader())
Richard Smith2b63d152015-05-16 02:28:53 +00005006 ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
5007 else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
Bruno Cardoso Lopes573b13f2017-03-22 00:11:21 +00005008 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5009 Error("mismatched umbrella headers in submodule");
5010 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 }
5012 }
5013 break;
5014 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005015
Richard Smith202210b2014-10-24 20:23:01 +00005016 case SUBMODULE_HEADER:
5017 case SUBMODULE_EXCLUDED_HEADER:
5018 case SUBMODULE_PRIVATE_HEADER:
5019 // We lazily associate headers with their modules via the HeaderInfo table.
Argyrios Kyrtzidisb146baa2013-03-13 21:13:51 +00005020 // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
5021 // of complete filenames or remove it entirely.
Richard Smith202210b2014-10-24 20:23:01 +00005022 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005023
Richard Smith202210b2014-10-24 20:23:01 +00005024 case SUBMODULE_TEXTUAL_HEADER:
5025 case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
5026 // FIXME: Textual headers are not marked in the HeaderInfo table. Load
5027 // them here.
5028 break;
Lawrence Crowlb53e5482013-06-20 21:14:14 +00005029
Guy Benyei11169dd2012-12-18 14:30:41 +00005030 case SUBMODULE_TOPHEADER: {
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +00005031 CurrentModule->addTopHeaderFilename(Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005032 break;
5033 }
5034
5035 case SUBMODULE_UMBRELLA_DIR: {
Richard Smith2b63d152015-05-16 02:28:53 +00005036 std::string Dirname = Blob;
5037 ResolveImportedPath(F, Dirname);
5038 if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005039 if (!CurrentModule->getUmbrellaDir())
Richard Smith2b63d152015-05-16 02:28:53 +00005040 ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
5041 else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
Ben Langmuir2c9af442014-04-10 17:57:43 +00005042 if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
5043 Error("mismatched umbrella directories in submodule");
5044 return OutOfDate;
Guy Benyei11169dd2012-12-18 14:30:41 +00005045 }
5046 }
5047 break;
5048 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005049
Guy Benyei11169dd2012-12-18 14:30:41 +00005050 case SUBMODULE_METADATA: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005051 F.BaseSubmoduleID = getTotalNumSubmodules();
5052 F.LocalNumSubmodules = Record[0];
5053 unsigned LocalBaseSubmoduleID = Record[1];
5054 if (F.LocalNumSubmodules > 0) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005055 // Introduce the global -> local mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005056 // module.
5057 GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005058
5059 // Introduce the local -> global mapping for submodules within this
Guy Benyei11169dd2012-12-18 14:30:41 +00005060 // module.
5061 F.SubmoduleRemap.insertOrReplace(
5062 std::make_pair(LocalBaseSubmoduleID,
5063 F.BaseSubmoduleID - LocalBaseSubmoduleID));
Ben Langmuirfe971d92014-08-16 04:54:18 +00005064
Ben Langmuir52ca6782014-10-20 16:27:32 +00005065 SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
5066 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005067 break;
5068 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005069
Guy Benyei11169dd2012-12-18 14:30:41 +00005070 case SUBMODULE_IMPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005071 for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005072 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005073 Unresolved.File = &F;
5074 Unresolved.Mod = CurrentModule;
5075 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005076 Unresolved.Kind = UnresolvedModuleRef::Import;
Guy Benyei11169dd2012-12-18 14:30:41 +00005077 Unresolved.IsWildcard = false;
Douglas Gregorfb912652013-03-20 21:10:35 +00005078 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005079 }
5080 break;
5081 }
5082
5083 case SUBMODULE_EXPORTS: {
Guy Benyei11169dd2012-12-18 14:30:41 +00005084 for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
Douglas Gregorfb912652013-03-20 21:10:35 +00005085 UnresolvedModuleRef Unresolved;
Guy Benyei11169dd2012-12-18 14:30:41 +00005086 Unresolved.File = &F;
5087 Unresolved.Mod = CurrentModule;
5088 Unresolved.ID = Record[Idx];
Douglas Gregorfb912652013-03-20 21:10:35 +00005089 Unresolved.Kind = UnresolvedModuleRef::Export;
Guy Benyei11169dd2012-12-18 14:30:41 +00005090 Unresolved.IsWildcard = Record[Idx + 1];
Douglas Gregorfb912652013-03-20 21:10:35 +00005091 UnresolvedModuleRefs.push_back(Unresolved);
Guy Benyei11169dd2012-12-18 14:30:41 +00005092 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005093
5094 // Once we've loaded the set of exports, there's no reason to keep
Guy Benyei11169dd2012-12-18 14:30:41 +00005095 // the parsed, unresolved exports around.
5096 CurrentModule->UnresolvedExports.clear();
5097 break;
5098 }
5099 case SUBMODULE_REQUIRES: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005100 CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
5101 PP.getTargetInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00005102 break;
5103 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005104
5105 case SUBMODULE_LINK_LIBRARY:
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005106 CurrentModule->LinkLibraries.push_back(
Chris Lattner0e6c9402013-01-20 02:38:54 +00005107 Module::LinkLibrary(Blob, Record[0]));
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005108 break;
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005109
5110 case SUBMODULE_CONFIG_MACRO:
Douglas Gregor35b13ec2013-03-20 00:22:05 +00005111 CurrentModule->ConfigMacros.push_back(Blob.str());
5112 break;
Douglas Gregorfb912652013-03-20 21:10:35 +00005113
5114 case SUBMODULE_CONFLICT: {
Douglas Gregorfb912652013-03-20 21:10:35 +00005115 UnresolvedModuleRef Unresolved;
5116 Unresolved.File = &F;
5117 Unresolved.Mod = CurrentModule;
5118 Unresolved.ID = Record[0];
5119 Unresolved.Kind = UnresolvedModuleRef::Conflict;
5120 Unresolved.IsWildcard = false;
5121 Unresolved.String = Blob;
5122 UnresolvedModuleRefs.push_back(Unresolved);
5123 break;
5124 }
Richard Smithdc1f0422016-07-20 19:10:16 +00005125
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005126 case SUBMODULE_INITIALIZERS: {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005127 if (!ContextObj)
5128 break;
Richard Smithdc1f0422016-07-20 19:10:16 +00005129 SmallVector<uint32_t, 16> Inits;
5130 for (auto &ID : Record)
5131 Inits.push_back(getGlobalDeclID(F, ID));
Richard Smithdbafb6c2017-06-29 23:23:46 +00005132 ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
Richard Smithdc1f0422016-07-20 19:10:16 +00005133 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00005134 }
Douglas Gregorf0b11de2017-09-14 23:38:44 +00005135
5136 case SUBMODULE_EXPORT_AS:
5137 CurrentModule->ExportAsModule = Blob.str();
5138 break;
5139 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005140 }
5141}
5142
5143/// \brief Parse the record that corresponds to a LangOptions data
5144/// structure.
5145///
5146/// This routine parses the language options from the AST file and then gives
5147/// them to the AST listener if one is set.
5148///
5149/// \returns true if the listener deems the file unacceptable, false otherwise.
5150bool ASTReader::ParseLanguageOptions(const RecordData &Record,
5151 bool Complain,
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005152 ASTReaderListener &Listener,
5153 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005154 LangOptions LangOpts;
5155 unsigned Idx = 0;
5156#define LANGOPT(Name, Bits, Default, Description) \
5157 LangOpts.Name = Record[Idx++];
5158#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
5159 LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
5160#include "clang/Basic/LangOptions.def"
Alexey Samsonovedf99a92014-11-07 22:29:38 +00005161#define SANITIZER(NAME, ID) \
5162 LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
Will Dietzf54319c2013-01-18 11:30:38 +00005163#include "clang/Basic/Sanitizers.def"
Guy Benyei11169dd2012-12-18 14:30:41 +00005164
Ben Langmuircd98cb72015-06-23 18:20:18 +00005165 for (unsigned N = Record[Idx++]; N; --N)
5166 LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
5167
Guy Benyei11169dd2012-12-18 14:30:41 +00005168 ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
5169 VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
5170 LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005171
Ben Langmuird4a667a2015-06-23 18:20:23 +00005172 LangOpts.CurrentModule = ReadString(Record, Idx);
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005173
5174 // Comment options.
5175 for (unsigned N = Record[Idx++]; N; --N) {
5176 LangOpts.CommentOpts.BlockCommandNames.push_back(
5177 ReadString(Record, Idx));
5178 }
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00005179 LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
Dmitri Gribenkoacf2e782013-02-22 14:21:27 +00005180
Samuel Antaoee8fb302016-01-06 13:42:12 +00005181 // OpenMP offloading options.
5182 for (unsigned N = Record[Idx++]; N; --N) {
5183 LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
5184 }
5185
5186 LangOpts.OMPHostIRFile = ReadString(Record, Idx);
5187
Richard Smith1e2cf0d2014-10-31 02:28:58 +00005188 return Listener.ReadLanguageOptions(LangOpts, Complain,
5189 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005190}
5191
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005192bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
5193 ASTReaderListener &Listener,
5194 bool AllowCompatibleDifferences) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005195 unsigned Idx = 0;
5196 TargetOptions TargetOpts;
5197 TargetOpts.Triple = ReadString(Record, Idx);
5198 TargetOpts.CPU = ReadString(Record, Idx);
5199 TargetOpts.ABI = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005200 for (unsigned N = Record[Idx++]; N; --N) {
5201 TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
5202 }
5203 for (unsigned N = Record[Idx++]; N; --N) {
5204 TargetOpts.Features.push_back(ReadString(Record, Idx));
5205 }
5206
Chandler Carruth0d745bc2015-03-14 04:47:43 +00005207 return Listener.ReadTargetOptions(TargetOpts, Complain,
5208 AllowCompatibleDifferences);
Guy Benyei11169dd2012-12-18 14:30:41 +00005209}
5210
5211bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
5212 ASTReaderListener &Listener) {
Ben Langmuirb92de022014-04-29 16:25:26 +00005213 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
Guy Benyei11169dd2012-12-18 14:30:41 +00005214 unsigned Idx = 0;
Ben Langmuirb92de022014-04-29 16:25:26 +00005215#define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005216#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
Ben Langmuirb92de022014-04-29 16:25:26 +00005217 DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
Guy Benyei11169dd2012-12-18 14:30:41 +00005218#include "clang/Basic/DiagnosticOptions.def"
5219
Richard Smith3be1cb22014-08-07 00:24:21 +00005220 for (unsigned N = Record[Idx++]; N; --N)
Ben Langmuirb92de022014-04-29 16:25:26 +00005221 DiagOpts->Warnings.push_back(ReadString(Record, Idx));
Richard Smith3be1cb22014-08-07 00:24:21 +00005222 for (unsigned N = Record[Idx++]; N; --N)
5223 DiagOpts->Remarks.push_back(ReadString(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00005224
5225 return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
5226}
5227
5228bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
5229 ASTReaderListener &Listener) {
5230 FileSystemOptions FSOpts;
5231 unsigned Idx = 0;
5232 FSOpts.WorkingDir = ReadString(Record, Idx);
5233 return Listener.ReadFileSystemOptions(FSOpts, Complain);
5234}
5235
5236bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
5237 bool Complain,
5238 ASTReaderListener &Listener) {
5239 HeaderSearchOptions HSOpts;
5240 unsigned Idx = 0;
5241 HSOpts.Sysroot = ReadString(Record, Idx);
5242
5243 // Include entries.
5244 for (unsigned N = Record[Idx++]; N; --N) {
5245 std::string Path = ReadString(Record, Idx);
5246 frontend::IncludeDirGroup Group
5247 = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005248 bool IsFramework = Record[Idx++];
5249 bool IgnoreSysRoot = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005250 HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
5251 IgnoreSysRoot);
Guy Benyei11169dd2012-12-18 14:30:41 +00005252 }
5253
5254 // System header prefixes.
5255 for (unsigned N = Record[Idx++]; N; --N) {
5256 std::string Prefix = ReadString(Record, Idx);
5257 bool IsSystemHeader = Record[Idx++];
Benjamin Kramer3204b152015-05-29 19:42:19 +00005258 HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
Guy Benyei11169dd2012-12-18 14:30:41 +00005259 }
5260
5261 HSOpts.ResourceDir = ReadString(Record, Idx);
5262 HSOpts.ModuleCachePath = ReadString(Record, Idx);
Argyrios Kyrtzidis1594c152014-03-03 08:12:05 +00005263 HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005264 HSOpts.DisableModuleHash = Record[Idx++];
Richard Smith18934752017-06-06 00:32:01 +00005265 HSOpts.ImplicitModuleMaps = Record[Idx++];
5266 HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005267 HSOpts.UseBuiltinIncludes = Record[Idx++];
5268 HSOpts.UseStandardSystemIncludes = Record[Idx++];
5269 HSOpts.UseStandardCXXIncludes = Record[Idx++];
5270 HSOpts.UseLibcxx = Record[Idx++];
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005271 std::string SpecificModuleCachePath = ReadString(Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00005272
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +00005273 return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
5274 Complain);
Guy Benyei11169dd2012-12-18 14:30:41 +00005275}
5276
5277bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
5278 bool Complain,
5279 ASTReaderListener &Listener,
5280 std::string &SuggestedPredefines) {
5281 PreprocessorOptions PPOpts;
5282 unsigned Idx = 0;
5283
5284 // Macro definitions/undefs
5285 for (unsigned N = Record[Idx++]; N; --N) {
5286 std::string Macro = ReadString(Record, Idx);
5287 bool IsUndef = Record[Idx++];
5288 PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
5289 }
5290
5291 // Includes
5292 for (unsigned N = Record[Idx++]; N; --N) {
5293 PPOpts.Includes.push_back(ReadString(Record, Idx));
5294 }
5295
5296 // Macro Includes
5297 for (unsigned N = Record[Idx++]; N; --N) {
5298 PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
5299 }
5300
5301 PPOpts.UsePredefines = Record[Idx++];
Argyrios Kyrtzidisd3afa0c2013-04-26 21:33:40 +00005302 PPOpts.DetailedRecord = Record[Idx++];
Guy Benyei11169dd2012-12-18 14:30:41 +00005303 PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
5304 PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
5305 PPOpts.ObjCXXARCStandardLibrary =
5306 static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
5307 SuggestedPredefines.clear();
5308 return Listener.ReadPreprocessorOptions(PPOpts, Complain,
5309 SuggestedPredefines);
5310}
5311
5312std::pair<ModuleFile *, unsigned>
5313ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
5314 GlobalPreprocessedEntityMapType::iterator
5315 I = GlobalPreprocessedEntityMap.find(GlobalIndex);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005316 assert(I != GlobalPreprocessedEntityMap.end() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00005317 "Corrupted global preprocessed entity map");
5318 ModuleFile *M = I->second;
5319 unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
5320 return std::make_pair(M, LocalIndex);
5321}
5322
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005323llvm::iterator_range<PreprocessingRecord::iterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005324ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
5325 if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
5326 return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
5327 Mod.NumPreprocessedEntities);
5328
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005329 return llvm::make_range(PreprocessingRecord::iterator(),
5330 PreprocessingRecord::iterator());
Guy Benyei11169dd2012-12-18 14:30:41 +00005331}
5332
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005333llvm::iterator_range<ASTReader::ModuleDeclIterator>
Guy Benyei11169dd2012-12-18 14:30:41 +00005334ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005335 return llvm::make_range(
5336 ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
5337 ModuleDeclIterator(this, &Mod,
5338 Mod.FileSortedDecls + Mod.NumFileSortedDecls));
Guy Benyei11169dd2012-12-18 14:30:41 +00005339}
5340
5341PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
5342 PreprocessedEntityID PPID = Index+1;
5343 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5344 ModuleFile &M = *PPInfo.first;
5345 unsigned LocalIndex = PPInfo.second;
5346 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
5347
Guy Benyei11169dd2012-12-18 14:30:41 +00005348 if (!PP.getPreprocessingRecord()) {
5349 Error("no preprocessing record");
Craig Toppera13603a2014-05-22 05:54:18 +00005350 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005351 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005352
5353 SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005354 M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
5355
5356 llvm::BitstreamEntry Entry =
5357 M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
5358 if (Entry.Kind != llvm::BitstreamEntry::Record)
Craig Toppera13603a2014-05-22 05:54:18 +00005359 return nullptr;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005360
Guy Benyei11169dd2012-12-18 14:30:41 +00005361 // Read the record.
Richard Smithcb34bd32016-03-27 07:28:06 +00005362 SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
5363 TranslateSourceLocation(M, PPOffs.getEnd()));
Guy Benyei11169dd2012-12-18 14:30:41 +00005364 PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005365 StringRef Blob;
Guy Benyei11169dd2012-12-18 14:30:41 +00005366 RecordData Record;
5367 PreprocessorDetailRecordTypes RecType =
Chris Lattner0e6c9402013-01-20 02:38:54 +00005368 (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
5369 Entry.ID, Record, &Blob);
Guy Benyei11169dd2012-12-18 14:30:41 +00005370 switch (RecType) {
5371 case PPD_MACRO_EXPANSION: {
5372 bool isBuiltin = Record[0];
Craig Toppera13603a2014-05-22 05:54:18 +00005373 IdentifierInfo *Name = nullptr;
Richard Smith66a81862015-05-04 02:25:31 +00005374 MacroDefinitionRecord *Def = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005375 if (isBuiltin)
5376 Name = getLocalIdentifier(M, Record[1]);
5377 else {
Richard Smith66a81862015-05-04 02:25:31 +00005378 PreprocessedEntityID GlobalID =
5379 getGlobalPreprocessedEntityID(M, Record[1]);
5380 Def = cast<MacroDefinitionRecord>(
5381 PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
Guy Benyei11169dd2012-12-18 14:30:41 +00005382 }
5383
5384 MacroExpansion *ME;
5385 if (isBuiltin)
5386 ME = new (PPRec) MacroExpansion(Name, Range);
5387 else
5388 ME = new (PPRec) MacroExpansion(Def, Range);
5389
5390 return ME;
5391 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005392
Guy Benyei11169dd2012-12-18 14:30:41 +00005393 case PPD_MACRO_DEFINITION: {
5394 // Decode the identifier info and then check again; if the macro is
5395 // still defined and associated with the identifier,
5396 IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
Richard Smith66a81862015-05-04 02:25:31 +00005397 MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00005398
5399 if (DeserializationListener)
5400 DeserializationListener->MacroDefinitionRead(PPID, MD);
5401
5402 return MD;
5403 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005404
Guy Benyei11169dd2012-12-18 14:30:41 +00005405 case PPD_INCLUSION_DIRECTIVE: {
Chris Lattner0e6c9402013-01-20 02:38:54 +00005406 const char *FullFileNameStart = Blob.data() + Record[0];
5407 StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
Craig Toppera13603a2014-05-22 05:54:18 +00005408 const FileEntry *File = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00005409 if (!FullFileName.empty())
5410 File = PP.getFileManager().getFile(FullFileName);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005411
Guy Benyei11169dd2012-12-18 14:30:41 +00005412 // FIXME: Stable encoding
5413 InclusionDirective::InclusionKind Kind
5414 = static_cast<InclusionDirective::InclusionKind>(Record[2]);
5415 InclusionDirective *ID
5416 = new (PPRec) InclusionDirective(PPRec, Kind,
Chris Lattner0e6c9402013-01-20 02:38:54 +00005417 StringRef(Blob.data(), Record[0]),
Guy Benyei11169dd2012-12-18 14:30:41 +00005418 Record[1], Record[3],
5419 File,
5420 Range);
5421 return ID;
5422 }
5423 }
5424
5425 llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
5426}
5427
5428/// \brief \arg SLocMapI points at a chunk of a module that contains no
5429/// preprocessed entities or the entities it contains are not the ones we are
5430/// looking for. Find the next module that contains entities and return the ID
5431/// of the first entry.
5432PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
5433 GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
5434 ++SLocMapI;
5435 for (GlobalSLocOffsetMapType::const_iterator
5436 EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
5437 ModuleFile &M = *SLocMapI->second;
5438 if (M.NumPreprocessedEntities)
5439 return M.BasePreprocessedEntityID;
5440 }
5441
5442 return getTotalNumPreprocessedEntities();
5443}
5444
5445namespace {
5446
Guy Benyei11169dd2012-12-18 14:30:41 +00005447struct PPEntityComp {
5448 const ASTReader &Reader;
5449 ModuleFile &M;
5450
5451 PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
5452
5453 bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
5454 SourceLocation LHS = getLoc(L);
5455 SourceLocation RHS = getLoc(R);
5456 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5457 }
5458
5459 bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
5460 SourceLocation LHS = getLoc(L);
5461 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5462 }
5463
5464 bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
5465 SourceLocation RHS = getLoc(R);
5466 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
5467 }
5468
5469 SourceLocation getLoc(const PPEntityOffset &PPE) const {
Richard Smithb22a1d12016-03-27 20:13:24 +00005470 return Reader.TranslateSourceLocation(M, PPE.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005471 }
5472};
5473
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005474} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005475
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005476PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
5477 bool EndsAfter) const {
5478 if (SourceMgr.isLocalSourceLocation(Loc))
Guy Benyei11169dd2012-12-18 14:30:41 +00005479 return getTotalNumPreprocessedEntities();
5480
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005481 GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
5482 SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00005483 assert(SLocMapI != GlobalSLocOffsetMap.end() &&
5484 "Corrupted global sloc offset map");
5485
5486 if (SLocMapI->second->NumPreprocessedEntities == 0)
5487 return findNextPreprocessedEntity(SLocMapI);
5488
5489 ModuleFile &M = *SLocMapI->second;
5490 typedef const PPEntityOffset *pp_iterator;
5491 pp_iterator pp_begin = M.PreprocessedEntityOffsets;
5492 pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
5493
5494 size_t Count = M.NumPreprocessedEntities;
5495 size_t Half;
5496 pp_iterator First = pp_begin;
5497 pp_iterator PPI;
5498
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005499 if (EndsAfter) {
5500 PPI = std::upper_bound(pp_begin, pp_end, Loc,
Richard Smithb22a1d12016-03-27 20:13:24 +00005501 PPEntityComp(*this, M));
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005502 } else {
5503 // Do a binary search manually instead of using std::lower_bound because
5504 // The end locations of entities may be unordered (when a macro expansion
5505 // is inside another macro argument), but for this case it is not important
5506 // whether we get the first macro expansion or its containing macro.
5507 while (Count > 0) {
5508 Half = Count / 2;
5509 PPI = First;
5510 std::advance(PPI, Half);
Richard Smithb22a1d12016-03-27 20:13:24 +00005511 if (SourceMgr.isBeforeInTranslationUnit(
5512 TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005513 First = PPI;
5514 ++First;
5515 Count = Count - Half - 1;
5516 } else
5517 Count = Half;
5518 }
Guy Benyei11169dd2012-12-18 14:30:41 +00005519 }
5520
5521 if (PPI == pp_end)
5522 return findNextPreprocessedEntity(SLocMapI);
5523
5524 return M.BasePreprocessedEntityID + (PPI - pp_begin);
5525}
5526
Guy Benyei11169dd2012-12-18 14:30:41 +00005527/// \brief Returns a pair of [Begin, End) indices of preallocated
5528/// preprocessed entities that \arg Range encompasses.
5529std::pair<unsigned, unsigned>
5530 ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
5531 if (Range.isInvalid())
5532 return std::make_pair(0,0);
5533 assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
5534
Alp Toker2e9ce4c2014-05-16 18:59:21 +00005535 PreprocessedEntityID BeginID =
5536 findPreprocessedEntity(Range.getBegin(), false);
5537 PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
Guy Benyei11169dd2012-12-18 14:30:41 +00005538 return std::make_pair(BeginID, EndID);
5539}
5540
5541/// \brief Optionally returns true or false if the preallocated preprocessed
5542/// entity with index \arg Index came from file \arg FID.
David Blaikie05785d12013-02-20 22:23:23 +00005543Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
Guy Benyei11169dd2012-12-18 14:30:41 +00005544 FileID FID) {
5545 if (FID.isInvalid())
5546 return false;
5547
5548 std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
5549 ModuleFile &M = *PPInfo.first;
5550 unsigned LocalIndex = PPInfo.second;
5551 const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005552
Richard Smithcb34bd32016-03-27 07:28:06 +00005553 SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
Guy Benyei11169dd2012-12-18 14:30:41 +00005554 if (Loc.isInvalid())
5555 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005556
Guy Benyei11169dd2012-12-18 14:30:41 +00005557 if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
5558 return true;
5559 else
5560 return false;
5561}
5562
5563namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005564
Guy Benyei11169dd2012-12-18 14:30:41 +00005565 /// \brief Visitor used to search for information about a header file.
5566 class HeaderFileInfoVisitor {
Guy Benyei11169dd2012-12-18 14:30:41 +00005567 const FileEntry *FE;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005568
David Blaikie05785d12013-02-20 22:23:23 +00005569 Optional<HeaderFileInfo> HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005570
Guy Benyei11169dd2012-12-18 14:30:41 +00005571 public:
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005572 explicit HeaderFileInfoVisitor(const FileEntry *FE)
5573 : FE(FE) { }
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005574
5575 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005576 HeaderFileInfoLookupTable *Table
5577 = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
5578 if (!Table)
5579 return false;
5580
5581 // Look in the on-disk hash table for an entry for this file name.
Richard Smithbdf2d932015-07-30 03:37:16 +00005582 HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
Guy Benyei11169dd2012-12-18 14:30:41 +00005583 if (Pos == Table->end())
5584 return false;
5585
Richard Smithbdf2d932015-07-30 03:37:16 +00005586 HFI = *Pos;
Guy Benyei11169dd2012-12-18 14:30:41 +00005587 return true;
5588 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005589
David Blaikie05785d12013-02-20 22:23:23 +00005590 Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
Guy Benyei11169dd2012-12-18 14:30:41 +00005591 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00005592
5593} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00005594
5595HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
Argyrios Kyrtzidis61a38962013-03-06 18:12:44 +00005596 HeaderFileInfoVisitor Visitor(FE);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00005597 ModuleMgr.visit(Visitor);
Argyrios Kyrtzidis1054bbf2013-05-08 23:46:55 +00005598 if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
Guy Benyei11169dd2012-12-18 14:30:41 +00005599 return *HFI;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005600
Guy Benyei11169dd2012-12-18 14:30:41 +00005601 return HeaderFileInfo();
5602}
5603
5604void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
Richard Smithd230de22017-01-26 01:01:01 +00005605 using DiagState = DiagnosticsEngine::DiagState;
5606 SmallVector<DiagState *, 32> DiagStates;
5607
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00005608 for (ModuleFile &F : ModuleMgr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005609 unsigned Idx = 0;
Richard Smithd230de22017-01-26 01:01:01 +00005610 auto &Record = F.PragmaDiagMappings;
5611 if (Record.empty())
5612 continue;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005613
Richard Smithd230de22017-01-26 01:01:01 +00005614 DiagStates.clear();
5615
5616 auto ReadDiagState =
5617 [&](const DiagState &BasedOn, SourceLocation Loc,
5618 bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
5619 unsigned BackrefID = Record[Idx++];
5620 if (BackrefID != 0)
5621 return DiagStates[BackrefID - 1];
5622
Guy Benyei11169dd2012-12-18 14:30:41 +00005623 // A new DiagState was created here.
Richard Smithd230de22017-01-26 01:01:01 +00005624 Diag.DiagStates.push_back(BasedOn);
5625 DiagState *NewState = &Diag.DiagStates.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00005626 DiagStates.push_back(NewState);
Duncan P. N. Exon Smith3cb183b2017-03-14 19:31:27 +00005627 unsigned Size = Record[Idx++];
5628 assert(Idx + Size * 2 <= Record.size() &&
5629 "Invalid data, not enough diag/map pairs");
5630 while (Size--) {
Richard Smithd230de22017-01-26 01:01:01 +00005631 unsigned DiagID = Record[Idx++];
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005632 DiagnosticMapping NewMapping =
Richard Smithe37391c2017-05-03 00:28:49 +00005633 DiagnosticMapping::deserialize(Record[Idx++]);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005634 if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
5635 continue;
5636
5637 DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
5638
5639 // If this mapping was specified as a warning but the severity was
5640 // upgraded due to diagnostic settings, simulate the current diagnostic
5641 // settings (and use a warning).
Richard Smithe37391c2017-05-03 00:28:49 +00005642 if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
5643 NewMapping.setSeverity(diag::Severity::Warning);
5644 NewMapping.setUpgradedFromWarning(false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005645 }
5646
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005647 Mapping = NewMapping;
Richard Smithd230de22017-01-26 01:01:01 +00005648 }
Richard Smithd230de22017-01-26 01:01:01 +00005649 return NewState;
5650 };
5651
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005652 // Read the first state.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005653 DiagState *FirstState;
5654 if (F.Kind == MK_ImplicitModule) {
5655 // Implicitly-built modules are reused with different diagnostic
5656 // settings. Use the initial diagnostic state from Diag to simulate this
5657 // compilation's diagnostic settings.
5658 FirstState = Diag.DiagStatesByLoc.FirstDiagState;
5659 DiagStates.push_back(FirstState);
5660
5661 // Skip the initial diagnostic state from the serialized module.
Richard Smithe37391c2017-05-03 00:28:49 +00005662 assert(Record[1] == 0 &&
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005663 "Invalid data, unexpected backref in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005664 Idx = 3 + Record[2] * 2;
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005665 assert(Idx < Record.size() &&
5666 "Invalid data, not enough state change pairs in initial state");
Richard Smithe37391c2017-05-03 00:28:49 +00005667 } else if (F.isModule()) {
5668 // For an explicit module, preserve the flags from the module build
5669 // command line (-w, -Weverything, -Werror, ...) along with any explicit
5670 // -Wblah flags.
5671 unsigned Flags = Record[Idx++];
5672 DiagState Initial;
5673 Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
5674 Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
5675 Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
5676 Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
5677 Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
5678 Initial.ExtBehavior = (diag::Severity)Flags;
5679 FirstState = ReadDiagState(Initial, SourceLocation(), true);
Richard Smithea741482017-05-01 22:10:47 +00005680
Richard Smithe37391c2017-05-03 00:28:49 +00005681 // Set up the root buffer of the module to start with the initial
5682 // diagnostic state of the module itself, to cover files that contain no
5683 // explicit transitions (for which we did not serialize anything).
5684 Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
5685 .StateTransitions.push_back({FirstState, 0});
5686 } else {
5687 // For prefix ASTs, start with whatever the user configured on the
5688 // command line.
5689 Idx++; // Skip flags.
5690 FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
5691 SourceLocation(), false);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +00005692 }
Richard Smithd230de22017-01-26 01:01:01 +00005693
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005694 // Read the state transitions.
5695 unsigned NumLocations = Record[Idx++];
5696 while (NumLocations--) {
5697 assert(Idx < Record.size() &&
5698 "Invalid data, missing pragma diagnostic states");
Richard Smithd230de22017-01-26 01:01:01 +00005699 SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
5700 auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
5701 assert(IDAndOffset.second == 0 && "not a start location for a FileID");
5702 unsigned Transitions = Record[Idx++];
5703
5704 // Note that we don't need to set up Parent/ParentOffset here, because
5705 // we won't be changing the diagnostic state within imported FileIDs
5706 // (other than perhaps appending to the main source file, which has no
5707 // parent).
5708 auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
5709 F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
5710 for (unsigned I = 0; I != Transitions; ++I) {
5711 unsigned Offset = Record[Idx++];
5712 auto *State =
5713 ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
5714 F.StateTransitions.push_back({State, Offset});
Guy Benyei11169dd2012-12-18 14:30:41 +00005715 }
5716 }
Richard Smithd230de22017-01-26 01:01:01 +00005717
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005718 // Read the final state.
5719 assert(Idx < Record.size() &&
5720 "Invalid data, missing final pragma diagnostic state");
5721 SourceLocation CurStateLoc =
5722 ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
5723 auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
5724
5725 if (!F.isModule()) {
5726 Diag.DiagStatesByLoc.CurDiagState = CurState;
5727 Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
5728
5729 // Preserve the property that the imaginary root file describes the
5730 // current state.
Simon Pilgrim22518632017-10-10 13:56:17 +00005731 FileID NullFile;
5732 auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
Duncan P. N. Exon Smitha351c102017-04-12 03:45:32 +00005733 if (T.empty())
5734 T.push_back({CurState, 0});
5735 else
5736 T[0].State = CurState;
5737 }
5738
Richard Smithd230de22017-01-26 01:01:01 +00005739 // Don't try to read these mappings again.
5740 Record.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00005741 }
5742}
5743
5744/// \brief Get the correct cursor and offset for loading a type.
5745ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
5746 GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
5747 assert(I != GlobalTypeMap.end() && "Corrupted global type map");
5748 ModuleFile *M = I->second;
5749 return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
5750}
5751
5752/// \brief Read and return the type with the given index..
5753///
5754/// The index is the type ID, shifted and minus the number of predefs. This
5755/// routine actually reads the record corresponding to the type at the given
5756/// location. It is a helper routine for GetType, which deals with reading type
5757/// IDs.
5758QualType ASTReader::readTypeRecord(unsigned Index) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00005759 assert(ContextObj && "reading type with no AST context");
5760 ASTContext &Context = *ContextObj;
Guy Benyei11169dd2012-12-18 14:30:41 +00005761 RecordLocation Loc = TypeCursorForIndex(Index);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00005762 BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00005763
5764 // Keep track of where we are in the stream, then jump back there
5765 // after reading this type.
5766 SavedStreamPosition SavedPosition(DeclsCursor);
5767
5768 ReadingKindTracker ReadingKind(Read_Type, *this);
5769
5770 // Note that we are loading a type record.
5771 Deserializing AType(this);
5772
5773 unsigned Idx = 0;
5774 DeclsCursor.JumpToBit(Loc.Offset);
5775 RecordData Record;
5776 unsigned Code = DeclsCursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00005777 switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005778 case TYPE_EXT_QUAL: {
5779 if (Record.size() != 2) {
5780 Error("Incorrect encoding of extended qualifier type");
5781 return QualType();
5782 }
5783 QualType Base = readType(*Loc.F, Record, Idx);
5784 Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
5785 return Context.getQualifiedType(Base, Quals);
5786 }
5787
5788 case TYPE_COMPLEX: {
5789 if (Record.size() != 1) {
5790 Error("Incorrect encoding of complex type");
5791 return QualType();
5792 }
5793 QualType ElemType = readType(*Loc.F, Record, Idx);
5794 return Context.getComplexType(ElemType);
5795 }
5796
5797 case TYPE_POINTER: {
5798 if (Record.size() != 1) {
5799 Error("Incorrect encoding of pointer type");
5800 return QualType();
5801 }
5802 QualType PointeeType = readType(*Loc.F, Record, Idx);
5803 return Context.getPointerType(PointeeType);
5804 }
5805
Reid Kleckner8a365022013-06-24 17:51:48 +00005806 case TYPE_DECAYED: {
5807 if (Record.size() != 1) {
5808 Error("Incorrect encoding of decayed type");
5809 return QualType();
5810 }
5811 QualType OriginalType = readType(*Loc.F, Record, Idx);
5812 QualType DT = Context.getAdjustedParameterType(OriginalType);
5813 if (!isa<DecayedType>(DT))
5814 Error("Decayed type does not decay");
5815 return DT;
5816 }
5817
Reid Kleckner0503a872013-12-05 01:23:43 +00005818 case TYPE_ADJUSTED: {
5819 if (Record.size() != 2) {
5820 Error("Incorrect encoding of adjusted type");
5821 return QualType();
5822 }
5823 QualType OriginalTy = readType(*Loc.F, Record, Idx);
5824 QualType AdjustedTy = readType(*Loc.F, Record, Idx);
5825 return Context.getAdjustedType(OriginalTy, AdjustedTy);
5826 }
5827
Guy Benyei11169dd2012-12-18 14:30:41 +00005828 case TYPE_BLOCK_POINTER: {
5829 if (Record.size() != 1) {
5830 Error("Incorrect encoding of block pointer type");
5831 return QualType();
5832 }
5833 QualType PointeeType = readType(*Loc.F, Record, Idx);
5834 return Context.getBlockPointerType(PointeeType);
5835 }
5836
5837 case TYPE_LVALUE_REFERENCE: {
5838 if (Record.size() != 2) {
5839 Error("Incorrect encoding of lvalue reference type");
5840 return QualType();
5841 }
5842 QualType PointeeType = readType(*Loc.F, Record, Idx);
5843 return Context.getLValueReferenceType(PointeeType, Record[1]);
5844 }
5845
5846 case TYPE_RVALUE_REFERENCE: {
5847 if (Record.size() != 1) {
5848 Error("Incorrect encoding of rvalue reference type");
5849 return QualType();
5850 }
5851 QualType PointeeType = readType(*Loc.F, Record, Idx);
5852 return Context.getRValueReferenceType(PointeeType);
5853 }
5854
5855 case TYPE_MEMBER_POINTER: {
5856 if (Record.size() != 2) {
5857 Error("Incorrect encoding of member pointer type");
5858 return QualType();
5859 }
5860 QualType PointeeType = readType(*Loc.F, Record, Idx);
5861 QualType ClassType = readType(*Loc.F, Record, Idx);
5862 if (PointeeType.isNull() || ClassType.isNull())
5863 return QualType();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005864
Guy Benyei11169dd2012-12-18 14:30:41 +00005865 return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
5866 }
5867
5868 case TYPE_CONSTANT_ARRAY: {
5869 QualType ElementType = readType(*Loc.F, Record, Idx);
5870 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5871 unsigned IndexTypeQuals = Record[2];
5872 unsigned Idx = 3;
5873 llvm::APInt Size = ReadAPInt(Record, Idx);
5874 return Context.getConstantArrayType(ElementType, Size,
5875 ASM, IndexTypeQuals);
5876 }
5877
5878 case TYPE_INCOMPLETE_ARRAY: {
5879 QualType ElementType = readType(*Loc.F, Record, Idx);
5880 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5881 unsigned IndexTypeQuals = Record[2];
5882 return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
5883 }
5884
5885 case TYPE_VARIABLE_ARRAY: {
5886 QualType ElementType = readType(*Loc.F, Record, Idx);
5887 ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
5888 unsigned IndexTypeQuals = Record[2];
5889 SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
5890 SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
5891 return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
5892 ASM, IndexTypeQuals,
5893 SourceRange(LBLoc, RBLoc));
5894 }
5895
5896 case TYPE_VECTOR: {
5897 if (Record.size() != 3) {
5898 Error("incorrect encoding of vector type in AST file");
5899 return QualType();
5900 }
5901
5902 QualType ElementType = readType(*Loc.F, Record, Idx);
5903 unsigned NumElements = Record[1];
5904 unsigned VecKind = Record[2];
5905 return Context.getVectorType(ElementType, NumElements,
5906 (VectorType::VectorKind)VecKind);
5907 }
5908
5909 case TYPE_EXT_VECTOR: {
5910 if (Record.size() != 3) {
5911 Error("incorrect encoding of extended vector type in AST file");
5912 return QualType();
5913 }
5914
5915 QualType ElementType = readType(*Loc.F, Record, Idx);
5916 unsigned NumElements = Record[1];
5917 return Context.getExtVectorType(ElementType, NumElements);
5918 }
5919
5920 case TYPE_FUNCTION_NO_PROTO: {
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005921 if (Record.size() != 7) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005922 Error("incorrect encoding of no-proto function type");
5923 return QualType();
5924 }
5925 QualType ResultType = readType(*Loc.F, Record, Idx);
5926 FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005927 (CallingConv)Record[4], Record[5], Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005928 return Context.getFunctionNoProtoType(ResultType, Info);
5929 }
5930
5931 case TYPE_FUNCTION_PROTO: {
5932 QualType ResultType = readType(*Loc.F, Record, Idx);
5933
5934 FunctionProtoType::ExtProtoInfo EPI;
5935 EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
5936 /*hasregparm*/ Record[2],
5937 /*regparm*/ Record[3],
5938 static_cast<CallingConv>(Record[4]),
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005939 /*produces*/ Record[5],
5940 /*nocallersavedregs*/ Record[6]);
Guy Benyei11169dd2012-12-18 14:30:41 +00005941
Oren Ben Simhon318a6ea2017-04-27 12:01:00 +00005942 unsigned Idx = 7;
Guy Benyei11169dd2012-12-18 14:30:41 +00005943
5944 EPI.Variadic = Record[Idx++];
5945 EPI.HasTrailingReturn = Record[Idx++];
5946 EPI.TypeQuals = Record[Idx++];
5947 EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
Richard Smith564417a2014-03-20 21:47:22 +00005948 SmallVector<QualType, 8> ExceptionStorage;
Richard Smith8acb4282014-07-31 21:57:55 +00005949 readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
Richard Smith01b2cb42014-07-26 06:37:51 +00005950
5951 unsigned NumParams = Record[Idx++];
5952 SmallVector<QualType, 16> ParamTypes;
5953 for (unsigned I = 0; I != NumParams; ++I)
5954 ParamTypes.push_back(readType(*Loc.F, Record, Idx));
5955
John McCall18afab72016-03-01 00:49:02 +00005956 SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
5957 if (Idx != Record.size()) {
5958 for (unsigned I = 0; I != NumParams; ++I)
5959 ExtParameterInfos.push_back(
5960 FunctionProtoType::ExtParameterInfo
5961 ::getFromOpaqueValue(Record[Idx++]));
5962 EPI.ExtParameterInfos = ExtParameterInfos.data();
5963 }
5964
5965 assert(Idx == Record.size());
5966
Jordan Rose5c382722013-03-08 21:51:21 +00005967 return Context.getFunctionType(ResultType, ParamTypes, EPI);
Guy Benyei11169dd2012-12-18 14:30:41 +00005968 }
5969
5970 case TYPE_UNRESOLVED_USING: {
5971 unsigned Idx = 0;
5972 return Context.getTypeDeclType(
5973 ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
5974 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00005975
Guy Benyei11169dd2012-12-18 14:30:41 +00005976 case TYPE_TYPEDEF: {
5977 if (Record.size() != 2) {
5978 Error("incorrect encoding of typedef type");
5979 return QualType();
5980 }
5981 unsigned Idx = 0;
5982 TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
5983 QualType Canonical = readType(*Loc.F, Record, Idx);
5984 if (!Canonical.isNull())
5985 Canonical = Context.getCanonicalType(Canonical);
5986 return Context.getTypedefType(Decl, Canonical);
5987 }
5988
5989 case TYPE_TYPEOF_EXPR:
5990 return Context.getTypeOfExprType(ReadExpr(*Loc.F));
5991
5992 case TYPE_TYPEOF: {
5993 if (Record.size() != 1) {
5994 Error("incorrect encoding of typeof(type) in AST file");
5995 return QualType();
5996 }
5997 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
5998 return Context.getTypeOfType(UnderlyingType);
5999 }
6000
6001 case TYPE_DECLTYPE: {
6002 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6003 return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
6004 }
6005
6006 case TYPE_UNARY_TRANSFORM: {
6007 QualType BaseType = readType(*Loc.F, Record, Idx);
6008 QualType UnderlyingType = readType(*Loc.F, Record, Idx);
6009 UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
6010 return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
6011 }
6012
Richard Smith74aeef52013-04-26 16:15:35 +00006013 case TYPE_AUTO: {
6014 QualType Deduced = readType(*Loc.F, Record, Idx);
Richard Smithe301ba22015-11-11 02:02:15 +00006015 AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
Richard Smith27d807c2013-04-30 13:56:41 +00006016 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
Richard Smithe301ba22015-11-11 02:02:15 +00006017 return Context.getAutoType(Deduced, Keyword, IsDependent);
Richard Smith74aeef52013-04-26 16:15:35 +00006018 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006019
Richard Smith600b5262017-01-26 20:40:47 +00006020 case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
6021 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6022 QualType Deduced = readType(*Loc.F, Record, Idx);
6023 bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
6024 return Context.getDeducedTemplateSpecializationType(Name, Deduced,
6025 IsDependent);
6026 }
6027
Guy Benyei11169dd2012-12-18 14:30:41 +00006028 case TYPE_RECORD: {
6029 if (Record.size() != 2) {
6030 Error("incorrect encoding of record type");
6031 return QualType();
6032 }
6033 unsigned Idx = 0;
6034 bool IsDependent = Record[Idx++];
6035 RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
6036 RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
6037 QualType T = Context.getRecordType(RD);
6038 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6039 return T;
6040 }
6041
6042 case TYPE_ENUM: {
6043 if (Record.size() != 2) {
6044 Error("incorrect encoding of enum type");
6045 return QualType();
6046 }
6047 unsigned Idx = 0;
6048 bool IsDependent = Record[Idx++];
6049 QualType T
6050 = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
6051 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6052 return T;
6053 }
6054
6055 case TYPE_ATTRIBUTED: {
6056 if (Record.size() != 3) {
6057 Error("incorrect encoding of attributed type");
6058 return QualType();
6059 }
6060 QualType modifiedType = readType(*Loc.F, Record, Idx);
6061 QualType equivalentType = readType(*Loc.F, Record, Idx);
6062 AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
6063 return Context.getAttributedType(kind, modifiedType, equivalentType);
6064 }
6065
6066 case TYPE_PAREN: {
6067 if (Record.size() != 1) {
6068 Error("incorrect encoding of paren type");
6069 return QualType();
6070 }
6071 QualType InnerType = readType(*Loc.F, Record, Idx);
6072 return Context.getParenType(InnerType);
6073 }
6074
6075 case TYPE_PACK_EXPANSION: {
6076 if (Record.size() != 2) {
6077 Error("incorrect encoding of pack expansion type");
6078 return QualType();
6079 }
6080 QualType Pattern = readType(*Loc.F, Record, Idx);
6081 if (Pattern.isNull())
6082 return QualType();
David Blaikie05785d12013-02-20 22:23:23 +00006083 Optional<unsigned> NumExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00006084 if (Record[1])
6085 NumExpansions = Record[1] - 1;
6086 return Context.getPackExpansionType(Pattern, NumExpansions);
6087 }
6088
6089 case TYPE_ELABORATED: {
6090 unsigned Idx = 0;
6091 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6092 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
6093 QualType NamedType = readType(*Loc.F, Record, Idx);
6094 return Context.getElaboratedType(Keyword, NNS, NamedType);
6095 }
6096
6097 case TYPE_OBJC_INTERFACE: {
6098 unsigned Idx = 0;
6099 ObjCInterfaceDecl *ItfD
6100 = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
6101 return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
6102 }
6103
Manman Rene6be26c2016-09-13 17:25:08 +00006104 case TYPE_OBJC_TYPE_PARAM: {
6105 unsigned Idx = 0;
6106 ObjCTypeParamDecl *Decl
6107 = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
6108 unsigned NumProtos = Record[Idx++];
6109 SmallVector<ObjCProtocolDecl*, 4> Protos;
6110 for (unsigned I = 0; I != NumProtos; ++I)
6111 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
6112 return Context.getObjCTypeParamType(Decl, Protos);
6113 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006114 case TYPE_OBJC_OBJECT: {
6115 unsigned Idx = 0;
6116 QualType Base = readType(*Loc.F, Record, Idx);
Douglas Gregore9d95f12015-07-07 03:57:35 +00006117 unsigned NumTypeArgs = Record[Idx++];
6118 SmallVector<QualType, 4> TypeArgs;
6119 for (unsigned I = 0; I != NumTypeArgs; ++I)
6120 TypeArgs.push_back(readType(*Loc.F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006121 unsigned NumProtos = Record[Idx++];
6122 SmallVector<ObjCProtocolDecl*, 4> Protos;
6123 for (unsigned I = 0; I != NumProtos; ++I)
6124 Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
Douglas Gregorab209d82015-07-07 03:58:42 +00006125 bool IsKindOf = Record[Idx++];
6126 return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
Guy Benyei11169dd2012-12-18 14:30:41 +00006127 }
6128
6129 case TYPE_OBJC_OBJECT_POINTER: {
6130 unsigned Idx = 0;
6131 QualType Pointee = readType(*Loc.F, Record, Idx);
6132 return Context.getObjCObjectPointerType(Pointee);
6133 }
6134
6135 case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
6136 unsigned Idx = 0;
6137 QualType Parm = readType(*Loc.F, Record, Idx);
6138 QualType Replacement = readType(*Loc.F, Record, Idx);
Stephan Tolksdorfe96f8b32014-03-15 10:23:27 +00006139 return Context.getSubstTemplateTypeParmType(
6140 cast<TemplateTypeParmType>(Parm),
6141 Context.getCanonicalType(Replacement));
Guy Benyei11169dd2012-12-18 14:30:41 +00006142 }
6143
6144 case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
6145 unsigned Idx = 0;
6146 QualType Parm = readType(*Loc.F, Record, Idx);
6147 TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
6148 return Context.getSubstTemplateTypeParmPackType(
6149 cast<TemplateTypeParmType>(Parm),
6150 ArgPack);
6151 }
6152
6153 case TYPE_INJECTED_CLASS_NAME: {
6154 CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
6155 QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
6156 // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
6157 // for AST reading, too much interdependencies.
Richard Smith6377f8f2014-10-21 21:15:18 +00006158 const Type *T = nullptr;
6159 for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
6160 if (const Type *Existing = DI->getTypeForDecl()) {
6161 T = Existing;
6162 break;
6163 }
6164 }
6165 if (!T) {
Richard Smithf17fdbd2014-04-24 02:25:27 +00006166 T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
Richard Smith6377f8f2014-10-21 21:15:18 +00006167 for (auto *DI = D; DI; DI = DI->getPreviousDecl())
6168 DI->setTypeForDecl(T);
6169 }
Richard Smithf17fdbd2014-04-24 02:25:27 +00006170 return QualType(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00006171 }
6172
6173 case TYPE_TEMPLATE_TYPE_PARM: {
6174 unsigned Idx = 0;
6175 unsigned Depth = Record[Idx++];
6176 unsigned Index = Record[Idx++];
6177 bool Pack = Record[Idx++];
6178 TemplateTypeParmDecl *D
6179 = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
6180 return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
6181 }
6182
6183 case TYPE_DEPENDENT_NAME: {
6184 unsigned Idx = 0;
6185 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6186 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006187 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006188 QualType Canon = readType(*Loc.F, Record, Idx);
6189 if (!Canon.isNull())
6190 Canon = Context.getCanonicalType(Canon);
6191 return Context.getDependentNameType(Keyword, NNS, Name, Canon);
6192 }
6193
6194 case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
6195 unsigned Idx = 0;
6196 ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
6197 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
Richard Smithbdf2d932015-07-30 03:37:16 +00006198 const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006199 unsigned NumArgs = Record[Idx++];
6200 SmallVector<TemplateArgument, 8> Args;
6201 Args.reserve(NumArgs);
6202 while (NumArgs--)
6203 Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
6204 return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
David Majnemer6fbeee32016-07-07 04:43:07 +00006205 Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006206 }
6207
6208 case TYPE_DEPENDENT_SIZED_ARRAY: {
6209 unsigned Idx = 0;
6210
6211 // ArrayType
6212 QualType ElementType = readType(*Loc.F, Record, Idx);
6213 ArrayType::ArraySizeModifier ASM
6214 = (ArrayType::ArraySizeModifier)Record[Idx++];
6215 unsigned IndexTypeQuals = Record[Idx++];
6216
6217 // DependentSizedArrayType
6218 Expr *NumElts = ReadExpr(*Loc.F);
6219 SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
6220
6221 return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
6222 IndexTypeQuals, Brackets);
6223 }
6224
6225 case TYPE_TEMPLATE_SPECIALIZATION: {
6226 unsigned Idx = 0;
6227 bool IsDependent = Record[Idx++];
6228 TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
6229 SmallVector<TemplateArgument, 8> Args;
6230 ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
6231 QualType Underlying = readType(*Loc.F, Record, Idx);
6232 QualType T;
6233 if (Underlying.isNull())
David Majnemer6fbeee32016-07-07 04:43:07 +00006234 T = Context.getCanonicalTemplateSpecializationType(Name, Args);
Guy Benyei11169dd2012-12-18 14:30:41 +00006235 else
David Majnemer6fbeee32016-07-07 04:43:07 +00006236 T = Context.getTemplateSpecializationType(Name, Args, Underlying);
Guy Benyei11169dd2012-12-18 14:30:41 +00006237 const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
6238 return T;
6239 }
6240
6241 case TYPE_ATOMIC: {
6242 if (Record.size() != 1) {
6243 Error("Incorrect encoding of atomic type");
6244 return QualType();
6245 }
6246 QualType ValueType = readType(*Loc.F, Record, Idx);
6247 return Context.getAtomicType(ValueType);
6248 }
Xiuli Pan9c14e282016-01-09 12:53:17 +00006249
Joey Goulye3c85de2016-12-01 11:30:49 +00006250 case TYPE_PIPE: {
6251 if (Record.size() != 2) {
Xiuli Pan9c14e282016-01-09 12:53:17 +00006252 Error("Incorrect encoding of pipe type");
6253 return QualType();
6254 }
6255
6256 // Reading the pipe element type.
6257 QualType ElementType = readType(*Loc.F, Record, Idx);
Joey Goulye3c85de2016-12-01 11:30:49 +00006258 unsigned ReadOnly = Record[1];
6259 return Context.getPipeType(ElementType, ReadOnly);
Joey Gouly5788b782016-11-18 14:10:54 +00006260 }
6261
Alex Lorenz00aee432017-03-22 10:04:48 +00006262 case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
6263 unsigned Idx = 0;
6264
6265 // DependentSizedExtVectorType
6266 QualType ElementType = readType(*Loc.F, Record, Idx);
6267 Expr *SizeExpr = ReadExpr(*Loc.F);
6268 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6269
6270 return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
6271 AttrLoc);
6272 }
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006273
6274 case TYPE_DEPENDENT_ADDRESS_SPACE: {
6275 unsigned Idx = 0;
6276
6277 // DependentAddressSpaceType
6278 QualType PointeeType = readType(*Loc.F, Record, Idx);
6279 Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
6280 SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
6281
6282 return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
6283 AttrLoc);
6284 }
Guy Benyei11169dd2012-12-18 14:30:41 +00006285 }
6286 llvm_unreachable("Invalid TypeCode!");
6287}
6288
Richard Smith564417a2014-03-20 21:47:22 +00006289void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
6290 SmallVectorImpl<QualType> &Exceptions,
Richard Smith8acb4282014-07-31 21:57:55 +00006291 FunctionProtoType::ExceptionSpecInfo &ESI,
Richard Smith564417a2014-03-20 21:47:22 +00006292 const RecordData &Record, unsigned &Idx) {
6293 ExceptionSpecificationType EST =
6294 static_cast<ExceptionSpecificationType>(Record[Idx++]);
Richard Smith8acb4282014-07-31 21:57:55 +00006295 ESI.Type = EST;
Richard Smith564417a2014-03-20 21:47:22 +00006296 if (EST == EST_Dynamic) {
Richard Smith8acb4282014-07-31 21:57:55 +00006297 for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
Richard Smith564417a2014-03-20 21:47:22 +00006298 Exceptions.push_back(readType(ModuleFile, Record, Idx));
Richard Smith8acb4282014-07-31 21:57:55 +00006299 ESI.Exceptions = Exceptions;
Richard Smith564417a2014-03-20 21:47:22 +00006300 } else if (EST == EST_ComputedNoexcept) {
Richard Smith8acb4282014-07-31 21:57:55 +00006301 ESI.NoexceptExpr = ReadExpr(ModuleFile);
Richard Smith564417a2014-03-20 21:47:22 +00006302 } else if (EST == EST_Uninstantiated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006303 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
6304 ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006305 } else if (EST == EST_Unevaluated) {
Richard Smith8acb4282014-07-31 21:57:55 +00006306 ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
Richard Smith564417a2014-03-20 21:47:22 +00006307 }
6308}
6309
Guy Benyei11169dd2012-12-18 14:30:41 +00006310class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006311 ModuleFile *F;
6312 ASTReader *Reader;
6313 const ASTReader::RecordData &Record;
Guy Benyei11169dd2012-12-18 14:30:41 +00006314 unsigned &Idx;
6315
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006316 SourceLocation ReadSourceLocation() {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006317 return Reader->ReadSourceLocation(*F, Record, Idx);
6318 }
6319
6320 TypeSourceInfo *GetTypeSourceInfo() {
6321 return Reader->GetTypeSourceInfo(*F, Record, Idx);
6322 }
6323
6324 NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
6325 return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006326 }
6327
Guy Benyei11169dd2012-12-18 14:30:41 +00006328public:
David L. Jonesbe1557a2016-12-21 00:17:49 +00006329 TypeLocReader(ModuleFile &F, ASTReader &Reader,
Guy Benyei11169dd2012-12-18 14:30:41 +00006330 const ASTReader::RecordData &Record, unsigned &Idx)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006331 : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
Guy Benyei11169dd2012-12-18 14:30:41 +00006332
6333 // We want compile-time assurance that we've enumerated all of
6334 // these, so unfortunately we have to declare them first, then
6335 // define them out-of-line.
6336#define ABSTRACT_TYPELOC(CLASS, PARENT)
6337#define TYPELOC(CLASS, PARENT) \
6338 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
6339#include "clang/AST/TypeLocNodes.def"
6340
6341 void VisitFunctionTypeLoc(FunctionTypeLoc);
6342 void VisitArrayTypeLoc(ArrayTypeLoc);
6343};
6344
6345void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6346 // nothing to do
6347}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006348
Guy Benyei11169dd2012-12-18 14:30:41 +00006349void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006350 TL.setBuiltinLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006351 if (TL.needsExtraLocalData()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006352 TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
6353 TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
6354 TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
6355 TL.setModeAttr(Record[Idx++]);
Guy Benyei11169dd2012-12-18 14:30:41 +00006356 }
6357}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006358
Guy Benyei11169dd2012-12-18 14:30:41 +00006359void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006360 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006361}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006362
Guy Benyei11169dd2012-12-18 14:30:41 +00006363void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006364 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006365}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006366
Reid Kleckner8a365022013-06-24 17:51:48 +00006367void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6368 // nothing to do
6369}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006370
Reid Kleckner0503a872013-12-05 01:23:43 +00006371void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6372 // nothing to do
6373}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006374
Guy Benyei11169dd2012-12-18 14:30:41 +00006375void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006376 TL.setCaretLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006377}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006378
Guy Benyei11169dd2012-12-18 14:30:41 +00006379void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006380 TL.setAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006381}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006382
Guy Benyei11169dd2012-12-18 14:30:41 +00006383void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006384 TL.setAmpAmpLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006385}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006386
Guy Benyei11169dd2012-12-18 14:30:41 +00006387void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006388 TL.setStarLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006389 TL.setClassTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006390}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006391
Guy Benyei11169dd2012-12-18 14:30:41 +00006392void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006393 TL.setLBracketLoc(ReadSourceLocation());
6394 TL.setRBracketLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006395 if (Record[Idx++])
6396 TL.setSizeExpr(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006397 else
Craig Toppera13603a2014-05-22 05:54:18 +00006398 TL.setSizeExpr(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006399}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006400
Guy Benyei11169dd2012-12-18 14:30:41 +00006401void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
6402 VisitArrayTypeLoc(TL);
6403}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006404
Guy Benyei11169dd2012-12-18 14:30:41 +00006405void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
6406 VisitArrayTypeLoc(TL);
6407}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006408
Guy Benyei11169dd2012-12-18 14:30:41 +00006409void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
6410 VisitArrayTypeLoc(TL);
6411}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006412
Guy Benyei11169dd2012-12-18 14:30:41 +00006413void TypeLocReader::VisitDependentSizedArrayTypeLoc(
6414 DependentSizedArrayTypeLoc TL) {
6415 VisitArrayTypeLoc(TL);
6416}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006417
Andrew Gozillon572bbb02017-10-02 06:25:51 +00006418void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
6419 DependentAddressSpaceTypeLoc TL) {
6420
6421 TL.setAttrNameLoc(ReadSourceLocation());
6422 SourceRange range;
6423 range.setBegin(ReadSourceLocation());
6424 range.setEnd(ReadSourceLocation());
6425 TL.setAttrOperandParensRange(range);
6426 TL.setAttrExprOperand(Reader->ReadExpr(*F));
6427}
6428
Guy Benyei11169dd2012-12-18 14:30:41 +00006429void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
6430 DependentSizedExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006431 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006432}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006433
Guy Benyei11169dd2012-12-18 14:30:41 +00006434void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006435 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006436}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006437
Guy Benyei11169dd2012-12-18 14:30:41 +00006438void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006439 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006440}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006441
Guy Benyei11169dd2012-12-18 14:30:41 +00006442void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006443 TL.setLocalRangeBegin(ReadSourceLocation());
6444 TL.setLParenLoc(ReadSourceLocation());
6445 TL.setRParenLoc(ReadSourceLocation());
Malcolm Parsonsa3220ce2017-01-12 16:11:28 +00006446 TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
6447 Reader->ReadSourceLocation(*F, Record, Idx)));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006448 TL.setLocalRangeEnd(ReadSourceLocation());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006449 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006450 TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006451 }
6452}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006453
Guy Benyei11169dd2012-12-18 14:30:41 +00006454void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
6455 VisitFunctionTypeLoc(TL);
6456}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006457
Guy Benyei11169dd2012-12-18 14:30:41 +00006458void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
6459 VisitFunctionTypeLoc(TL);
6460}
6461void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006462 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006463}
6464void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006465 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006466}
6467void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006468 TL.setTypeofLoc(ReadSourceLocation());
6469 TL.setLParenLoc(ReadSourceLocation());
6470 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006471}
6472void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006473 TL.setTypeofLoc(ReadSourceLocation());
6474 TL.setLParenLoc(ReadSourceLocation());
6475 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006476 TL.setUnderlyingTInfo(GetTypeSourceInfo());
Guy Benyei11169dd2012-12-18 14:30:41 +00006477}
6478void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006479 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006480}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006481
Guy Benyei11169dd2012-12-18 14:30:41 +00006482void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006483 TL.setKWLoc(ReadSourceLocation());
6484 TL.setLParenLoc(ReadSourceLocation());
6485 TL.setRParenLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006486 TL.setUnderlyingTInfo(GetTypeSourceInfo());
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::VisitAutoTypeLoc(AutoTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006490 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006491}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006492
Richard Smith600b5262017-01-26 20:40:47 +00006493void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
6494 DeducedTemplateSpecializationTypeLoc TL) {
6495 TL.setTemplateNameLoc(ReadSourceLocation());
6496}
6497
Guy Benyei11169dd2012-12-18 14:30:41 +00006498void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006499 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006500}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006501
Guy Benyei11169dd2012-12-18 14:30:41 +00006502void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006503 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006504}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006505
Guy Benyei11169dd2012-12-18 14:30:41 +00006506void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006507 TL.setAttrNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006508 if (TL.hasAttrOperand()) {
6509 SourceRange range;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006510 range.setBegin(ReadSourceLocation());
6511 range.setEnd(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006512 TL.setAttrOperandParensRange(range);
6513 }
6514 if (TL.hasAttrExprOperand()) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006515 if (Record[Idx++])
6516 TL.setAttrExprOperand(Reader->ReadExpr(*F));
Guy Benyei11169dd2012-12-18 14:30:41 +00006517 else
Craig Toppera13603a2014-05-22 05:54:18 +00006518 TL.setAttrExprOperand(nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00006519 } else if (TL.hasAttrEnumOperand())
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006520 TL.setAttrEnumOperandLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006521}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006522
Guy Benyei11169dd2012-12-18 14:30:41 +00006523void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006524 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006525}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006526
Guy Benyei11169dd2012-12-18 14:30:41 +00006527void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
6528 SubstTemplateTypeParmTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006529 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006530}
6531void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
6532 SubstTemplateTypeParmPackTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006533 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006534}
6535void TypeLocReader::VisitTemplateSpecializationTypeLoc(
6536 TemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006537 TL.setTemplateKeywordLoc(ReadSourceLocation());
6538 TL.setTemplateNameLoc(ReadSourceLocation());
6539 TL.setLAngleLoc(ReadSourceLocation());
6540 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006541 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006542 TL.setArgLocInfo(
6543 i,
6544 Reader->GetTemplateArgumentLocInfo(
6545 *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006546}
6547void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006548 TL.setLParenLoc(ReadSourceLocation());
6549 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006550}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006551
Guy Benyei11169dd2012-12-18 14:30:41 +00006552void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006553 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006554 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
Guy Benyei11169dd2012-12-18 14:30:41 +00006555}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006556
Guy Benyei11169dd2012-12-18 14:30:41 +00006557void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006558 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006559}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006560
Guy Benyei11169dd2012-12-18 14:30:41 +00006561void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006562 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006563 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006564 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006565}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006566
Guy Benyei11169dd2012-12-18 14:30:41 +00006567void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
6568 DependentTemplateSpecializationTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006569 TL.setElaboratedKeywordLoc(ReadSourceLocation());
David L. Jonesbe1557a2016-12-21 00:17:49 +00006570 TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006571 TL.setTemplateKeywordLoc(ReadSourceLocation());
6572 TL.setTemplateNameLoc(ReadSourceLocation());
6573 TL.setLAngleLoc(ReadSourceLocation());
6574 TL.setRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006575 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006576 TL.setArgLocInfo(
6577 I,
6578 Reader->GetTemplateArgumentLocInfo(
6579 *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00006580}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006581
Guy Benyei11169dd2012-12-18 14:30:41 +00006582void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006583 TL.setEllipsisLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006584}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006585
Guy Benyei11169dd2012-12-18 14:30:41 +00006586void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006587 TL.setNameLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006588}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006589
Manman Rene6be26c2016-09-13 17:25:08 +00006590void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
6591 if (TL.getNumProtocols()) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006592 TL.setProtocolLAngleLoc(ReadSourceLocation());
6593 TL.setProtocolRAngleLoc(ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006594 }
6595 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006596 TL.setProtocolLoc(i, ReadSourceLocation());
Manman Rene6be26c2016-09-13 17:25:08 +00006597}
6598
Guy Benyei11169dd2012-12-18 14:30:41 +00006599void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
David L. Jonesbe1557a2016-12-21 00:17:49 +00006600 TL.setHasBaseTypeAsWritten(Record[Idx++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006601 TL.setTypeArgsLAngleLoc(ReadSourceLocation());
6602 TL.setTypeArgsRAngleLoc(ReadSourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +00006603 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
David L. Jonesbe1557a2016-12-21 00:17:49 +00006604 TL.setTypeArgTInfo(i, GetTypeSourceInfo());
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006605 TL.setProtocolLAngleLoc(ReadSourceLocation());
6606 TL.setProtocolRAngleLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006607 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006608 TL.setProtocolLoc(i, ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006609}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006610
Guy Benyei11169dd2012-12-18 14:30:41 +00006611void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006612 TL.setStarLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006613}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006614
Guy Benyei11169dd2012-12-18 14:30:41 +00006615void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006616 TL.setKWLoc(ReadSourceLocation());
6617 TL.setLParenLoc(ReadSourceLocation());
6618 TL.setRParenLoc(ReadSourceLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00006619}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00006620
Xiuli Pan9c14e282016-01-09 12:53:17 +00006621void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006622 TL.setKWLoc(ReadSourceLocation());
Xiuli Pan9c14e282016-01-09 12:53:17 +00006623}
Guy Benyei11169dd2012-12-18 14:30:41 +00006624
David L. Jonesbe1557a2016-12-21 00:17:49 +00006625TypeSourceInfo *
6626ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
6627 unsigned &Idx) {
Guy Benyei11169dd2012-12-18 14:30:41 +00006628 QualType InfoTy = readType(F, Record, Idx);
6629 if (InfoTy.isNull())
Craig Toppera13603a2014-05-22 05:54:18 +00006630 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006631
6632 TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
David L. Jonesbe1557a2016-12-21 00:17:49 +00006633 TypeLocReader TLR(F, *this, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00006634 for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
6635 TLR.Visit(TL);
6636 return TInfo;
6637}
6638
6639QualType ASTReader::GetType(TypeID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006640 assert(ContextObj && "reading type with no AST context");
6641 ASTContext &Context = *ContextObj;
6642
Guy Benyei11169dd2012-12-18 14:30:41 +00006643 unsigned FastQuals = ID & Qualifiers::FastMask;
6644 unsigned Index = ID >> Qualifiers::FastWidth;
6645
6646 if (Index < NUM_PREDEF_TYPE_IDS) {
6647 QualType T;
6648 switch ((PredefinedTypeIDs)Index) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00006649 case PREDEF_TYPE_NULL_ID:
6650 return QualType();
6651 case PREDEF_TYPE_VOID_ID:
6652 T = Context.VoidTy;
6653 break;
6654 case PREDEF_TYPE_BOOL_ID:
6655 T = Context.BoolTy;
6656 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006657
6658 case PREDEF_TYPE_CHAR_U_ID:
6659 case PREDEF_TYPE_CHAR_S_ID:
6660 // FIXME: Check that the signedness of CharTy is correct!
6661 T = Context.CharTy;
6662 break;
6663
Alexey Baderbdf7c842015-09-15 12:18:29 +00006664 case PREDEF_TYPE_UCHAR_ID:
6665 T = Context.UnsignedCharTy;
6666 break;
6667 case PREDEF_TYPE_USHORT_ID:
6668 T = Context.UnsignedShortTy;
6669 break;
6670 case PREDEF_TYPE_UINT_ID:
6671 T = Context.UnsignedIntTy;
6672 break;
6673 case PREDEF_TYPE_ULONG_ID:
6674 T = Context.UnsignedLongTy;
6675 break;
6676 case PREDEF_TYPE_ULONGLONG_ID:
6677 T = Context.UnsignedLongLongTy;
6678 break;
6679 case PREDEF_TYPE_UINT128_ID:
6680 T = Context.UnsignedInt128Ty;
6681 break;
6682 case PREDEF_TYPE_SCHAR_ID:
6683 T = Context.SignedCharTy;
6684 break;
6685 case PREDEF_TYPE_WCHAR_ID:
6686 T = Context.WCharTy;
6687 break;
6688 case PREDEF_TYPE_SHORT_ID:
6689 T = Context.ShortTy;
6690 break;
6691 case PREDEF_TYPE_INT_ID:
6692 T = Context.IntTy;
6693 break;
6694 case PREDEF_TYPE_LONG_ID:
6695 T = Context.LongTy;
6696 break;
6697 case PREDEF_TYPE_LONGLONG_ID:
6698 T = Context.LongLongTy;
6699 break;
6700 case PREDEF_TYPE_INT128_ID:
6701 T = Context.Int128Ty;
6702 break;
6703 case PREDEF_TYPE_HALF_ID:
6704 T = Context.HalfTy;
6705 break;
6706 case PREDEF_TYPE_FLOAT_ID:
6707 T = Context.FloatTy;
6708 break;
6709 case PREDEF_TYPE_DOUBLE_ID:
6710 T = Context.DoubleTy;
6711 break;
6712 case PREDEF_TYPE_LONGDOUBLE_ID:
6713 T = Context.LongDoubleTy;
6714 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00006715 case PREDEF_TYPE_FLOAT16_ID:
6716 T = Context.Float16Ty;
6717 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00006718 case PREDEF_TYPE_FLOAT128_ID:
6719 T = Context.Float128Ty;
6720 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006721 case PREDEF_TYPE_OVERLOAD_ID:
6722 T = Context.OverloadTy;
6723 break;
6724 case PREDEF_TYPE_BOUND_MEMBER:
6725 T = Context.BoundMemberTy;
6726 break;
6727 case PREDEF_TYPE_PSEUDO_OBJECT:
6728 T = Context.PseudoObjectTy;
6729 break;
6730 case PREDEF_TYPE_DEPENDENT_ID:
6731 T = Context.DependentTy;
6732 break;
6733 case PREDEF_TYPE_UNKNOWN_ANY:
6734 T = Context.UnknownAnyTy;
6735 break;
6736 case PREDEF_TYPE_NULLPTR_ID:
6737 T = Context.NullPtrTy;
6738 break;
6739 case PREDEF_TYPE_CHAR16_ID:
6740 T = Context.Char16Ty;
6741 break;
6742 case PREDEF_TYPE_CHAR32_ID:
6743 T = Context.Char32Ty;
6744 break;
6745 case PREDEF_TYPE_OBJC_ID:
6746 T = Context.ObjCBuiltinIdTy;
6747 break;
6748 case PREDEF_TYPE_OBJC_CLASS:
6749 T = Context.ObjCBuiltinClassTy;
6750 break;
6751 case PREDEF_TYPE_OBJC_SEL:
6752 T = Context.ObjCBuiltinSelTy;
6753 break;
Alexey Bader954ba212016-04-08 13:40:33 +00006754#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6755 case PREDEF_TYPE_##Id##_ID: \
6756 T = Context.SingletonId; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00006757 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00006758#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00006759 case PREDEF_TYPE_SAMPLER_ID:
6760 T = Context.OCLSamplerTy;
6761 break;
6762 case PREDEF_TYPE_EVENT_ID:
6763 T = Context.OCLEventTy;
6764 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006765 case PREDEF_TYPE_CLK_EVENT_ID:
6766 T = Context.OCLClkEventTy;
6767 break;
6768 case PREDEF_TYPE_QUEUE_ID:
6769 T = Context.OCLQueueTy;
6770 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00006771 case PREDEF_TYPE_RESERVE_ID_ID:
6772 T = Context.OCLReserveIDTy;
6773 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00006774 case PREDEF_TYPE_AUTO_DEDUCT:
6775 T = Context.getAutoDeductType();
6776 break;
6777
6778 case PREDEF_TYPE_AUTO_RREF_DEDUCT:
6779 T = Context.getAutoRRefDeductType();
Guy Benyei11169dd2012-12-18 14:30:41 +00006780 break;
6781
6782 case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
6783 T = Context.ARCUnbridgedCastTy;
6784 break;
6785
Guy Benyei11169dd2012-12-18 14:30:41 +00006786 case PREDEF_TYPE_BUILTIN_FN:
6787 T = Context.BuiltinFnTy;
6788 break;
Alexey Bataev1a3320e2015-08-25 14:24:04 +00006789
6790 case PREDEF_TYPE_OMP_ARRAY_SECTION:
6791 T = Context.OMPArraySectionTy;
6792 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00006793 }
6794
6795 assert(!T.isNull() && "Unknown predefined type");
6796 return T.withFastQualifiers(FastQuals);
6797 }
6798
6799 Index -= NUM_PREDEF_TYPE_IDS;
6800 assert(Index < TypesLoaded.size() && "Type index out-of-range");
6801 if (TypesLoaded[Index].isNull()) {
6802 TypesLoaded[Index] = readTypeRecord(Index);
6803 if (TypesLoaded[Index].isNull())
6804 return QualType();
6805
6806 TypesLoaded[Index]->setFromAST();
6807 if (DeserializationListener)
6808 DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
6809 TypesLoaded[Index]);
6810 }
6811
6812 return TypesLoaded[Index].withFastQualifiers(FastQuals);
6813}
6814
6815QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
6816 return GetType(getGlobalTypeID(F, LocalID));
6817}
6818
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006819serialization::TypeID
Guy Benyei11169dd2012-12-18 14:30:41 +00006820ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
6821 unsigned FastQuals = LocalID & Qualifiers::FastMask;
6822 unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006823
Guy Benyei11169dd2012-12-18 14:30:41 +00006824 if (LocalIndex < NUM_PREDEF_TYPE_IDS)
6825 return LocalID;
6826
Richard Smith37a93df2017-02-18 00:32:02 +00006827 if (!F.ModuleOffsetMap.empty())
6828 ReadModuleOffsetMap(F);
6829
Guy Benyei11169dd2012-12-18 14:30:41 +00006830 ContinuousRangeMap<uint32_t, int, 2>::iterator I
6831 = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
6832 assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006833
Guy Benyei11169dd2012-12-18 14:30:41 +00006834 unsigned GlobalIndex = LocalIndex + I->second;
6835 return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
6836}
6837
6838TemplateArgumentLocInfo
6839ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
6840 TemplateArgument::ArgKind Kind,
6841 const RecordData &Record,
6842 unsigned &Index) {
6843 switch (Kind) {
6844 case TemplateArgument::Expression:
6845 return ReadExpr(F);
6846 case TemplateArgument::Type:
6847 return GetTypeSourceInfo(F, Record, Index);
6848 case TemplateArgument::Template: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006849 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006850 Index);
6851 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6852 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
6853 SourceLocation());
6854 }
6855 case TemplateArgument::TemplateExpansion: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006856 NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00006857 Index);
6858 SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
6859 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00006860 return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
Guy Benyei11169dd2012-12-18 14:30:41 +00006861 EllipsisLoc);
6862 }
6863 case TemplateArgument::Null:
6864 case TemplateArgument::Integral:
6865 case TemplateArgument::Declaration:
6866 case TemplateArgument::NullPtr:
6867 case TemplateArgument::Pack:
6868 // FIXME: Is this right?
6869 return TemplateArgumentLocInfo();
6870 }
6871 llvm_unreachable("unexpected template argument loc");
6872}
6873
6874TemplateArgumentLoc
6875ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
6876 const RecordData &Record, unsigned &Index) {
6877 TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
6878
6879 if (Arg.getKind() == TemplateArgument::Expression) {
6880 if (Record[Index++]) // bool InfoHasSameExpr.
6881 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
6882 }
6883 return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
6884 Record, Index));
6885}
6886
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00006887const ASTTemplateArgumentListInfo*
6888ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
6889 const RecordData &Record,
6890 unsigned &Index) {
6891 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
6892 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
6893 unsigned NumArgsAsWritten = Record[Index++];
6894 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
6895 for (unsigned i = 0; i != NumArgsAsWritten; ++i)
6896 TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
6897 return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
6898}
6899
Guy Benyei11169dd2012-12-18 14:30:41 +00006900Decl *ASTReader::GetExternalDecl(uint32_t ID) {
6901 return GetDecl(ID);
6902}
6903
Richard Smith053f6c62014-05-16 23:01:30 +00006904void ASTReader::CompleteRedeclChain(const Decl *D) {
Richard Smith851072e2014-05-19 20:59:20 +00006905 if (NumCurrentElementsDeserializing) {
6906 // We arrange to not care about the complete redeclaration chain while we're
6907 // deserializing. Just remember that the AST has marked this one as complete
6908 // but that it's not actually complete yet, so we know we still need to
6909 // complete it later.
6910 PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
6911 return;
6912 }
6913
Richard Smith053f6c62014-05-16 23:01:30 +00006914 const DeclContext *DC = D->getDeclContext()->getRedeclContext();
6915
Richard Smith053f6c62014-05-16 23:01:30 +00006916 // If this is a named declaration, complete it by looking it up
6917 // within its context.
6918 //
Richard Smith01bdb7a2014-08-28 05:44:07 +00006919 // FIXME: Merging a function definition should merge
Richard Smith053f6c62014-05-16 23:01:30 +00006920 // all mergeable entities within it.
6921 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
6922 isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
6923 if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
Richard Smitha534a312015-07-21 23:54:07 +00006924 if (!getContext().getLangOpts().CPlusPlus &&
6925 isa<TranslationUnitDecl>(DC)) {
Richard Smith053f6c62014-05-16 23:01:30 +00006926 // Outside of C++, we don't have a lookup table for the TU, so update
Richard Smitha534a312015-07-21 23:54:07 +00006927 // the identifier instead. (For C++ modules, we don't store decls
6928 // in the serialized identifier table, so we do the lookup in the TU.)
6929 auto *II = Name.getAsIdentifierInfo();
6930 assert(II && "non-identifier name in C?");
Richard Smith053f6c62014-05-16 23:01:30 +00006931 if (II->isOutOfDate())
6932 updateOutOfDateIdentifier(*II);
6933 } else
6934 DC->lookup(Name);
Richard Smith01bdb7a2014-08-28 05:44:07 +00006935 } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
Richard Smith3cb15722015-08-05 22:41:45 +00006936 // Find all declarations of this kind from the relevant context.
6937 for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
6938 auto *DC = cast<DeclContext>(DCDecl);
6939 SmallVector<Decl*, 8> Decls;
6940 FindExternalLexicalDecls(
6941 DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
6942 }
Richard Smith053f6c62014-05-16 23:01:30 +00006943 }
6944 }
Richard Smith50895422015-01-31 03:04:55 +00006945
6946 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
6947 CTSD->getSpecializedTemplate()->LoadLazySpecializations();
6948 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
6949 VTSD->getSpecializedTemplate()->LoadLazySpecializations();
6950 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
6951 if (auto *Template = FD->getPrimaryTemplate())
6952 Template->LoadLazySpecializations();
6953 }
Richard Smith053f6c62014-05-16 23:01:30 +00006954}
6955
Richard Smithc2bb8182015-03-24 06:36:48 +00006956CXXCtorInitializer **
6957ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
6958 RecordLocation Loc = getLocalBitOffset(Offset);
6959 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
6960 SavedStreamPosition SavedPosition(Cursor);
6961 Cursor.JumpToBit(Loc.Offset);
6962 ReadingKindTracker ReadingKind(Read_Decl, *this);
6963
6964 RecordData Record;
6965 unsigned Code = Cursor.ReadCode();
6966 unsigned RecCode = Cursor.readRecord(Code, Record);
6967 if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
6968 Error("malformed AST file: missing C++ ctor initializers");
6969 return nullptr;
6970 }
6971
6972 unsigned Idx = 0;
6973 return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
6974}
6975
Guy Benyei11169dd2012-12-18 14:30:41 +00006976CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00006977 assert(ContextObj && "reading base specifiers with no AST context");
6978 ASTContext &Context = *ContextObj;
6979
Guy Benyei11169dd2012-12-18 14:30:41 +00006980 RecordLocation Loc = getLocalBitOffset(Offset);
Chris Lattner7fb3bef2013-01-20 00:56:42 +00006981 BitstreamCursor &Cursor = Loc.F->DeclsCursor;
Guy Benyei11169dd2012-12-18 14:30:41 +00006982 SavedStreamPosition SavedPosition(Cursor);
6983 Cursor.JumpToBit(Loc.Offset);
6984 ReadingKindTracker ReadingKind(Read_Decl, *this);
6985 RecordData Record;
6986 unsigned Code = Cursor.ReadCode();
Chris Lattner0e6c9402013-01-20 02:38:54 +00006987 unsigned RecCode = Cursor.readRecord(Code, Record);
Guy Benyei11169dd2012-12-18 14:30:41 +00006988 if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
Richard Smithcd45dbc2014-04-19 03:48:30 +00006989 Error("malformed AST file: missing C++ base specifiers");
Craig Toppera13603a2014-05-22 05:54:18 +00006990 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00006991 }
6992
6993 unsigned Idx = 0;
6994 unsigned NumBases = Record[Idx++];
6995 void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
6996 CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
6997 for (unsigned I = 0; I != NumBases; ++I)
6998 Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
6999 return Bases;
7000}
7001
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007002serialization::DeclID
Guy Benyei11169dd2012-12-18 14:30:41 +00007003ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
7004 if (LocalID < NUM_PREDEF_DECL_IDS)
7005 return LocalID;
7006
Richard Smith37a93df2017-02-18 00:32:02 +00007007 if (!F.ModuleOffsetMap.empty())
7008 ReadModuleOffsetMap(F);
7009
Guy Benyei11169dd2012-12-18 14:30:41 +00007010 ContinuousRangeMap<uint32_t, int, 2>::iterator I
7011 = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
7012 assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007013
Guy Benyei11169dd2012-12-18 14:30:41 +00007014 return LocalID + I->second;
7015}
7016
7017bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
7018 ModuleFile &M) const {
Richard Smithfe620d22015-03-05 23:24:12 +00007019 // Predefined decls aren't from any module.
7020 if (ID < NUM_PREDEF_DECL_IDS)
7021 return false;
7022
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007023 return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
Richard Smithbcda1a92015-07-12 23:51:20 +00007024 ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007025}
7026
Douglas Gregor9f782892013-01-21 15:25:38 +00007027ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007028 if (!D->isFromASTFile())
Craig Toppera13603a2014-05-22 05:54:18 +00007029 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007030 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
7031 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7032 return I->second;
7033}
7034
7035SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
7036 if (ID < NUM_PREDEF_DECL_IDS)
7037 return SourceLocation();
Richard Smithcd45dbc2014-04-19 03:48:30 +00007038
Guy Benyei11169dd2012-12-18 14:30:41 +00007039 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7040
7041 if (Index > DeclsLoaded.size()) {
7042 Error("declaration ID out-of-range for AST file");
7043 return SourceLocation();
7044 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007045
Guy Benyei11169dd2012-12-18 14:30:41 +00007046 if (Decl *D = DeclsLoaded[Index])
7047 return D->getLocation();
7048
Richard Smithcb34bd32016-03-27 07:28:06 +00007049 SourceLocation Loc;
7050 DeclCursorForID(ID, Loc);
7051 return Loc;
Guy Benyei11169dd2012-12-18 14:30:41 +00007052}
7053
Richard Smithfe620d22015-03-05 23:24:12 +00007054static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
7055 switch (ID) {
7056 case PREDEF_DECL_NULL_ID:
7057 return nullptr;
7058
7059 case PREDEF_DECL_TRANSLATION_UNIT_ID:
7060 return Context.getTranslationUnitDecl();
7061
7062 case PREDEF_DECL_OBJC_ID_ID:
7063 return Context.getObjCIdDecl();
7064
7065 case PREDEF_DECL_OBJC_SEL_ID:
7066 return Context.getObjCSelDecl();
7067
7068 case PREDEF_DECL_OBJC_CLASS_ID:
7069 return Context.getObjCClassDecl();
7070
7071 case PREDEF_DECL_OBJC_PROTOCOL_ID:
7072 return Context.getObjCProtocolDecl();
7073
7074 case PREDEF_DECL_INT_128_ID:
7075 return Context.getInt128Decl();
7076
7077 case PREDEF_DECL_UNSIGNED_INT_128_ID:
7078 return Context.getUInt128Decl();
7079
7080 case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
7081 return Context.getObjCInstanceTypeDecl();
7082
7083 case PREDEF_DECL_BUILTIN_VA_LIST_ID:
7084 return Context.getBuiltinVaListDecl();
Richard Smithf19e1272015-03-07 00:04:49 +00007085
Richard Smith9b88a4c2015-07-27 05:40:23 +00007086 case PREDEF_DECL_VA_LIST_TAG:
7087 return Context.getVaListTagDecl();
7088
Charles Davisc7d5c942015-09-17 20:55:33 +00007089 case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
7090 return Context.getBuiltinMSVaListDecl();
7091
Richard Smithf19e1272015-03-07 00:04:49 +00007092 case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
7093 return Context.getExternCContextDecl();
David Majnemerd9b1a4f2015-11-04 03:40:30 +00007094
7095 case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
7096 return Context.getMakeIntegerSeqDecl();
Quentin Colombet043406b2016-02-03 22:41:00 +00007097
7098 case PREDEF_DECL_CF_CONSTANT_STRING_ID:
7099 return Context.getCFConstantStringDecl();
Ben Langmuirf5416742016-02-04 00:55:24 +00007100
7101 case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
7102 return Context.getCFConstantStringTagDecl();
Eric Fiselier6ad68552016-07-01 01:24:09 +00007103
7104 case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
7105 return Context.getTypePackElementDecl();
Richard Smithfe620d22015-03-05 23:24:12 +00007106 }
Yaron Keren322bdad2015-03-06 07:49:14 +00007107 llvm_unreachable("PredefinedDeclIDs unknown enum value");
Richard Smithfe620d22015-03-05 23:24:12 +00007108}
7109
Richard Smithcd45dbc2014-04-19 03:48:30 +00007110Decl *ASTReader::GetExistingDecl(DeclID ID) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007111 assert(ContextObj && "reading decl with no AST context");
Richard Smithcd45dbc2014-04-19 03:48:30 +00007112 if (ID < NUM_PREDEF_DECL_IDS) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00007113 Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
Richard Smithfe620d22015-03-05 23:24:12 +00007114 if (D) {
7115 // Track that we have merged the declaration with ID \p ID into the
7116 // pre-existing predefined declaration \p D.
Richard Smith5fc18a92015-07-12 23:43:21 +00007117 auto &Merged = KeyDecls[D->getCanonicalDecl()];
Richard Smithfe620d22015-03-05 23:24:12 +00007118 if (Merged.empty())
7119 Merged.push_back(ID);
Guy Benyei11169dd2012-12-18 14:30:41 +00007120 }
Richard Smithfe620d22015-03-05 23:24:12 +00007121 return D;
Guy Benyei11169dd2012-12-18 14:30:41 +00007122 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007123
Guy Benyei11169dd2012-12-18 14:30:41 +00007124 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7125
7126 if (Index >= DeclsLoaded.size()) {
7127 assert(0 && "declaration ID out-of-range for AST file");
7128 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007129 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00007130 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007131
7132 return DeclsLoaded[Index];
7133}
7134
7135Decl *ASTReader::GetDecl(DeclID ID) {
7136 if (ID < NUM_PREDEF_DECL_IDS)
7137 return GetExistingDecl(ID);
7138
7139 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
7140
7141 if (Index >= DeclsLoaded.size()) {
7142 assert(0 && "declaration ID out-of-range for AST file");
7143 Error("declaration ID out-of-range for AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00007144 return nullptr;
Richard Smithcd45dbc2014-04-19 03:48:30 +00007145 }
7146
Guy Benyei11169dd2012-12-18 14:30:41 +00007147 if (!DeclsLoaded[Index]) {
7148 ReadDeclRecord(ID);
7149 if (DeserializationListener)
7150 DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
7151 }
7152
7153 return DeclsLoaded[Index];
7154}
7155
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007156DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
Guy Benyei11169dd2012-12-18 14:30:41 +00007157 DeclID GlobalID) {
7158 if (GlobalID < NUM_PREDEF_DECL_IDS)
7159 return GlobalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007160
Guy Benyei11169dd2012-12-18 14:30:41 +00007161 GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
7162 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
7163 ModuleFile *Owner = I->second;
7164
7165 llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
7166 = M.GlobalToLocalDeclIDs.find(Owner);
7167 if (Pos == M.GlobalToLocalDeclIDs.end())
7168 return 0;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007169
Guy Benyei11169dd2012-12-18 14:30:41 +00007170 return GlobalID - Owner->BaseDeclID + Pos->second;
7171}
7172
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007173serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00007174 const RecordData &Record,
7175 unsigned &Idx) {
7176 if (Idx >= Record.size()) {
7177 Error("Corrupted AST file");
7178 return 0;
7179 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007180
Guy Benyei11169dd2012-12-18 14:30:41 +00007181 return getGlobalDeclID(F, Record[Idx++]);
7182}
7183
7184/// \brief Resolve the offset of a statement into a statement.
7185///
7186/// This operation will read a new statement from the external
7187/// source each time it is called, and is meant to be used via a
7188/// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
7189Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
7190 // Switch case IDs are per Decl.
7191 ClearSwitchCaseIDs();
7192
7193 // Offset here is a global offset across the entire chain.
7194 RecordLocation Loc = getLocalBitOffset(Offset);
7195 Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
David Blaikie9fd16f82017-03-08 23:57:08 +00007196 assert(NumCurrentElementsDeserializing == 0 &&
7197 "should not be called while already deserializing");
7198 Deserializing D(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007199 return ReadStmtFromStream(*Loc.F);
7200}
7201
Richard Smith3cb15722015-08-05 22:41:45 +00007202void ASTReader::FindExternalLexicalDecls(
7203 const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
7204 SmallVectorImpl<Decl *> &Decls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007205 bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
7206
Richard Smith9ccdd932015-08-06 22:14:12 +00007207 auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
Richard Smith82f8fcd2015-08-06 22:07:25 +00007208 assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
7209 for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
7210 auto K = (Decl::Kind)+LexicalDecls[I];
7211 if (!IsKindWeWant(K))
7212 continue;
7213
7214 auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
7215
7216 // Don't add predefined declarations to the lexical context more
7217 // than once.
7218 if (ID < NUM_PREDEF_DECL_IDS) {
7219 if (PredefsVisited[ID])
7220 continue;
7221
7222 PredefsVisited[ID] = true;
7223 }
7224
7225 if (Decl *D = GetLocalDecl(*M, ID)) {
Richard Smith2317a3e2015-08-11 21:21:20 +00007226 assert(D->getKind() == K && "wrong kind for lexical decl");
Richard Smith82f8fcd2015-08-06 22:07:25 +00007227 if (!DC->isDeclInLexicalTraversal(D))
7228 Decls.push_back(D);
7229 }
7230 }
7231 };
7232
7233 if (isa<TranslationUnitDecl>(DC)) {
7234 for (auto Lexical : TULexicalDecls)
7235 Visit(Lexical.first, Lexical.second);
7236 } else {
7237 auto I = LexicalDecls.find(DC);
7238 if (I != LexicalDecls.end())
Richard Smith9c9173d2015-08-11 22:00:24 +00007239 Visit(I->second.first, I->second.second);
Richard Smith82f8fcd2015-08-06 22:07:25 +00007240 }
7241
Guy Benyei11169dd2012-12-18 14:30:41 +00007242 ++NumLexicalDeclContextsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007243}
7244
7245namespace {
7246
7247class DeclIDComp {
7248 ASTReader &Reader;
7249 ModuleFile &Mod;
7250
7251public:
7252 DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
7253
7254 bool operator()(LocalDeclID L, LocalDeclID R) const {
7255 SourceLocation LHS = getLocation(L);
7256 SourceLocation RHS = getLocation(R);
7257 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7258 }
7259
7260 bool operator()(SourceLocation LHS, LocalDeclID R) const {
7261 SourceLocation RHS = getLocation(R);
7262 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7263 }
7264
7265 bool operator()(LocalDeclID L, SourceLocation RHS) const {
7266 SourceLocation LHS = getLocation(L);
7267 return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
7268 }
7269
7270 SourceLocation getLocation(LocalDeclID ID) const {
7271 return Reader.getSourceManager().getFileLoc(
7272 Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
7273 }
7274};
7275
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007276} // end anonymous namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007277
7278void ASTReader::FindFileRegionDecls(FileID File,
7279 unsigned Offset, unsigned Length,
7280 SmallVectorImpl<Decl *> &Decls) {
7281 SourceManager &SM = getSourceManager();
7282
7283 llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
7284 if (I == FileDeclIDs.end())
7285 return;
7286
7287 FileDeclsInfo &DInfo = I->second;
7288 if (DInfo.Decls.empty())
7289 return;
7290
7291 SourceLocation
7292 BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
7293 SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
7294
7295 DeclIDComp DIDComp(*this, *DInfo.Mod);
7296 ArrayRef<serialization::LocalDeclID>::iterator
7297 BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7298 BeginLoc, DIDComp);
7299 if (BeginIt != DInfo.Decls.begin())
7300 --BeginIt;
7301
7302 // If we are pointing at a top-level decl inside an objc container, we need
7303 // to backtrack until we find it otherwise we will fail to report that the
7304 // region overlaps with an objc container.
7305 while (BeginIt != DInfo.Decls.begin() &&
7306 GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
7307 ->isTopLevelDeclInObjCContainer())
7308 --BeginIt;
7309
7310 ArrayRef<serialization::LocalDeclID>::iterator
7311 EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
7312 EndLoc, DIDComp);
7313 if (EndIt != DInfo.Decls.end())
7314 ++EndIt;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007315
Guy Benyei11169dd2012-12-18 14:30:41 +00007316 for (ArrayRef<serialization::LocalDeclID>::iterator
7317 DIt = BeginIt; DIt != EndIt; ++DIt)
7318 Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
7319}
7320
Richard Smith9ce12e32013-02-07 03:30:24 +00007321bool
Guy Benyei11169dd2012-12-18 14:30:41 +00007322ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
7323 DeclarationName Name) {
Richard Smithd88a7f12015-09-01 20:35:42 +00007324 assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
Guy Benyei11169dd2012-12-18 14:30:41 +00007325 "DeclContext has no visible decls in storage");
7326 if (!Name)
Richard Smith9ce12e32013-02-07 03:30:24 +00007327 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +00007328
Richard Smithd88a7f12015-09-01 20:35:42 +00007329 auto It = Lookups.find(DC);
7330 if (It == Lookups.end())
7331 return false;
7332
Richard Smith8c913ec2014-08-14 02:21:01 +00007333 Deserializing LookupResults(this);
7334
Richard Smithd88a7f12015-09-01 20:35:42 +00007335 // Load the list of declarations.
Guy Benyei11169dd2012-12-18 14:30:41 +00007336 SmallVector<NamedDecl *, 64> Decls;
Richard Smithd88a7f12015-09-01 20:35:42 +00007337 for (DeclID ID : It->second.Table.find(Name)) {
7338 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7339 if (ND->getDeclName() == Name)
7340 Decls.push_back(ND);
7341 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00007342
Guy Benyei11169dd2012-12-18 14:30:41 +00007343 ++NumVisibleDeclContextsRead;
7344 SetExternalVisibleDeclsForName(DC, Name, Decls);
Richard Smith9ce12e32013-02-07 03:30:24 +00007345 return !Decls.empty();
Guy Benyei11169dd2012-12-18 14:30:41 +00007346}
7347
Guy Benyei11169dd2012-12-18 14:30:41 +00007348void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
7349 if (!DC->hasExternalVisibleStorage())
7350 return;
Richard Smithd88a7f12015-09-01 20:35:42 +00007351
7352 auto It = Lookups.find(DC);
7353 assert(It != Lookups.end() &&
7354 "have external visible storage but no lookup tables");
7355
Craig Topper79be4cd2013-07-05 04:33:53 +00007356 DeclsMap Decls;
Guy Benyei11169dd2012-12-18 14:30:41 +00007357
Richard Smithd88a7f12015-09-01 20:35:42 +00007358 for (DeclID ID : It->second.Table.findAll()) {
7359 NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
7360 Decls[ND->getDeclName()].push_back(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +00007361 }
7362
Guy Benyei11169dd2012-12-18 14:30:41 +00007363 ++NumVisibleDeclContextsRead;
7364
Craig Topper79be4cd2013-07-05 04:33:53 +00007365 for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007366 SetExternalVisibleDeclsForName(DC, I->first, I->second);
7367 }
7368 const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
7369}
7370
Richard Smithd88a7f12015-09-01 20:35:42 +00007371const serialization::reader::DeclContextLookupTable *
7372ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
7373 auto I = Lookups.find(Primary);
7374 return I == Lookups.end() ? nullptr : &I->second;
7375}
7376
Guy Benyei11169dd2012-12-18 14:30:41 +00007377/// \brief Under non-PCH compilation the consumer receives the objc methods
7378/// before receiving the implementation, and codegen depends on this.
7379/// We simulate this by deserializing and passing to consumer the methods of the
7380/// implementation before passing the deserialized implementation decl.
7381static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
7382 ASTConsumer *Consumer) {
7383 assert(ImplD && Consumer);
7384
Aaron Ballmanaff18c02014-03-13 19:03:34 +00007385 for (auto *I : ImplD->methods())
7386 Consumer->HandleInterestingDecl(DeclGroupRef(I));
Guy Benyei11169dd2012-12-18 14:30:41 +00007387
7388 Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
7389}
7390
Guy Benyei11169dd2012-12-18 14:30:41 +00007391void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
7392 if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
7393 PassObjCImplDeclToConsumer(ImplD, Consumer);
7394 else
7395 Consumer->HandleInterestingDecl(DeclGroupRef(D));
7396}
7397
7398void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
7399 this->Consumer = Consumer;
7400
Richard Smith9e2341d2015-03-23 03:25:59 +00007401 if (Consumer)
7402 PassInterestingDeclsToConsumer();
Richard Smith7f330cd2015-03-18 01:42:29 +00007403
7404 if (DeserializationListener)
7405 DeserializationListener->ReaderInitialized(this);
Guy Benyei11169dd2012-12-18 14:30:41 +00007406}
7407
7408void ASTReader::PrintStats() {
7409 std::fprintf(stderr, "*** AST File Statistics:\n");
7410
7411 unsigned NumTypesLoaded
7412 = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
7413 QualType());
7414 unsigned NumDeclsLoaded
7415 = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007416 (Decl *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007417 unsigned NumIdentifiersLoaded
7418 = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
7419 IdentifiersLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007420 (IdentifierInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007421 unsigned NumMacrosLoaded
7422 = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
7423 MacrosLoaded.end(),
Craig Toppera13603a2014-05-22 05:54:18 +00007424 (MacroInfo *)nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00007425 unsigned NumSelectorsLoaded
7426 = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
7427 SelectorsLoaded.end(),
7428 Selector());
7429
7430 if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
7431 std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
7432 NumSLocEntriesRead, TotalNumSLocEntries,
7433 ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
7434 if (!TypesLoaded.empty())
7435 std::fprintf(stderr, " %u/%u types read (%f%%)\n",
7436 NumTypesLoaded, (unsigned)TypesLoaded.size(),
7437 ((float)NumTypesLoaded/TypesLoaded.size() * 100));
7438 if (!DeclsLoaded.empty())
7439 std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
7440 NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
7441 ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
7442 if (!IdentifiersLoaded.empty())
7443 std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
7444 NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
7445 ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
7446 if (!MacrosLoaded.empty())
7447 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7448 NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
7449 ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
7450 if (!SelectorsLoaded.empty())
7451 std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
7452 NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
7453 ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
7454 if (TotalNumStatements)
7455 std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
7456 NumStatementsRead, TotalNumStatements,
7457 ((float)NumStatementsRead/TotalNumStatements * 100));
7458 if (TotalNumMacros)
7459 std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
7460 NumMacrosRead, TotalNumMacros,
7461 ((float)NumMacrosRead/TotalNumMacros * 100));
7462 if (TotalLexicalDeclContexts)
7463 std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
7464 NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
7465 ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
7466 * 100));
7467 if (TotalVisibleDeclContexts)
7468 std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
7469 NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
7470 ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
7471 * 100));
7472 if (TotalNumMethodPoolEntries) {
7473 std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
7474 NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
7475 ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
7476 * 100));
Guy Benyei11169dd2012-12-18 14:30:41 +00007477 }
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007478 if (NumMethodPoolLookups) {
7479 std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
7480 NumMethodPoolHits, NumMethodPoolLookups,
7481 ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
7482 }
7483 if (NumMethodPoolTableLookups) {
7484 std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
7485 NumMethodPoolTableHits, NumMethodPoolTableLookups,
7486 ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
7487 * 100.0));
7488 }
7489
Douglas Gregor00a50f72013-01-25 00:38:33 +00007490 if (NumIdentifierLookupHits) {
7491 std::fprintf(stderr,
7492 " %u / %u identifier table lookups succeeded (%f%%)\n",
7493 NumIdentifierLookupHits, NumIdentifierLookups,
7494 (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
7495 }
7496
Douglas Gregore060e572013-01-25 01:03:03 +00007497 if (GlobalIndex) {
7498 std::fprintf(stderr, "\n");
7499 GlobalIndex->printStats();
7500 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007501
Guy Benyei11169dd2012-12-18 14:30:41 +00007502 std::fprintf(stderr, "\n");
7503 dump();
7504 std::fprintf(stderr, "\n");
7505}
7506
7507template<typename Key, typename ModuleFile, unsigned InitialCapacity>
Vassil Vassilevb2710682017-03-02 18:13:19 +00007508LLVM_DUMP_METHOD static void
Guy Benyei11169dd2012-12-18 14:30:41 +00007509dumpModuleIDMap(StringRef Name,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007510 const ContinuousRangeMap<Key, ModuleFile *,
Guy Benyei11169dd2012-12-18 14:30:41 +00007511 InitialCapacity> &Map) {
7512 if (Map.begin() == Map.end())
7513 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007514
Guy Benyei11169dd2012-12-18 14:30:41 +00007515 typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
7516 llvm::errs() << Name << ":\n";
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007517 for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
Guy Benyei11169dd2012-12-18 14:30:41 +00007518 I != IEnd; ++I) {
7519 llvm::errs() << " " << I->first << " -> " << I->second->FileName
7520 << "\n";
7521 }
7522}
7523
Yaron Kerencdae9412016-01-29 19:38:18 +00007524LLVM_DUMP_METHOD void ASTReader::dump() {
Guy Benyei11169dd2012-12-18 14:30:41 +00007525 llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
7526 dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
7527 dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
7528 dumpModuleIDMap("Global type map", GlobalTypeMap);
7529 dumpModuleIDMap("Global declaration map", GlobalDeclMap);
7530 dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
7531 dumpModuleIDMap("Global macro map", GlobalMacroMap);
7532 dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
7533 dumpModuleIDMap("Global selector map", GlobalSelectorMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007534 dumpModuleIDMap("Global preprocessed entity map",
Guy Benyei11169dd2012-12-18 14:30:41 +00007535 GlobalPreprocessedEntityMap);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007536
Guy Benyei11169dd2012-12-18 14:30:41 +00007537 llvm::errs() << "\n*** PCH/Modules Loaded:";
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007538 for (ModuleFile &M : ModuleMgr)
7539 M.dump();
Guy Benyei11169dd2012-12-18 14:30:41 +00007540}
7541
7542/// Return the amount of memory used by memory buffers, breaking down
7543/// by heap-backed versus mmap'ed memory.
7544void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
Duncan P. N. Exon Smith96a06e02017-01-28 22:15:22 +00007545 for (ModuleFile &I : ModuleMgr) {
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +00007546 if (llvm::MemoryBuffer *buf = I.Buffer) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007547 size_t bytes = buf->getBufferSize();
7548 switch (buf->getBufferKind()) {
7549 case llvm::MemoryBuffer::MemoryBuffer_Malloc:
7550 sizes.malloc_bytes += bytes;
7551 break;
7552 case llvm::MemoryBuffer::MemoryBuffer_MMap:
7553 sizes.mmap_bytes += bytes;
7554 break;
7555 }
7556 }
7557 }
7558}
7559
7560void ASTReader::InitializeSema(Sema &S) {
7561 SemaObj = &S;
7562 S.addExternalSource(this);
7563
7564 // Makes sure any declarations that were deserialized "too early"
7565 // still get added to the identifier's declaration chains.
Ben Langmuir5418f402014-09-10 21:29:41 +00007566 for (uint64_t ID : PreloadedDeclIDs) {
7567 NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
7568 pushExternalDeclIntoScope(D, D->getDeclName());
Guy Benyei11169dd2012-12-18 14:30:41 +00007569 }
Ben Langmuir5418f402014-09-10 21:29:41 +00007570 PreloadedDeclIDs.clear();
Guy Benyei11169dd2012-12-18 14:30:41 +00007571
Richard Smith3d8e97e2013-10-18 06:54:39 +00007572 // FIXME: What happens if these are changed by a module import?
Guy Benyei11169dd2012-12-18 14:30:41 +00007573 if (!FPPragmaOptions.empty()) {
7574 assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
Adam Nemet484aa452017-03-27 19:17:25 +00007575 SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
Guy Benyei11169dd2012-12-18 14:30:41 +00007576 }
7577
Yaxun Liu5b746652016-12-18 05:18:55 +00007578 SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
7579 SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
7580 SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
Richard Smith3d8e97e2013-10-18 06:54:39 +00007581
7582 UpdateSema();
7583}
7584
7585void ASTReader::UpdateSema() {
7586 assert(SemaObj && "no Sema to update");
7587
7588 // Load the offsets of the declarations that Sema references.
7589 // They will be lazily deserialized when needed.
7590 if (!SemaDeclRefs.empty()) {
Richard Smith96269c52016-09-29 22:49:46 +00007591 assert(SemaDeclRefs.size() % 3 == 0);
7592 for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
Richard Smith3d8e97e2013-10-18 06:54:39 +00007593 if (!SemaObj->StdNamespace)
7594 SemaObj->StdNamespace = SemaDeclRefs[I];
7595 if (!SemaObj->StdBadAlloc)
7596 SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
Richard Smith96269c52016-09-29 22:49:46 +00007597 if (!SemaObj->StdAlignValT)
7598 SemaObj->StdAlignValT = SemaDeclRefs[I+2];
Richard Smith3d8e97e2013-10-18 06:54:39 +00007599 }
7600 SemaDeclRefs.clear();
7601 }
Dario Domizioli13a0a382014-05-23 12:13:25 +00007602
Nico Weber779355f2016-03-02 23:22:00 +00007603 // Update the state of pragmas. Use the same API as if we had encountered the
7604 // pragma in the source.
Dario Domizioli13a0a382014-05-23 12:13:25 +00007605 if(OptimizeOffPragmaLocation.isValid())
7606 SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
Nico Weber779355f2016-03-02 23:22:00 +00007607 if (PragmaMSStructState != -1)
7608 SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
Nico Weber42932312016-03-03 00:17:35 +00007609 if (PointersToMembersPragmaLocation.isValid()) {
7610 SemaObj->ActOnPragmaMSPointersToMembers(
7611 (LangOptions::PragmaMSPointersToMembersKind)
7612 PragmaMSPointersToMembersState,
7613 PointersToMembersPragmaLocation);
7614 }
Justin Lebar67a78a62016-10-08 22:15:58 +00007615 SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007616
7617 if (PragmaPackCurrentValue) {
7618 // The bottom of the stack might have a default value. It must be adjusted
7619 // to the current value to ensure that the packing state is preserved after
7620 // popping entries that were included/imported from a PCH/module.
7621 bool DropFirst = false;
7622 if (!PragmaPackStack.empty() &&
7623 PragmaPackStack.front().Location.isInvalid()) {
7624 assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
7625 "Expected a default alignment value");
7626 SemaObj->PackStack.Stack.emplace_back(
7627 PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
Alex Lorenz45b40142017-07-28 14:41:21 +00007628 SemaObj->PackStack.CurrentPragmaLocation,
7629 PragmaPackStack.front().PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007630 DropFirst = true;
7631 }
7632 for (const auto &Entry :
7633 llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
7634 SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
Alex Lorenz45b40142017-07-28 14:41:21 +00007635 Entry.Location, Entry.PushLocation);
Alex Lorenz7d7e1e02017-03-31 15:36:21 +00007636 if (PragmaPackCurrentLocation.isInvalid()) {
7637 assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
7638 "Expected a default alignment value");
7639 // Keep the current values.
7640 } else {
7641 SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
7642 SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
7643 }
7644 }
Guy Benyei11169dd2012-12-18 14:30:41 +00007645}
7646
Richard Smitha8d5b6a2015-07-17 19:51:03 +00007647IdentifierInfo *ASTReader::get(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007648 // Note that we are loading an identifier.
7649 Deserializing AnIdentifier(this);
Douglas Gregore060e572013-01-25 01:03:03 +00007650
Douglas Gregor7211ac12013-01-25 23:32:03 +00007651 IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
Douglas Gregor00a50f72013-01-25 00:38:33 +00007652 NumIdentifierLookups,
7653 NumIdentifierLookupHits);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007654
7655 // We don't need to do identifier table lookups in C++ modules (we preload
7656 // all interesting declarations, and don't need to use the scope for name
7657 // lookups). Perform the lookup in PCH files, though, since we don't build
7658 // a complete initial identifier table if we're carrying on from a PCH.
Richard Smithdbafb6c2017-06-29 23:23:46 +00007659 if (PP.getLangOpts().CPlusPlus) {
Richard Smith33e0f7e2015-07-22 02:08:40 +00007660 for (auto F : ModuleMgr.pch_modules())
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007661 if (Visitor(*F))
Richard Smith33e0f7e2015-07-22 02:08:40 +00007662 break;
7663 } else {
7664 // If there is a global index, look there first to determine which modules
7665 // provably do not have any results for this identifier.
7666 GlobalModuleIndex::HitSet Hits;
7667 GlobalModuleIndex::HitSet *HitsPtr = nullptr;
7668 if (!loadGlobalIndex()) {
7669 if (GlobalIndex->lookupIdentifier(Name, Hits)) {
7670 HitsPtr = &Hits;
7671 }
7672 }
7673
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007674 ModuleMgr.visit(Visitor, HitsPtr);
Richard Smith33e0f7e2015-07-22 02:08:40 +00007675 }
7676
Guy Benyei11169dd2012-12-18 14:30:41 +00007677 IdentifierInfo *II = Visitor.getIdentifierInfo();
7678 markIdentifierUpToDate(II);
7679 return II;
7680}
7681
7682namespace clang {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007683
Guy Benyei11169dd2012-12-18 14:30:41 +00007684 /// \brief An identifier-lookup iterator that enumerates all of the
7685 /// identifiers stored within a set of AST files.
7686 class ASTIdentifierIterator : public IdentifierIterator {
7687 /// \brief The AST reader whose identifiers are being enumerated.
7688 const ASTReader &Reader;
7689
7690 /// \brief The current index into the chain of AST files stored in
7691 /// the AST reader.
7692 unsigned Index;
7693
7694 /// \brief The current position within the identifier lookup table
7695 /// of the current AST file.
7696 ASTIdentifierLookupTable::key_iterator Current;
7697
7698 /// \brief The end position within the identifier lookup table of
7699 /// the current AST file.
7700 ASTIdentifierLookupTable::key_iterator End;
7701
Ben Langmuir537c5b52016-05-04 00:53:13 +00007702 /// \brief Whether to skip any modules in the ASTReader.
7703 bool SkipModules;
7704
Guy Benyei11169dd2012-12-18 14:30:41 +00007705 public:
Ben Langmuir537c5b52016-05-04 00:53:13 +00007706 explicit ASTIdentifierIterator(const ASTReader &Reader,
7707 bool SkipModules = false);
Guy Benyei11169dd2012-12-18 14:30:41 +00007708
Craig Topper3e89dfe2014-03-13 02:13:41 +00007709 StringRef Next() override;
Guy Benyei11169dd2012-12-18 14:30:41 +00007710 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007711
7712} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007713
Ben Langmuir537c5b52016-05-04 00:53:13 +00007714ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
7715 bool SkipModules)
7716 : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007717}
7718
7719StringRef ASTIdentifierIterator::Next() {
7720 while (Current == End) {
7721 // If we have exhausted all of our AST files, we're done.
7722 if (Index == 0)
7723 return StringRef();
7724
7725 --Index;
Ben Langmuir537c5b52016-05-04 00:53:13 +00007726 ModuleFile &F = Reader.ModuleMgr[Index];
7727 if (SkipModules && F.isModule())
7728 continue;
7729
7730 ASTIdentifierLookupTable *IdTable =
7731 (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
Guy Benyei11169dd2012-12-18 14:30:41 +00007732 Current = IdTable->key_begin();
7733 End = IdTable->key_end();
7734 }
7735
7736 // We have any identifiers remaining in the current AST file; return
7737 // the next one.
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007738 StringRef Result = *Current;
Guy Benyei11169dd2012-12-18 14:30:41 +00007739 ++Current;
Douglas Gregorbfd73d72013-01-23 18:53:14 +00007740 return Result;
Guy Benyei11169dd2012-12-18 14:30:41 +00007741}
7742
Ben Langmuir537c5b52016-05-04 00:53:13 +00007743namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007744
Ben Langmuir537c5b52016-05-04 00:53:13 +00007745/// A utility for appending two IdentifierIterators.
7746class ChainedIdentifierIterator : public IdentifierIterator {
7747 std::unique_ptr<IdentifierIterator> Current;
7748 std::unique_ptr<IdentifierIterator> Queued;
7749
7750public:
7751 ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
7752 std::unique_ptr<IdentifierIterator> Second)
7753 : Current(std::move(First)), Queued(std::move(Second)) {}
7754
7755 StringRef Next() override {
7756 if (!Current)
7757 return StringRef();
7758
7759 StringRef result = Current->Next();
7760 if (!result.empty())
7761 return result;
7762
7763 // Try the queued iterator, which may itself be empty.
7764 Current.reset();
7765 std::swap(Current, Queued);
7766 return Next();
7767 }
7768};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007769
Ben Langmuir537c5b52016-05-04 00:53:13 +00007770} // end anonymous namespace.
7771
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007772IdentifierIterator *ASTReader::getIdentifiers() {
Ben Langmuir537c5b52016-05-04 00:53:13 +00007773 if (!loadGlobalIndex()) {
7774 std::unique_ptr<IdentifierIterator> ReaderIter(
7775 new ASTIdentifierIterator(*this, /*SkipModules=*/true));
7776 std::unique_ptr<IdentifierIterator> ModulesIter(
7777 GlobalIndex->createIdentifierIterator());
7778 return new ChainedIdentifierIterator(std::move(ReaderIter),
7779 std::move(ModulesIter));
7780 }
Argyrios Kyrtzidis9aca3c62013-04-17 22:10:55 +00007781
Guy Benyei11169dd2012-12-18 14:30:41 +00007782 return new ASTIdentifierIterator(*this);
7783}
7784
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007785namespace clang {
7786namespace serialization {
7787
Guy Benyei11169dd2012-12-18 14:30:41 +00007788 class ReadMethodPoolVisitor {
7789 ASTReader &Reader;
7790 Selector Sel;
7791 unsigned PriorGeneration;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007792 unsigned InstanceBits;
7793 unsigned FactoryBits;
Nico Weberff4b35e2014-12-27 22:14:15 +00007794 bool InstanceHasMoreThanOneDecl;
7795 bool FactoryHasMoreThanOneDecl;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00007796 SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
7797 SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007798
7799 public:
Nico Weber2e0c8f72014-12-27 03:58:08 +00007800 ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
Guy Benyei11169dd2012-12-18 14:30:41 +00007801 unsigned PriorGeneration)
Nico Weber2e0c8f72014-12-27 03:58:08 +00007802 : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
Nico Weberff4b35e2014-12-27 22:14:15 +00007803 InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
7804 FactoryHasMoreThanOneDecl(false) {}
Nico Weber2e0c8f72014-12-27 03:58:08 +00007805
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007806 bool operator()(ModuleFile &M) {
Guy Benyei11169dd2012-12-18 14:30:41 +00007807 if (!M.SelectorLookupTable)
7808 return false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007809
Guy Benyei11169dd2012-12-18 14:30:41 +00007810 // If we've already searched this module file, skip it now.
Richard Smithbdf2d932015-07-30 03:37:16 +00007811 if (M.Generation <= PriorGeneration)
Guy Benyei11169dd2012-12-18 14:30:41 +00007812 return true;
7813
Richard Smithbdf2d932015-07-30 03:37:16 +00007814 ++Reader.NumMethodPoolTableLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007815 ASTSelectorLookupTable *PoolTable
7816 = (ASTSelectorLookupTable*)M.SelectorLookupTable;
Richard Smithbdf2d932015-07-30 03:37:16 +00007817 ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
Guy Benyei11169dd2012-12-18 14:30:41 +00007818 if (Pos == PoolTable->end())
7819 return false;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007820
Richard Smithbdf2d932015-07-30 03:37:16 +00007821 ++Reader.NumMethodPoolTableHits;
7822 ++Reader.NumSelectorsRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007823 // FIXME: Not quite happy with the statistics here. We probably should
7824 // disable this tracking when called via LoadSelector.
7825 // Also, should entries without methods count as misses?
Richard Smithbdf2d932015-07-30 03:37:16 +00007826 ++Reader.NumMethodPoolEntriesRead;
Guy Benyei11169dd2012-12-18 14:30:41 +00007827 ASTSelectorLookupTrait::data_type Data = *Pos;
Richard Smithbdf2d932015-07-30 03:37:16 +00007828 if (Reader.DeserializationListener)
7829 Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007830
Richard Smithbdf2d932015-07-30 03:37:16 +00007831 InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
7832 FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
7833 InstanceBits = Data.InstanceBits;
7834 FactoryBits = Data.FactoryBits;
7835 InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
7836 FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00007837 return true;
7838 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007839
Guy Benyei11169dd2012-12-18 14:30:41 +00007840 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007841 ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
7842 return InstanceMethods;
Guy Benyei11169dd2012-12-18 14:30:41 +00007843 }
7844
7845 /// \brief Retrieve the instance methods found by this visitor.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007846 ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
Guy Benyei11169dd2012-12-18 14:30:41 +00007847 return FactoryMethods;
7848 }
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007849
7850 unsigned getInstanceBits() const { return InstanceBits; }
7851 unsigned getFactoryBits() const { return FactoryBits; }
Nico Weberff4b35e2014-12-27 22:14:15 +00007852 bool instanceHasMoreThanOneDecl() const {
7853 return InstanceHasMoreThanOneDecl;
7854 }
7855 bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
Guy Benyei11169dd2012-12-18 14:30:41 +00007856 };
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00007857
7858} // end namespace serialization
7859} // end namespace clang
Guy Benyei11169dd2012-12-18 14:30:41 +00007860
7861/// \brief Add the given set of methods to the method list.
7862static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
7863 ObjCMethodList &List) {
7864 for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
7865 S.addMethodToGlobalList(&List, Methods[I]);
7866 }
7867}
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007868
Guy Benyei11169dd2012-12-18 14:30:41 +00007869void ASTReader::ReadMethodPool(Selector Sel) {
7870 // Get the selector generation and update it to the current generation.
7871 unsigned &Generation = SelectorGeneration[Sel];
7872 unsigned PriorGeneration = Generation;
Richard Smith053f6c62014-05-16 23:01:30 +00007873 Generation = getGeneration();
Manman Rena0f31a02016-04-29 19:04:05 +00007874 SelectorOutOfDate[Sel] = false;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007875
Guy Benyei11169dd2012-12-18 14:30:41 +00007876 // Search for methods defined with this selector.
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007877 ++NumMethodPoolLookups;
Guy Benyei11169dd2012-12-18 14:30:41 +00007878 ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
Benjamin Kramer9a9efba2015-07-25 12:14:04 +00007879 ModuleMgr.visit(Visitor);
7880
Guy Benyei11169dd2012-12-18 14:30:41 +00007881 if (Visitor.getInstanceMethods().empty() &&
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007882 Visitor.getFactoryMethods().empty())
Guy Benyei11169dd2012-12-18 14:30:41 +00007883 return;
Douglas Gregorad2f7a52013-01-28 17:54:36 +00007884
7885 ++NumMethodPoolHits;
7886
Guy Benyei11169dd2012-12-18 14:30:41 +00007887 if (!getSema())
7888 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007889
Guy Benyei11169dd2012-12-18 14:30:41 +00007890 Sema &S = *getSema();
7891 Sema::GlobalMethodPool::iterator Pos
7892 = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
Ben Langmuira0c32e92015-01-12 19:27:00 +00007893
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007894 Pos->second.first.setBits(Visitor.getInstanceBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007895 Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00007896 Pos->second.second.setBits(Visitor.getFactoryBits());
Nico Weberff4b35e2014-12-27 22:14:15 +00007897 Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
Ben Langmuira0c32e92015-01-12 19:27:00 +00007898
7899 // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
7900 // when building a module we keep every method individually and may need to
7901 // update hasMoreThanOneDecl as we add the methods.
7902 addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
7903 addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
Guy Benyei11169dd2012-12-18 14:30:41 +00007904}
7905
Manman Rena0f31a02016-04-29 19:04:05 +00007906void ASTReader::updateOutOfDateSelector(Selector Sel) {
7907 if (SelectorOutOfDate[Sel])
7908 ReadMethodPool(Sel);
7909}
7910
Guy Benyei11169dd2012-12-18 14:30:41 +00007911void ASTReader::ReadKnownNamespaces(
7912 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
7913 Namespaces.clear();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007914
Guy Benyei11169dd2012-12-18 14:30:41 +00007915 for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00007916 if (NamespaceDecl *Namespace
Guy Benyei11169dd2012-12-18 14:30:41 +00007917 = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
7918 Namespaces.push_back(Namespace);
7919 }
7920}
7921
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007922void ASTReader::ReadUndefinedButUsed(
Richard Smithd6a04d72016-03-25 21:49:43 +00007923 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007924 for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
7925 NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
Nick Lewycky8334af82013-01-26 00:35:08 +00007926 SourceLocation Loc =
Nick Lewycky9c7eb1d2013-02-01 08:13:20 +00007927 SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
Nick Lewycky8334af82013-01-26 00:35:08 +00007928 Undefined.insert(std::make_pair(D, Loc));
7929 }
7930}
Nick Lewycky8334af82013-01-26 00:35:08 +00007931
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00007932void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
7933 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
7934 Exprs) {
7935 for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
7936 FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
7937 uint64_t Count = DelayedDeleteExprs[Idx++];
7938 for (uint64_t C = 0; C < Count; ++C) {
7939 SourceLocation DeleteLoc =
7940 SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
7941 const bool IsArrayForm = DelayedDeleteExprs[Idx++];
7942 Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
7943 }
7944 }
7945}
7946
Guy Benyei11169dd2012-12-18 14:30:41 +00007947void ASTReader::ReadTentativeDefinitions(
7948 SmallVectorImpl<VarDecl *> &TentativeDefs) {
7949 for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
7950 VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
7951 if (Var)
7952 TentativeDefs.push_back(Var);
7953 }
7954 TentativeDefinitions.clear();
7955}
7956
7957void ASTReader::ReadUnusedFileScopedDecls(
7958 SmallVectorImpl<const DeclaratorDecl *> &Decls) {
7959 for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
7960 DeclaratorDecl *D
7961 = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
7962 if (D)
7963 Decls.push_back(D);
7964 }
7965 UnusedFileScopedDecls.clear();
7966}
7967
7968void ASTReader::ReadDelegatingConstructors(
7969 SmallVectorImpl<CXXConstructorDecl *> &Decls) {
7970 for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
7971 CXXConstructorDecl *D
7972 = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
7973 if (D)
7974 Decls.push_back(D);
7975 }
7976 DelegatingCtorDecls.clear();
7977}
7978
7979void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
7980 for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
7981 TypedefNameDecl *D
7982 = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
7983 if (D)
7984 Decls.push_back(D);
7985 }
7986 ExtVectorDecls.clear();
7987}
7988
Nico Weber72889432014-09-06 01:25:55 +00007989void ASTReader::ReadUnusedLocalTypedefNameCandidates(
7990 llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
7991 for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
7992 ++I) {
7993 TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
7994 GetDecl(UnusedLocalTypedefNameCandidates[I]));
7995 if (D)
7996 Decls.insert(D);
7997 }
7998 UnusedLocalTypedefNameCandidates.clear();
7999}
8000
Guy Benyei11169dd2012-12-18 14:30:41 +00008001void ASTReader::ReadReferencedSelectors(
8002 SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
8003 if (ReferencedSelectorsData.empty())
8004 return;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008005
Guy Benyei11169dd2012-12-18 14:30:41 +00008006 // If there are @selector references added them to its pool. This is for
8007 // implementation of -Wselector.
8008 unsigned int DataSize = ReferencedSelectorsData.size()-1;
8009 unsigned I = 0;
8010 while (I < DataSize) {
8011 Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
8012 SourceLocation SelLoc
8013 = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
8014 Sels.push_back(std::make_pair(Sel, SelLoc));
8015 }
8016 ReferencedSelectorsData.clear();
8017}
8018
8019void ASTReader::ReadWeakUndeclaredIdentifiers(
8020 SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
8021 if (WeakUndeclaredIdentifiers.empty())
8022 return;
8023
8024 for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008025 IdentifierInfo *WeakId
Guy Benyei11169dd2012-12-18 14:30:41 +00008026 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008027 IdentifierInfo *AliasId
Guy Benyei11169dd2012-12-18 14:30:41 +00008028 = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
8029 SourceLocation Loc
8030 = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
8031 bool Used = WeakUndeclaredIdentifiers[I++];
8032 WeakInfo WI(AliasId, Loc);
8033 WI.setUsed(Used);
8034 WeakIDs.push_back(std::make_pair(WeakId, WI));
8035 }
8036 WeakUndeclaredIdentifiers.clear();
8037}
8038
8039void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
8040 for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
8041 ExternalVTableUse VT;
8042 VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
8043 VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
8044 VT.DefinitionRequired = VTableUses[Idx++];
8045 VTables.push_back(VT);
8046 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008047
Guy Benyei11169dd2012-12-18 14:30:41 +00008048 VTableUses.clear();
8049}
8050
8051void ASTReader::ReadPendingInstantiations(
8052 SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
8053 for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
8054 ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
8055 SourceLocation Loc
8056 = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
8057
8058 Pending.push_back(std::make_pair(D, Loc));
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008059 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008060 PendingInstantiations.clear();
8061}
8062
Richard Smithe40f2ba2013-08-07 21:41:30 +00008063void ASTReader::ReadLateParsedTemplates(
Justin Lebar28f09c52016-10-10 16:26:08 +00008064 llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
8065 &LPTMap) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00008066 for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
8067 /* In loop */) {
8068 FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
8069
Justin Lebar28f09c52016-10-10 16:26:08 +00008070 auto LT = llvm::make_unique<LateParsedTemplate>();
Richard Smithe40f2ba2013-08-07 21:41:30 +00008071 LT->D = GetDecl(LateParsedTemplates[Idx++]);
8072
8073 ModuleFile *F = getOwningModuleFile(LT->D);
8074 assert(F && "No module");
8075
8076 unsigned TokN = LateParsedTemplates[Idx++];
8077 LT->Toks.reserve(TokN);
8078 for (unsigned T = 0; T < TokN; ++T)
8079 LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
8080
Justin Lebar28f09c52016-10-10 16:26:08 +00008081 LPTMap.insert(std::make_pair(FD, std::move(LT)));
Richard Smithe40f2ba2013-08-07 21:41:30 +00008082 }
8083
8084 LateParsedTemplates.clear();
8085}
8086
Guy Benyei11169dd2012-12-18 14:30:41 +00008087void ASTReader::LoadSelector(Selector Sel) {
8088 // It would be complicated to avoid reading the methods anyway. So don't.
8089 ReadMethodPool(Sel);
8090}
8091
8092void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
8093 assert(ID && "Non-zero identifier ID required");
8094 assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
8095 IdentifiersLoaded[ID - 1] = II;
8096 if (DeserializationListener)
8097 DeserializationListener->IdentifierRead(ID, II);
8098}
8099
8100/// \brief Set the globally-visible declarations associated with the given
8101/// identifier.
8102///
8103/// If the AST reader is currently in a state where the given declaration IDs
8104/// cannot safely be resolved, they are queued until it is safe to resolve
8105/// them.
8106///
8107/// \param II an IdentifierInfo that refers to one or more globally-visible
8108/// declarations.
8109///
8110/// \param DeclIDs the set of declaration IDs with the name @p II that are
8111/// visible at global scope.
8112///
Douglas Gregor6168bd22013-02-18 15:53:43 +00008113/// \param Decls if non-null, this vector will be populated with the set of
8114/// deserialized declarations. These declarations will not be pushed into
8115/// scope.
Guy Benyei11169dd2012-12-18 14:30:41 +00008116void
8117ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
8118 const SmallVectorImpl<uint32_t> &DeclIDs,
Douglas Gregor6168bd22013-02-18 15:53:43 +00008119 SmallVectorImpl<Decl *> *Decls) {
8120 if (NumCurrentElementsDeserializing && !Decls) {
8121 PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
Guy Benyei11169dd2012-12-18 14:30:41 +00008122 return;
8123 }
8124
8125 for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
Ben Langmuir5418f402014-09-10 21:29:41 +00008126 if (!SemaObj) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008127 // Queue this declaration so that it will be added to the
8128 // translation unit scope and identifier's declaration chain
8129 // once a Sema object is known.
Ben Langmuir5418f402014-09-10 21:29:41 +00008130 PreloadedDeclIDs.push_back(DeclIDs[I]);
8131 continue;
Guy Benyei11169dd2012-12-18 14:30:41 +00008132 }
Ben Langmuir5418f402014-09-10 21:29:41 +00008133
8134 NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
8135
8136 // If we're simply supposed to record the declarations, do so now.
8137 if (Decls) {
8138 Decls->push_back(D);
8139 continue;
8140 }
8141
8142 // Introduce this declaration into the translation-unit scope
8143 // and add it to the declaration chain for this identifier, so
8144 // that (unqualified) name lookup will find it.
8145 pushExternalDeclIntoScope(D, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008146 }
8147}
8148
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008149IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008150 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008151 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008152
8153 if (IdentifiersLoaded.empty()) {
8154 Error("no identifier table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008155 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008156 }
8157
8158 ID -= 1;
8159 if (!IdentifiersLoaded[ID]) {
8160 GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
8161 assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
8162 ModuleFile *M = I->second;
8163 unsigned Index = ID - M->BaseIdentifierID;
8164 const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
8165
8166 // All of the strings in the AST file are preceded by a 16-bit length.
8167 // Extract that 16-bit length to avoid having to execute strlen().
8168 // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
8169 // unsigned integers. This is important to avoid integer overflow when
8170 // we cast them to 'unsigned'.
8171 const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
8172 unsigned StrLen = (((unsigned) StrLenPtr[0])
8173 | (((unsigned) StrLenPtr[1]) << 8)) - 1;
Richard Smitheb4b58f62016-02-05 01:40:54 +00008174 auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
8175 IdentifiersLoaded[ID] = &II;
8176 markIdentifierFromAST(*this, II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008177 if (DeserializationListener)
Richard Smitheb4b58f62016-02-05 01:40:54 +00008178 DeserializationListener->IdentifierRead(ID + 1, &II);
Guy Benyei11169dd2012-12-18 14:30:41 +00008179 }
8180
8181 return IdentifiersLoaded[ID];
8182}
8183
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008184IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
8185 return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
Guy Benyei11169dd2012-12-18 14:30:41 +00008186}
8187
8188IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
8189 if (LocalID < NUM_PREDEF_IDENT_IDS)
8190 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008191
Richard Smith37a93df2017-02-18 00:32:02 +00008192 if (!M.ModuleOffsetMap.empty())
8193 ReadModuleOffsetMap(M);
8194
Guy Benyei11169dd2012-12-18 14:30:41 +00008195 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8196 = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008197 assert(I != M.IdentifierRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008198 && "Invalid index into identifier index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008199
Guy Benyei11169dd2012-12-18 14:30:41 +00008200 return LocalID + I->second;
8201}
8202
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008203MacroInfo *ASTReader::getMacro(MacroID ID) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008204 if (ID == 0)
Craig Toppera13603a2014-05-22 05:54:18 +00008205 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008206
8207 if (MacrosLoaded.empty()) {
8208 Error("no macro table in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008209 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008210 }
8211
8212 ID -= NUM_PREDEF_MACRO_IDS;
8213 if (!MacrosLoaded[ID]) {
8214 GlobalMacroMapType::iterator I
8215 = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
8216 assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
8217 ModuleFile *M = I->second;
8218 unsigned Index = ID - M->BaseMacroID;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008219 MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008220
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00008221 if (DeserializationListener)
8222 DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
8223 MacrosLoaded[ID]);
Guy Benyei11169dd2012-12-18 14:30:41 +00008224 }
8225
8226 return MacrosLoaded[ID];
8227}
8228
8229MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
8230 if (LocalID < NUM_PREDEF_MACRO_IDS)
8231 return LocalID;
8232
Richard Smith37a93df2017-02-18 00:32:02 +00008233 if (!M.ModuleOffsetMap.empty())
8234 ReadModuleOffsetMap(M);
8235
Guy Benyei11169dd2012-12-18 14:30:41 +00008236 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8237 = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
8238 assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
8239
8240 return LocalID + I->second;
8241}
8242
8243serialization::SubmoduleID
8244ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
8245 if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
8246 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008247
Richard Smith37a93df2017-02-18 00:32:02 +00008248 if (!M.ModuleOffsetMap.empty())
8249 ReadModuleOffsetMap(M);
8250
Guy Benyei11169dd2012-12-18 14:30:41 +00008251 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8252 = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008253 assert(I != M.SubmoduleRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008254 && "Invalid index into submodule index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008255
Guy Benyei11169dd2012-12-18 14:30:41 +00008256 return LocalID + I->second;
8257}
8258
8259Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
8260 if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
8261 assert(GlobalID == 0 && "Unhandled global submodule ID");
Craig Toppera13603a2014-05-22 05:54:18 +00008262 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008263 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008264
Guy Benyei11169dd2012-12-18 14:30:41 +00008265 if (GlobalID > SubmodulesLoaded.size()) {
8266 Error("submodule ID out of range in AST file");
Craig Toppera13603a2014-05-22 05:54:18 +00008267 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008268 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008269
Guy Benyei11169dd2012-12-18 14:30:41 +00008270 return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
8271}
Douglas Gregorc147b0b2013-01-12 01:29:50 +00008272
8273Module *ASTReader::getModule(unsigned ID) {
8274 return getSubmodule(ID);
8275}
8276
Richard Smithd88a7f12015-09-01 20:35:42 +00008277ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
8278 if (ID & 1) {
8279 // It's a module, look it up by submodule ID.
8280 auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
8281 return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
8282 } else {
8283 // It's a prefix (preamble, PCH, ...). Look it up by index.
8284 unsigned IndexFromEnd = ID >> 1;
8285 assert(IndexFromEnd && "got reference to unknown module file");
8286 return getModuleManager().pch_modules().end()[-IndexFromEnd];
8287 }
8288}
8289
8290unsigned ASTReader::getModuleFileID(ModuleFile *F) {
8291 if (!F)
8292 return 1;
8293
8294 // For a file representing a module, use the submodule ID of the top-level
8295 // module as the file ID. For any other kind of file, the number of such
8296 // files loaded beforehand will be the same on reload.
8297 // FIXME: Is this true even if we have an explicit module file and a PCH?
8298 if (F->isModule())
8299 return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
8300
8301 auto PCHModules = getModuleManager().pch_modules();
8302 auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
8303 assert(I != PCHModules.end() && "emitting reference to unknown file");
8304 return (I - PCHModules.end()) << 1;
8305}
8306
Adrian Prantl15bcf702015-06-30 17:39:43 +00008307llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
8308ASTReader::getSourceDescriptor(unsigned ID) {
8309 if (const Module *M = getSubmodule(ID))
Adrian Prantlc6458d62015-09-19 00:10:32 +00008310 return ExternalASTSource::ASTSourceDescriptor(*M);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008311
8312 // If there is only a single PCH, return it instead.
Hiroshi Inoue3170de02017-07-01 08:46:43 +00008313 // Chained PCH are not supported.
Saleem Abdulrasool97d25552017-03-02 17:37:11 +00008314 const auto &PCHChain = ModuleMgr.pch_modules();
8315 if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
Adrian Prantl15bcf702015-06-30 17:39:43 +00008316 ModuleFile &MF = ModuleMgr.getPrimaryModule();
Adrian Prantl3a2d4942016-01-22 23:30:56 +00008317 StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
Adrian Prantl9bc3c4f2016-04-27 17:06:22 +00008318 StringRef FileName = llvm::sys::path::filename(MF.FileName);
8319 return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
8320 MF.Signature);
Adrian Prantl15bcf702015-06-30 17:39:43 +00008321 }
8322 return None;
8323}
8324
David Blaikie1ac9c982017-04-11 21:13:37 +00008325ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
Richard Smitha4653622017-09-06 20:01:14 +00008326 auto I = DefinitionSource.find(FD);
8327 if (I == DefinitionSource.end())
David Blaikie9ffe5a32017-01-30 05:00:26 +00008328 return EK_ReplyHazy;
David Blaikiee6b7c282017-04-11 20:46:34 +00008329 return I->second ? EK_Never : EK_Always;
David Blaikie9ffe5a32017-01-30 05:00:26 +00008330}
8331
Guy Benyei11169dd2012-12-18 14:30:41 +00008332Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
8333 return DecodeSelector(getGlobalSelectorID(M, LocalID));
8334}
8335
8336Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
8337 if (ID == 0)
8338 return Selector();
8339
8340 if (ID > SelectorsLoaded.size()) {
8341 Error("selector ID out of range in AST file");
8342 return Selector();
8343 }
8344
Craig Toppera13603a2014-05-22 05:54:18 +00008345 if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008346 // Load this selector from the selector table.
8347 GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
8348 assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
8349 ModuleFile &M = *I->second;
8350 ASTSelectorLookupTrait Trait(*this, M);
8351 unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
8352 SelectorsLoaded[ID - 1] =
8353 Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
8354 if (DeserializationListener)
8355 DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
8356 }
8357
8358 return SelectorsLoaded[ID - 1];
8359}
8360
8361Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
8362 return DecodeSelector(ID);
8363}
8364
8365uint32_t ASTReader::GetNumExternalSelectors() {
8366 // ID 0 (the null selector) is considered an external selector.
8367 return getTotalNumSelectors() + 1;
8368}
8369
8370serialization::SelectorID
8371ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
8372 if (LocalID < NUM_PREDEF_SELECTOR_IDS)
8373 return LocalID;
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008374
Richard Smith37a93df2017-02-18 00:32:02 +00008375 if (!M.ModuleOffsetMap.empty())
8376 ReadModuleOffsetMap(M);
8377
Guy Benyei11169dd2012-12-18 14:30:41 +00008378 ContinuousRangeMap<uint32_t, int, 2>::iterator I
8379 = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008380 assert(I != M.SelectorRemap.end()
Guy Benyei11169dd2012-12-18 14:30:41 +00008381 && "Invalid index into selector index remap");
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008382
Guy Benyei11169dd2012-12-18 14:30:41 +00008383 return LocalID + I->second;
8384}
8385
8386DeclarationName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008387ASTReader::ReadDeclarationName(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008388 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008389 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008390 DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
8391 switch (Kind) {
8392 case DeclarationName::Identifier:
Douglas Gregorc8a992f2013-01-21 16:52:34 +00008393 return DeclarationName(GetIdentifierInfo(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008394
8395 case DeclarationName::ObjCZeroArgSelector:
8396 case DeclarationName::ObjCOneArgSelector:
8397 case DeclarationName::ObjCMultiArgSelector:
8398 return DeclarationName(ReadSelector(F, Record, Idx));
8399
8400 case DeclarationName::CXXConstructorName:
8401 return Context.DeclarationNames.getCXXConstructorName(
8402 Context.getCanonicalType(readType(F, Record, Idx)));
8403
8404 case DeclarationName::CXXDestructorName:
8405 return Context.DeclarationNames.getCXXDestructorName(
8406 Context.getCanonicalType(readType(F, Record, Idx)));
8407
Richard Smith35845152017-02-07 01:37:30 +00008408 case DeclarationName::CXXDeductionGuideName:
8409 return Context.DeclarationNames.getCXXDeductionGuideName(
8410 ReadDeclAs<TemplateDecl>(F, Record, Idx));
8411
Guy Benyei11169dd2012-12-18 14:30:41 +00008412 case DeclarationName::CXXConversionFunctionName:
8413 return Context.DeclarationNames.getCXXConversionFunctionName(
8414 Context.getCanonicalType(readType(F, Record, Idx)));
8415
8416 case DeclarationName::CXXOperatorName:
8417 return Context.DeclarationNames.getCXXOperatorName(
8418 (OverloadedOperatorKind)Record[Idx++]);
8419
8420 case DeclarationName::CXXLiteralOperatorName:
8421 return Context.DeclarationNames.getCXXLiteralOperatorName(
8422 GetIdentifierInfo(F, Record, Idx));
8423
8424 case DeclarationName::CXXUsingDirective:
8425 return DeclarationName::getUsingDirectiveName();
8426 }
8427
8428 llvm_unreachable("Invalid NameKind!");
8429}
8430
8431void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
8432 DeclarationNameLoc &DNLoc,
8433 DeclarationName Name,
8434 const RecordData &Record, unsigned &Idx) {
8435 switch (Name.getNameKind()) {
8436 case DeclarationName::CXXConstructorName:
8437 case DeclarationName::CXXDestructorName:
8438 case DeclarationName::CXXConversionFunctionName:
8439 DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
8440 break;
8441
8442 case DeclarationName::CXXOperatorName:
8443 DNLoc.CXXOperatorName.BeginOpNameLoc
8444 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8445 DNLoc.CXXOperatorName.EndOpNameLoc
8446 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8447 break;
8448
8449 case DeclarationName::CXXLiteralOperatorName:
8450 DNLoc.CXXLiteralOperatorName.OpNameLoc
8451 = ReadSourceLocation(F, Record, Idx).getRawEncoding();
8452 break;
8453
8454 case DeclarationName::Identifier:
8455 case DeclarationName::ObjCZeroArgSelector:
8456 case DeclarationName::ObjCOneArgSelector:
8457 case DeclarationName::ObjCMultiArgSelector:
8458 case DeclarationName::CXXUsingDirective:
Richard Smith35845152017-02-07 01:37:30 +00008459 case DeclarationName::CXXDeductionGuideName:
Guy Benyei11169dd2012-12-18 14:30:41 +00008460 break;
8461 }
8462}
8463
8464void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
8465 DeclarationNameInfo &NameInfo,
8466 const RecordData &Record, unsigned &Idx) {
8467 NameInfo.setName(ReadDeclarationName(F, Record, Idx));
8468 NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
8469 DeclarationNameLoc DNLoc;
8470 ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
8471 NameInfo.setInfo(DNLoc);
8472}
8473
8474void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
8475 const RecordData &Record, unsigned &Idx) {
8476 Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
8477 unsigned NumTPLists = Record[Idx++];
8478 Info.NumTemplParamLists = NumTPLists;
8479 if (NumTPLists) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008480 Info.TemplParamLists =
8481 new (getContext()) TemplateParameterList *[NumTPLists];
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00008482 for (unsigned i = 0; i != NumTPLists; ++i)
Guy Benyei11169dd2012-12-18 14:30:41 +00008483 Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
8484 }
8485}
8486
8487TemplateName
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008488ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008489 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008490 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008491 TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
8492 switch (Kind) {
8493 case TemplateName::Template:
8494 return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
8495
8496 case TemplateName::OverloadedTemplate: {
8497 unsigned size = Record[Idx++];
8498 UnresolvedSet<8> Decls;
8499 while (size--)
8500 Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
8501
8502 return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
8503 }
8504
8505 case TemplateName::QualifiedTemplate: {
8506 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8507 bool hasTemplKeyword = Record[Idx++];
8508 TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
8509 return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
8510 }
8511
8512 case TemplateName::DependentTemplate: {
8513 NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
8514 if (Record[Idx++]) // isIdentifier
8515 return Context.getDependentTemplateName(NNS,
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008516 GetIdentifierInfo(F, Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008517 Idx));
8518 return Context.getDependentTemplateName(NNS,
8519 (OverloadedOperatorKind)Record[Idx++]);
8520 }
8521
8522 case TemplateName::SubstTemplateTemplateParm: {
8523 TemplateTemplateParmDecl *param
8524 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8525 if (!param) return TemplateName();
8526 TemplateName replacement = ReadTemplateName(F, Record, Idx);
8527 return Context.getSubstTemplateTemplateParm(param, replacement);
8528 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008529
Guy Benyei11169dd2012-12-18 14:30:41 +00008530 case TemplateName::SubstTemplateTemplateParmPack: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008531 TemplateTemplateParmDecl *Param
Guy Benyei11169dd2012-12-18 14:30:41 +00008532 = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
8533 if (!Param)
8534 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008535
Guy Benyei11169dd2012-12-18 14:30:41 +00008536 TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
8537 if (ArgPack.getKind() != TemplateArgument::Pack)
8538 return TemplateName();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008539
Guy Benyei11169dd2012-12-18 14:30:41 +00008540 return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
8541 }
8542 }
8543
8544 llvm_unreachable("Unhandled template name kind!");
8545}
8546
Richard Smith2bb3c342015-08-09 01:05:31 +00008547TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
8548 const RecordData &Record,
8549 unsigned &Idx,
8550 bool Canonicalize) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008551 ASTContext &Context = getContext();
Richard Smith2bb3c342015-08-09 01:05:31 +00008552 if (Canonicalize) {
8553 // The caller wants a canonical template argument. Sometimes the AST only
8554 // wants template arguments in canonical form (particularly as the template
8555 // argument lists of template specializations) so ensure we preserve that
8556 // canonical form across serialization.
8557 TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
8558 return Context.getCanonicalTemplateArgument(Arg);
8559 }
8560
Guy Benyei11169dd2012-12-18 14:30:41 +00008561 TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
8562 switch (Kind) {
8563 case TemplateArgument::Null:
8564 return TemplateArgument();
8565 case TemplateArgument::Type:
8566 return TemplateArgument(readType(F, Record, Idx));
8567 case TemplateArgument::Declaration: {
8568 ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
David Blaikie0f62c8d2014-10-16 04:21:25 +00008569 return TemplateArgument(D, readType(F, Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008570 }
8571 case TemplateArgument::NullPtr:
8572 return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
8573 case TemplateArgument::Integral: {
8574 llvm::APSInt Value = ReadAPSInt(Record, Idx);
8575 QualType T = readType(F, Record, Idx);
8576 return TemplateArgument(Context, Value, T);
8577 }
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008578 case TemplateArgument::Template:
Guy Benyei11169dd2012-12-18 14:30:41 +00008579 return TemplateArgument(ReadTemplateName(F, Record, Idx));
8580 case TemplateArgument::TemplateExpansion: {
8581 TemplateName Name = ReadTemplateName(F, Record, Idx);
David Blaikie05785d12013-02-20 22:23:23 +00008582 Optional<unsigned> NumTemplateExpansions;
Guy Benyei11169dd2012-12-18 14:30:41 +00008583 if (unsigned NumExpansions = Record[Idx++])
8584 NumTemplateExpansions = NumExpansions - 1;
8585 return TemplateArgument(Name, NumTemplateExpansions);
8586 }
8587 case TemplateArgument::Expression:
8588 return TemplateArgument(ReadExpr(F));
8589 case TemplateArgument::Pack: {
8590 unsigned NumArgs = Record[Idx++];
8591 TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
8592 for (unsigned I = 0; I != NumArgs; ++I)
8593 Args[I] = ReadTemplateArgument(F, Record, Idx);
Benjamin Kramercce63472015-08-05 09:40:22 +00008594 return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
Guy Benyei11169dd2012-12-18 14:30:41 +00008595 }
8596 }
8597
8598 llvm_unreachable("Unhandled template argument kind!");
8599}
8600
8601TemplateParameterList *
8602ASTReader::ReadTemplateParameterList(ModuleFile &F,
8603 const RecordData &Record, unsigned &Idx) {
8604 SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
8605 SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
8606 SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
8607
8608 unsigned NumParams = Record[Idx++];
8609 SmallVector<NamedDecl *, 16> Params;
8610 Params.reserve(NumParams);
8611 while (NumParams--)
8612 Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
8613
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00008614 // TODO: Concepts
Richard Smithdbafb6c2017-06-29 23:23:46 +00008615 TemplateParameterList *TemplateParams = TemplateParameterList::Create(
8616 getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00008617 return TemplateParams;
8618}
8619
8620void
8621ASTReader::
Craig Topper5603df42013-07-05 19:34:19 +00008622ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00008623 ModuleFile &F, const RecordData &Record,
Richard Smith2bb3c342015-08-09 01:05:31 +00008624 unsigned &Idx, bool Canonicalize) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008625 unsigned NumTemplateArgs = Record[Idx++];
8626 TemplArgs.reserve(NumTemplateArgs);
8627 while (NumTemplateArgs--)
Richard Smith2bb3c342015-08-09 01:05:31 +00008628 TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
Guy Benyei11169dd2012-12-18 14:30:41 +00008629}
8630
8631/// \brief Read a UnresolvedSet structure.
Richard Smitha4ba74c2013-08-30 04:46:40 +00008632void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
Guy Benyei11169dd2012-12-18 14:30:41 +00008633 const RecordData &Record, unsigned &Idx) {
8634 unsigned NumDecls = Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008635 Set.reserve(getContext(), NumDecls);
Guy Benyei11169dd2012-12-18 14:30:41 +00008636 while (NumDecls--) {
Richard Smitha4ba74c2013-08-30 04:46:40 +00008637 DeclID ID = ReadDeclID(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008638 AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
Richard Smithdbafb6c2017-06-29 23:23:46 +00008639 Set.addLazyDecl(getContext(), ID, AS);
Guy Benyei11169dd2012-12-18 14:30:41 +00008640 }
8641}
8642
8643CXXBaseSpecifier
8644ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
8645 const RecordData &Record, unsigned &Idx) {
8646 bool isVirtual = static_cast<bool>(Record[Idx++]);
8647 bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
8648 AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
8649 bool inheritConstructors = static_cast<bool>(Record[Idx++]);
8650 TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
8651 SourceRange Range = ReadSourceRange(F, Record, Idx);
8652 SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008653 CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
Guy Benyei11169dd2012-12-18 14:30:41 +00008654 EllipsisLoc);
8655 Result.setInheritConstructors(inheritConstructors);
8656 return Result;
8657}
8658
Richard Smithc2bb8182015-03-24 06:36:48 +00008659CXXCtorInitializer **
Guy Benyei11169dd2012-12-18 14:30:41 +00008660ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
8661 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008662 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008663 unsigned NumInitializers = Record[Idx++];
Richard Smithc2bb8182015-03-24 06:36:48 +00008664 assert(NumInitializers && "wrote ctor initializers but have no inits");
8665 auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
8666 for (unsigned i = 0; i != NumInitializers; ++i) {
8667 TypeSourceInfo *TInfo = nullptr;
8668 bool IsBaseVirtual = false;
8669 FieldDecl *Member = nullptr;
8670 IndirectFieldDecl *IndirectMember = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008671
Richard Smithc2bb8182015-03-24 06:36:48 +00008672 CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
8673 switch (Type) {
8674 case CTOR_INITIALIZER_BASE:
8675 TInfo = GetTypeSourceInfo(F, Record, Idx);
8676 IsBaseVirtual = Record[Idx++];
8677 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008678
Richard Smithc2bb8182015-03-24 06:36:48 +00008679 case CTOR_INITIALIZER_DELEGATING:
8680 TInfo = GetTypeSourceInfo(F, Record, Idx);
8681 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008682
Richard Smithc2bb8182015-03-24 06:36:48 +00008683 case CTOR_INITIALIZER_MEMBER:
8684 Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
8685 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008686
Richard Smithc2bb8182015-03-24 06:36:48 +00008687 case CTOR_INITIALIZER_INDIRECT_MEMBER:
8688 IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
8689 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008690 }
Richard Smithc2bb8182015-03-24 06:36:48 +00008691
8692 SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
8693 Expr *Init = ReadExpr(F);
8694 SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
8695 SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
Richard Smithc2bb8182015-03-24 06:36:48 +00008696
8697 CXXCtorInitializer *BOMInit;
Richard Smith30e304e2016-12-14 00:03:17 +00008698 if (Type == CTOR_INITIALIZER_BASE)
Richard Smithc2bb8182015-03-24 06:36:48 +00008699 BOMInit = new (Context)
8700 CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
8701 RParenLoc, MemberOrEllipsisLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008702 else if (Type == CTOR_INITIALIZER_DELEGATING)
Richard Smithc2bb8182015-03-24 06:36:48 +00008703 BOMInit = new (Context)
8704 CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
Richard Smith30e304e2016-12-14 00:03:17 +00008705 else if (Member)
8706 BOMInit = new (Context)
8707 CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
8708 Init, RParenLoc);
8709 else
8710 BOMInit = new (Context)
8711 CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
8712 LParenLoc, Init, RParenLoc);
8713
Richard Smith418ed822016-12-14 19:45:03 +00008714 if (/*IsWritten*/Record[Idx++]) {
Richard Smith30e304e2016-12-14 00:03:17 +00008715 unsigned SourceOrder = Record[Idx++];
8716 BOMInit->setSourceOrder(SourceOrder);
Richard Smithc2bb8182015-03-24 06:36:48 +00008717 }
8718
Richard Smithc2bb8182015-03-24 06:36:48 +00008719 CtorInitializers[i] = BOMInit;
Guy Benyei11169dd2012-12-18 14:30:41 +00008720 }
8721
Richard Smithc2bb8182015-03-24 06:36:48 +00008722 return CtorInitializers;
Guy Benyei11169dd2012-12-18 14:30:41 +00008723}
8724
8725NestedNameSpecifier *
8726ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
8727 const RecordData &Record, unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008728 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008729 unsigned N = Record[Idx++];
Craig Toppera13603a2014-05-22 05:54:18 +00008730 NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00008731 for (unsigned I = 0; I != N; ++I) {
8732 NestedNameSpecifier::SpecifierKind Kind
8733 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8734 switch (Kind) {
8735 case NestedNameSpecifier::Identifier: {
8736 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
8737 NNS = NestedNameSpecifier::Create(Context, Prev, II);
8738 break;
8739 }
8740
8741 case NestedNameSpecifier::Namespace: {
8742 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8743 NNS = NestedNameSpecifier::Create(Context, Prev, NS);
8744 break;
8745 }
8746
8747 case NestedNameSpecifier::NamespaceAlias: {
8748 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8749 NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
8750 break;
8751 }
8752
8753 case NestedNameSpecifier::TypeSpec:
8754 case NestedNameSpecifier::TypeSpecWithTemplate: {
8755 const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
8756 if (!T)
Craig Toppera13603a2014-05-22 05:54:18 +00008757 return nullptr;
8758
Guy Benyei11169dd2012-12-18 14:30:41 +00008759 bool Template = Record[Idx++];
8760 NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
8761 break;
8762 }
8763
8764 case NestedNameSpecifier::Global: {
8765 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
8766 // No associated value, and there can't be a prefix.
8767 break;
8768 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008769
8770 case NestedNameSpecifier::Super: {
8771 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8772 NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
8773 break;
8774 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008775 }
8776 Prev = NNS;
8777 }
8778 return NNS;
8779}
8780
8781NestedNameSpecifierLoc
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008782ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008783 unsigned &Idx) {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008784 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008785 unsigned N = Record[Idx++];
8786 NestedNameSpecifierLocBuilder Builder;
8787 for (unsigned I = 0; I != N; ++I) {
8788 NestedNameSpecifier::SpecifierKind Kind
8789 = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
8790 switch (Kind) {
8791 case NestedNameSpecifier::Identifier: {
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008792 IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
Guy Benyei11169dd2012-12-18 14:30:41 +00008793 SourceRange Range = ReadSourceRange(F, Record, Idx);
8794 Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
8795 break;
8796 }
8797
8798 case NestedNameSpecifier::Namespace: {
8799 NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
8800 SourceRange Range = ReadSourceRange(F, Record, Idx);
8801 Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
8802 break;
8803 }
8804
8805 case NestedNameSpecifier::NamespaceAlias: {
8806 NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
8807 SourceRange Range = ReadSourceRange(F, Record, Idx);
8808 Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
8809 break;
8810 }
8811
8812 case NestedNameSpecifier::TypeSpec:
8813 case NestedNameSpecifier::TypeSpecWithTemplate: {
8814 bool Template = Record[Idx++];
8815 TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
8816 if (!T)
8817 return NestedNameSpecifierLoc();
8818 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8819
8820 // FIXME: 'template' keyword location not saved anywhere, so we fake it.
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008821 Builder.Extend(Context,
Guy Benyei11169dd2012-12-18 14:30:41 +00008822 Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
8823 T->getTypeLoc(), ColonColonLoc);
8824 break;
8825 }
8826
8827 case NestedNameSpecifier::Global: {
8828 SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
8829 Builder.MakeGlobal(Context, ColonColonLoc);
8830 break;
8831 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008832
8833 case NestedNameSpecifier::Super: {
8834 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
8835 SourceRange Range = ReadSourceRange(F, Record, Idx);
8836 Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
8837 break;
8838 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008839 }
8840 }
Nikola Smiljanic67860242014-09-26 00:28:20 +00008841
Guy Benyei11169dd2012-12-18 14:30:41 +00008842 return Builder.getWithLocInContext(Context);
8843}
8844
8845SourceRange
8846ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
8847 unsigned &Idx) {
8848 SourceLocation beg = ReadSourceLocation(F, Record, Idx);
8849 SourceLocation end = ReadSourceLocation(F, Record, Idx);
8850 return SourceRange(beg, end);
8851}
8852
8853/// \brief Read an integral value
8854llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
8855 unsigned BitWidth = Record[Idx++];
8856 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
8857 llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
8858 Idx += NumWords;
8859 return Result;
8860}
8861
8862/// \brief Read a signed integral value
8863llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
8864 bool isUnsigned = Record[Idx++];
8865 return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
8866}
8867
8868/// \brief Read a floating-point value
Tim Northover178723a2013-01-22 09:46:51 +00008869llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
8870 const llvm::fltSemantics &Sem,
8871 unsigned &Idx) {
8872 return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
Guy Benyei11169dd2012-12-18 14:30:41 +00008873}
8874
8875// \brief Read a string
8876std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
8877 unsigned Len = Record[Idx++];
8878 std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
8879 Idx += Len;
8880 return Result;
8881}
8882
Richard Smith7ed1bc92014-12-05 22:42:13 +00008883std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
8884 unsigned &Idx) {
8885 std::string Filename = ReadString(Record, Idx);
8886 ResolveImportedPath(F, Filename);
8887 return Filename;
8888}
8889
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008890VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
Guy Benyei11169dd2012-12-18 14:30:41 +00008891 unsigned &Idx) {
8892 unsigned Major = Record[Idx++];
8893 unsigned Minor = Record[Idx++];
8894 unsigned Subminor = Record[Idx++];
8895 if (Minor == 0)
8896 return VersionTuple(Major);
8897 if (Subminor == 0)
8898 return VersionTuple(Major, Minor - 1);
8899 return VersionTuple(Major, Minor - 1, Subminor - 1);
8900}
8901
David L. Jonesc4808b9e2016-12-15 20:53:26 +00008902CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
Guy Benyei11169dd2012-12-18 14:30:41 +00008903 const RecordData &Record,
8904 unsigned &Idx) {
8905 CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
Richard Smithdbafb6c2017-06-29 23:23:46 +00008906 return CXXTemporary::Create(getContext(), Decl);
Guy Benyei11169dd2012-12-18 14:30:41 +00008907}
8908
Richard Smith37a93df2017-02-18 00:32:02 +00008909DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
Argyrios Kyrtzidisdc9fdaf2013-05-24 05:44:08 +00008910 return Diag(CurrentImportLoc, DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00008911}
8912
Richard Smith37a93df2017-02-18 00:32:02 +00008913DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
Guy Benyei11169dd2012-12-18 14:30:41 +00008914 return Diags.Report(Loc, DiagID);
8915}
8916
8917/// \brief Retrieve the identifier table associated with the
8918/// preprocessor.
8919IdentifierTable &ASTReader::getIdentifierTable() {
8920 return PP.getIdentifierTable();
8921}
8922
8923/// \brief Record that the given ID maps to the given switch-case
8924/// statement.
8925void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008926 assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
Guy Benyei11169dd2012-12-18 14:30:41 +00008927 "Already have a SwitchCase with this ID");
8928 (*CurrSwitchCaseStmts)[ID] = SC;
8929}
8930
8931/// \brief Retrieve the switch-case statement with the given ID.
8932SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
Craig Toppera13603a2014-05-22 05:54:18 +00008933 assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
Guy Benyei11169dd2012-12-18 14:30:41 +00008934 return (*CurrSwitchCaseStmts)[ID];
8935}
8936
8937void ASTReader::ClearSwitchCaseIDs() {
8938 CurrSwitchCaseStmts->clear();
8939}
8940
8941void ASTReader::ReadComments() {
Richard Smithdbafb6c2017-06-29 23:23:46 +00008942 ASTContext &Context = getContext();
Guy Benyei11169dd2012-12-18 14:30:41 +00008943 std::vector<RawComment *> Comments;
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008944 for (SmallVectorImpl<std::pair<BitstreamCursor,
Guy Benyei11169dd2012-12-18 14:30:41 +00008945 serialization::ModuleFile *> >::iterator
8946 I = CommentsCursors.begin(),
8947 E = CommentsCursors.end();
8948 I != E; ++I) {
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008949 Comments.clear();
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008950 BitstreamCursor &Cursor = I->first;
Guy Benyei11169dd2012-12-18 14:30:41 +00008951 serialization::ModuleFile &F = *I->second;
8952 SavedStreamPosition SavedPosition(Cursor);
8953
8954 RecordData Record;
8955 while (true) {
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008956 llvm::BitstreamEntry Entry =
8957 Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008958
Chris Lattner7fb3bef2013-01-20 00:56:42 +00008959 switch (Entry.Kind) {
8960 case llvm::BitstreamEntry::SubBlock: // Handled for us already.
8961 case llvm::BitstreamEntry::Error:
8962 Error("malformed block record in AST file");
8963 return;
8964 case llvm::BitstreamEntry::EndBlock:
8965 goto NextCursor;
8966 case llvm::BitstreamEntry::Record:
8967 // The interesting case.
Guy Benyei11169dd2012-12-18 14:30:41 +00008968 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00008969 }
8970
8971 // Read a record.
8972 Record.clear();
Chris Lattner0e6c9402013-01-20 02:38:54 +00008973 switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00008974 case COMMENTS_RAW_COMMENT: {
8975 unsigned Idx = 0;
8976 SourceRange SR = ReadSourceRange(F, Record, Idx);
8977 RawComment::CommentKind Kind =
8978 (RawComment::CommentKind) Record[Idx++];
8979 bool IsTrailingComment = Record[Idx++];
8980 bool IsAlmostTrailingComment = Record[Idx++];
Dmitri Gribenkoa7d16ce2013-04-10 15:35:17 +00008981 Comments.push_back(new (Context) RawComment(
8982 SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
8983 Context.getLangOpts().CommentOpts.ParseAllComments));
Guy Benyei11169dd2012-12-18 14:30:41 +00008984 break;
8985 }
8986 }
8987 }
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008988 NextCursor:
Bruno Cardoso Lopesc23af572016-12-19 21:06:06 +00008989 // De-serialized SourceLocations get negative FileIDs for other modules,
8990 // potentially invalidating the original order. Sort it again.
8991 std::sort(Comments.begin(), Comments.end(),
8992 BeforeThanCompare<RawComment>(SourceMgr));
Dmitri Gribenko9ee0e302014-03-27 15:40:39 +00008993 Context.Comments.addDeserializedComments(Comments);
Guy Benyei11169dd2012-12-18 14:30:41 +00008994 }
Guy Benyei11169dd2012-12-18 14:30:41 +00008995}
8996
Argyrios Kyrtzidisa38cb202017-01-30 06:05:58 +00008997void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
8998 bool IncludeSystem, bool Complain,
8999 llvm::function_ref<void(const serialization::InputFile &IF,
9000 bool isSystem)> Visitor) {
9001 unsigned NumUserInputs = MF.NumUserInputFiles;
9002 unsigned NumInputs = MF.InputFilesLoaded.size();
9003 assert(NumUserInputs <= NumInputs);
9004 unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
9005 for (unsigned I = 0; I < N; ++I) {
9006 bool IsSystem = I >= NumUserInputs;
9007 InputFile IF = getInputFile(MF, I+1, Complain);
9008 Visitor(IF, IsSystem);
9009 }
9010}
9011
Richard Smithf3f84612017-06-29 02:19:42 +00009012void ASTReader::visitTopLevelModuleMaps(
9013 serialization::ModuleFile &MF,
9014 llvm::function_ref<void(const FileEntry *FE)> Visitor) {
9015 unsigned NumInputs = MF.InputFilesLoaded.size();
9016 for (unsigned I = 0; I < NumInputs; ++I) {
9017 InputFileInfo IFI = readInputFileInfo(MF, I + 1);
9018 if (IFI.TopLevelModuleMap)
9019 // FIXME: This unnecessarily re-reads the InputFileInfo.
9020 if (auto *FE = getInputFile(MF, I + 1).getFile())
9021 Visitor(FE);
9022 }
9023}
9024
Richard Smithcd45dbc2014-04-19 03:48:30 +00009025std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
9026 // If we know the owning module, use it.
Richard Smith42413142015-05-15 20:05:43 +00009027 if (Module *M = D->getImportedOwningModule())
Richard Smithcd45dbc2014-04-19 03:48:30 +00009028 return M->getFullModuleName();
9029
9030 // Otherwise, use the name of the top-level module the decl is within.
9031 if (ModuleFile *M = getOwningModuleFile(D))
9032 return M->ModuleName;
9033
9034 // Not from a module.
9035 return "";
9036}
9037
Guy Benyei11169dd2012-12-18 14:30:41 +00009038void ASTReader::finishPendingActions() {
Richard Smith851072e2014-05-19 20:59:20 +00009039 while (!PendingIdentifierInfos.empty() ||
9040 !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
Richard Smith2b9e3e32013-10-18 06:05:18 +00009041 !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
Richard Smitha0ce9c42014-07-29 23:23:27 +00009042 !PendingUpdateRecords.empty()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009043 // If any identifiers with corresponding top-level declarations have
9044 // been loaded, load those declarations now.
Craig Topper79be4cd2013-07-05 04:33:53 +00009045 typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
9046 TopLevelDeclsMap;
9047 TopLevelDeclsMap TopLevelDecls;
9048
Guy Benyei11169dd2012-12-18 14:30:41 +00009049 while (!PendingIdentifierInfos.empty()) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009050 IdentifierInfo *II = PendingIdentifierInfos.back().first;
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009051 SmallVector<uint32_t, 4> DeclIDs =
9052 std::move(PendingIdentifierInfos.back().second);
Douglas Gregorcb15f082013-02-19 18:26:28 +00009053 PendingIdentifierInfos.pop_back();
Douglas Gregor6168bd22013-02-18 15:53:43 +00009054
9055 SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
Guy Benyei11169dd2012-12-18 14:30:41 +00009056 }
Richard Smithf0ae3c2d2014-03-28 17:31:23 +00009057
Richard Smith851072e2014-05-19 20:59:20 +00009058 // For each decl chain that we wanted to complete while deserializing, mark
9059 // it as "still needs to be completed".
9060 for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
9061 markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
9062 }
9063 PendingIncompleteDeclChains.clear();
9064
Guy Benyei11169dd2012-12-18 14:30:41 +00009065 // Load pending declaration chains.
Richard Smithd8a83712015-08-22 01:47:18 +00009066 for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
Richard Smithd61d4ac2015-08-22 20:13:39 +00009067 loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
Guy Benyei11169dd2012-12-18 14:30:41 +00009068 PendingDeclChains.clear();
9069
Douglas Gregor6168bd22013-02-18 15:53:43 +00009070 // Make the most recent of the top-level declarations visible.
Craig Topper79be4cd2013-07-05 04:33:53 +00009071 for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
9072 TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
Douglas Gregor6168bd22013-02-18 15:53:43 +00009073 IdentifierInfo *II = TLD->first;
9074 for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +00009075 pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
Douglas Gregor6168bd22013-02-18 15:53:43 +00009076 }
9077 }
9078
Guy Benyei11169dd2012-12-18 14:30:41 +00009079 // Load any pending macro definitions.
9080 for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009081 IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
9082 SmallVector<PendingMacroInfo, 2> GlobalIDs;
9083 GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
9084 // Initialize the macro history from chained-PCHs ahead of module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009085 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidis719736c2013-01-19 03:14:56 +00009086 ++IDIdx) {
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009087 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009088 if (!Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009089 resolvePendingMacro(II, Info);
9090 }
9091 // Handle module imports.
Richard Smith49f906a2014-03-01 00:08:04 +00009092 for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009093 ++IDIdx) {
9094 const PendingMacroInfo &Info = GlobalIDs[IDIdx];
Manman Ren11f2a472016-08-18 17:42:15 +00009095 if (Info.M->isModule())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +00009096 resolvePendingMacro(II, Info);
Guy Benyei11169dd2012-12-18 14:30:41 +00009097 }
9098 }
9099 PendingMacroIDs.clear();
Argyrios Kyrtzidis83a6e3b2013-02-16 00:48:59 +00009100
9101 // Wire up the DeclContexts for Decls that we delayed setting until
9102 // recursive loading is completed.
9103 while (!PendingDeclContextInfos.empty()) {
9104 PendingDeclContextInfo Info = PendingDeclContextInfos.front();
9105 PendingDeclContextInfos.pop_front();
9106 DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
9107 DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
9108 Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
9109 }
Richard Smith2b9e3e32013-10-18 06:05:18 +00009110
Richard Smithd1c46742014-04-30 02:24:17 +00009111 // Perform any pending declaration updates.
Richard Smithd6db68c2014-08-07 20:58:41 +00009112 while (!PendingUpdateRecords.empty()) {
Richard Smithd1c46742014-04-30 02:24:17 +00009113 auto Update = PendingUpdateRecords.pop_back_val();
9114 ReadingKindTracker ReadingKind(Read_Decl, *this);
Vassil Vassilev74c3e8c2017-05-19 16:46:06 +00009115 loadDeclUpdateRecords(Update);
Richard Smithd1c46742014-04-30 02:24:17 +00009116 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009117 }
Richard Smith8a639892015-01-24 01:07:20 +00009118
9119 // At this point, all update records for loaded decls are in place, so any
9120 // fake class definitions should have become real.
9121 assert(PendingFakeDefinitionData.empty() &&
9122 "faked up a class definition but never saw the real one");
9123
Guy Benyei11169dd2012-12-18 14:30:41 +00009124 // If we deserialized any C++ or Objective-C class definitions, any
9125 // Objective-C protocol definitions, or any redeclarable templates, make sure
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009126 // that all redeclarations point to the definitions. Note that this can only
Guy Benyei11169dd2012-12-18 14:30:41 +00009127 // happen now, after the redeclaration chains have been fully wired.
Craig Topperc6914d02014-08-25 04:15:02 +00009128 for (Decl *D : PendingDefinitions) {
9129 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
Richard Smith5b21db82014-04-23 18:20:42 +00009130 if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009131 // Make sure that the TagType points at the definition.
9132 const_cast<TagType*>(TagT)->decl = TD;
9133 }
Richard Smith8ce51082015-03-11 01:44:51 +00009134
Craig Topperc6914d02014-08-25 04:15:02 +00009135 if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009136 for (auto *R = getMostRecentExistingDecl(RD); R;
9137 R = R->getPreviousDecl()) {
9138 assert((R == D) ==
9139 cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
Richard Smith2c381642014-08-27 23:11:59 +00009140 "declaration thinks it's the definition but it isn't");
Aaron Ballman86c93902014-03-06 23:45:36 +00009141 cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
Richard Smith2c381642014-08-27 23:11:59 +00009142 }
Guy Benyei11169dd2012-12-18 14:30:41 +00009143 }
9144
9145 continue;
9146 }
Richard Smith8ce51082015-03-11 01:44:51 +00009147
Craig Topperc6914d02014-08-25 04:15:02 +00009148 if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00009149 // Make sure that the ObjCInterfaceType points at the definition.
9150 const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
9151 ->Decl = ID;
Richard Smith8ce51082015-03-11 01:44:51 +00009152
9153 for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
9154 cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
9155
Guy Benyei11169dd2012-12-18 14:30:41 +00009156 continue;
9157 }
Richard Smith8ce51082015-03-11 01:44:51 +00009158
Craig Topperc6914d02014-08-25 04:15:02 +00009159 if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
Richard Smith8ce51082015-03-11 01:44:51 +00009160 for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
9161 cast<ObjCProtocolDecl>(R)->Data = PD->Data;
9162
Guy Benyei11169dd2012-12-18 14:30:41 +00009163 continue;
9164 }
Richard Smith8ce51082015-03-11 01:44:51 +00009165
Craig Topperc6914d02014-08-25 04:15:02 +00009166 auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
Richard Smith8ce51082015-03-11 01:44:51 +00009167 for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
9168 cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
Guy Benyei11169dd2012-12-18 14:30:41 +00009169 }
9170 PendingDefinitions.clear();
9171
Richard Smith42413142015-05-15 20:05:43 +00009172 // Do some cleanup.
9173 for (auto *ND : PendingMergedDefinitionsToDeduplicate)
9174 getContext().deduplicateMergedDefinitonsFor(ND);
9175 PendingMergedDefinitionsToDeduplicate.clear();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009176}
9177
9178void ASTReader::diagnoseOdrViolations() {
Richard Smithbb853c72014-08-13 01:23:33 +00009179 if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
9180 return;
9181
Richard Smitha0ce9c42014-07-29 23:23:27 +00009182 // Trigger the import of the full definition of each class that had any
9183 // odr-merging problems, so we can produce better diagnostics for them.
Richard Smithbb853c72014-08-13 01:23:33 +00009184 // These updates may in turn find and diagnose some ODR failures, so take
9185 // ownership of the set first.
9186 auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
9187 PendingOdrMergeFailures.clear();
9188 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009189 Merge.first->buildLookup();
9190 Merge.first->decls_begin();
9191 Merge.first->bases_begin();
9192 Merge.first->vbases_begin();
Richard Trieue13eabe2017-09-30 02:19:17 +00009193 for (auto &RecordPair : Merge.second) {
9194 auto *RD = RecordPair.first;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009195 RD->decls_begin();
9196 RD->bases_begin();
9197 RD->vbases_begin();
9198 }
9199 }
9200
9201 // For each declaration from a merged context, check that the canonical
9202 // definition of that context also contains a declaration of the same
9203 // entity.
9204 //
9205 // Caution: this loop does things that might invalidate iterators into
9206 // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
9207 while (!PendingOdrMergeChecks.empty()) {
9208 NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
9209
9210 // FIXME: Skip over implicit declarations for now. This matters for things
9211 // like implicitly-declared special member functions. This isn't entirely
9212 // correct; we can end up with multiple unmerged declarations of the same
9213 // implicit entity.
9214 if (D->isImplicit())
9215 continue;
9216
9217 DeclContext *CanonDef = D->getDeclContext();
Richard Smitha0ce9c42014-07-29 23:23:27 +00009218
9219 bool Found = false;
9220 const Decl *DCanon = D->getCanonicalDecl();
9221
Richard Smith01bdb7a2014-08-28 05:44:07 +00009222 for (auto RI : D->redecls()) {
9223 if (RI->getLexicalDeclContext() == CanonDef) {
9224 Found = true;
9225 break;
9226 }
9227 }
9228 if (Found)
9229 continue;
9230
Richard Smith0f4e2c42015-08-06 04:23:48 +00009231 // Quick check failed, time to do the slow thing. Note, we can't just
9232 // look up the name of D in CanonDef here, because the member that is
9233 // in CanonDef might not be found by name lookup (it might have been
9234 // replaced by a more recent declaration in the lookup table), and we
9235 // can't necessarily find it in the redeclaration chain because it might
9236 // be merely mergeable, not redeclarable.
Richard Smitha0ce9c42014-07-29 23:23:27 +00009237 llvm::SmallVector<const NamedDecl*, 4> Candidates;
Richard Smith0f4e2c42015-08-06 04:23:48 +00009238 for (auto *CanonMember : CanonDef->decls()) {
9239 if (CanonMember->getCanonicalDecl() == DCanon) {
9240 // This can happen if the declaration is merely mergeable and not
9241 // actually redeclarable (we looked for redeclarations earlier).
9242 //
9243 // FIXME: We should be able to detect this more efficiently, without
9244 // pulling in all of the members of CanonDef.
9245 Found = true;
9246 break;
Richard Smitha0ce9c42014-07-29 23:23:27 +00009247 }
Richard Smith0f4e2c42015-08-06 04:23:48 +00009248 if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
9249 if (ND->getDeclName() == D->getDeclName())
9250 Candidates.push_back(ND);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009251 }
9252
9253 if (!Found) {
Richard Smithd08aeb62014-08-28 01:33:39 +00009254 // The AST doesn't like TagDecls becoming invalid after they've been
9255 // completed. We only really need to mark FieldDecls as invalid here.
9256 if (!isa<TagDecl>(D))
9257 D->setInvalidDecl();
David L. Jonesc4808b9e2016-12-15 20:53:26 +00009258
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009259 // Ensure we don't accidentally recursively enter deserialization while
9260 // we're producing our diagnostic.
9261 Deserializing RecursionGuard(this);
Richard Smitha0ce9c42014-07-29 23:23:27 +00009262
9263 std::string CanonDefModule =
9264 getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
9265 Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
9266 << D << getOwningModuleNameForDiagnostic(D)
9267 << CanonDef << CanonDefModule.empty() << CanonDefModule;
9268
9269 if (Candidates.empty())
9270 Diag(cast<Decl>(CanonDef)->getLocation(),
9271 diag::note_module_odr_violation_no_possible_decls) << D;
9272 else {
9273 for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
9274 Diag(Candidates[I]->getLocation(),
9275 diag::note_module_odr_violation_possible_decl)
9276 << Candidates[I];
9277 }
9278
9279 DiagnosedOdrMergeFailures.insert(CanonDef);
9280 }
9281 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009282
Richard Smith4ab3dbd2015-02-13 22:43:51 +00009283 if (OdrMergeFailures.empty())
9284 return;
9285
9286 // Ensure we don't accidentally recursively enter deserialization while
9287 // we're producing our diagnostics.
9288 Deserializing RecursionGuard(this);
9289
Richard Smithcd45dbc2014-04-19 03:48:30 +00009290 // Issue any pending ODR-failure diagnostics.
Richard Smithbb853c72014-08-13 01:23:33 +00009291 for (auto &Merge : OdrMergeFailures) {
Richard Smitha0ce9c42014-07-29 23:23:27 +00009292 // If we've already pointed out a specific problem with this class, don't
9293 // bother issuing a general "something's different" diagnostic.
David Blaikie82e95a32014-11-19 07:49:47 +00009294 if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
Richard Smithcd45dbc2014-04-19 03:48:30 +00009295 continue;
9296
9297 bool Diagnosed = false;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009298 CXXRecordDecl *FirstRecord = Merge.first;
9299 std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009300 for (auto &RecordPair : Merge.second) {
9301 CXXRecordDecl *SecondRecord = RecordPair.first;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009302 // Multiple different declarations got merged together; tell the user
9303 // where they came from.
Richard Trieue7f7ed22017-02-22 01:11:25 +00009304 if (FirstRecord == SecondRecord)
9305 continue;
9306
9307 std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
Richard Trieue13eabe2017-09-30 02:19:17 +00009308
9309 auto *FirstDD = FirstRecord->DefinitionData;
9310 auto *SecondDD = RecordPair.second;
9311
9312 assert(FirstDD && SecondDD && "Definitions without DefinitionData");
9313
9314 // Diagnostics from DefinitionData are emitted here.
9315 if (FirstDD != SecondDD) {
9316 enum ODRDefinitionDataDifference {
9317 NumBases,
9318 NumVBases,
9319 BaseType,
9320 BaseVirtual,
9321 BaseAccess,
9322 };
9323 auto ODRDiagError = [FirstRecord, &FirstModule,
9324 this](SourceLocation Loc, SourceRange Range,
9325 ODRDefinitionDataDifference DiffType) {
9326 return Diag(Loc, diag::err_module_odr_violation_definition_data)
9327 << FirstRecord << FirstModule.empty() << FirstModule << Range
9328 << DiffType;
9329 };
9330 auto ODRDiagNote = [&SecondModule,
9331 this](SourceLocation Loc, SourceRange Range,
9332 ODRDefinitionDataDifference DiffType) {
9333 return Diag(Loc, diag::note_module_odr_violation_definition_data)
9334 << SecondModule << Range << DiffType;
9335 };
9336
9337 ODRHash Hash;
9338 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9339 Hash.clear();
9340 Hash.AddQualType(Ty);
9341 return Hash.CalculateHash();
9342 };
9343
9344 unsigned FirstNumBases = FirstDD->NumBases;
9345 unsigned FirstNumVBases = FirstDD->NumVBases;
9346 unsigned SecondNumBases = SecondDD->NumBases;
9347 unsigned SecondNumVBases = SecondDD->NumVBases;
9348
9349 auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
9350 unsigned NumBases = DD->NumBases;
9351 if (NumBases == 0) return SourceRange();
9352 auto bases = DD->bases();
9353 return SourceRange(bases[0].getLocStart(),
9354 bases[NumBases - 1].getLocEnd());
9355 };
9356
9357 if (FirstNumBases != SecondNumBases) {
9358 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9359 NumBases)
9360 << FirstNumBases;
9361 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9362 NumBases)
9363 << SecondNumBases;
9364 Diagnosed = true;
9365 break;
9366 }
9367
9368 if (FirstNumVBases != SecondNumVBases) {
9369 ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
9370 NumVBases)
9371 << FirstNumVBases;
9372 ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
9373 NumVBases)
9374 << SecondNumVBases;
9375 Diagnosed = true;
9376 break;
9377 }
9378
9379 auto FirstBases = FirstDD->bases();
9380 auto SecondBases = SecondDD->bases();
9381 unsigned i = 0;
9382 for (i = 0; i < FirstNumBases; ++i) {
9383 auto FirstBase = FirstBases[i];
9384 auto SecondBase = SecondBases[i];
9385 if (ComputeQualTypeODRHash(FirstBase.getType()) !=
9386 ComputeQualTypeODRHash(SecondBase.getType())) {
9387 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9388 BaseType)
9389 << (i + 1) << FirstBase.getType();
9390 ODRDiagNote(SecondRecord->getLocation(),
9391 SecondBase.getSourceRange(), BaseType)
9392 << (i + 1) << SecondBase.getType();
9393 break;
9394 }
9395
9396 if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
9397 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9398 BaseVirtual)
9399 << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
9400 ODRDiagNote(SecondRecord->getLocation(),
9401 SecondBase.getSourceRange(), BaseVirtual)
9402 << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
9403 break;
9404 }
9405
9406 if (FirstBase.getAccessSpecifierAsWritten() !=
9407 SecondBase.getAccessSpecifierAsWritten()) {
9408 ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
9409 BaseAccess)
9410 << (i + 1) << FirstBase.getType()
9411 << (int)FirstBase.getAccessSpecifierAsWritten();
9412 ODRDiagNote(SecondRecord->getLocation(),
9413 SecondBase.getSourceRange(), BaseAccess)
9414 << (i + 1) << SecondBase.getType()
9415 << (int)SecondBase.getAccessSpecifierAsWritten();
9416 break;
9417 }
9418 }
9419
9420 if (i != FirstNumBases) {
9421 Diagnosed = true;
9422 break;
9423 }
9424 }
9425
Richard Trieue7f7ed22017-02-22 01:11:25 +00009426 using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
Richard Trieu498117b2017-08-23 02:43:59 +00009427
9428 const ClassTemplateDecl *FirstTemplate =
9429 FirstRecord->getDescribedClassTemplate();
9430 const ClassTemplateDecl *SecondTemplate =
9431 SecondRecord->getDescribedClassTemplate();
9432
9433 assert(!FirstTemplate == !SecondTemplate &&
9434 "Both pointers should be null or non-null");
9435
9436 enum ODRTemplateDifference {
9437 ParamEmptyName,
9438 ParamName,
9439 ParamSingleDefaultArgument,
9440 ParamDifferentDefaultArgument,
9441 };
9442
9443 if (FirstTemplate && SecondTemplate) {
9444 DeclHashes FirstTemplateHashes;
9445 DeclHashes SecondTemplateHashes;
9446 ODRHash Hash;
9447
9448 auto PopulateTemplateParameterHashs =
9449 [&Hash](DeclHashes &Hashes, const ClassTemplateDecl *TD) {
9450 for (auto *D : TD->getTemplateParameters()->asArray()) {
9451 Hash.clear();
9452 Hash.AddSubDecl(D);
9453 Hashes.emplace_back(D, Hash.CalculateHash());
9454 }
9455 };
9456
9457 PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
9458 PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
9459
9460 assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
9461 "Number of template parameters should be equal.");
9462
9463 auto FirstIt = FirstTemplateHashes.begin();
9464 auto FirstEnd = FirstTemplateHashes.end();
9465 auto SecondIt = SecondTemplateHashes.begin();
9466 for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
9467 if (FirstIt->second == SecondIt->second)
9468 continue;
9469
9470 auto ODRDiagError = [FirstRecord, &FirstModule,
9471 this](SourceLocation Loc, SourceRange Range,
9472 ODRTemplateDifference DiffType) {
9473 return Diag(Loc, diag::err_module_odr_violation_template_parameter)
9474 << FirstRecord << FirstModule.empty() << FirstModule << Range
9475 << DiffType;
9476 };
9477 auto ODRDiagNote = [&SecondModule,
9478 this](SourceLocation Loc, SourceRange Range,
9479 ODRTemplateDifference DiffType) {
9480 return Diag(Loc, diag::note_module_odr_violation_template_parameter)
9481 << SecondModule << Range << DiffType;
9482 };
9483
9484 const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
9485 const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
9486
9487 assert(FirstDecl->getKind() == SecondDecl->getKind() &&
9488 "Parameter Decl's should be the same kind.");
9489
9490 DeclarationName FirstName = FirstDecl->getDeclName();
9491 DeclarationName SecondName = SecondDecl->getDeclName();
9492
9493 if (FirstName != SecondName) {
9494 const bool FirstNameEmpty =
9495 FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
9496 const bool SecondNameEmpty =
9497 SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
9498 assert((!FirstNameEmpty || !SecondNameEmpty) &&
9499 "Both template parameters cannot be unnamed.");
9500 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9501 FirstNameEmpty ? ParamEmptyName : ParamName)
9502 << FirstName;
9503 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9504 SecondNameEmpty ? ParamEmptyName : ParamName)
9505 << SecondName;
9506 break;
9507 }
9508
9509 switch (FirstDecl->getKind()) {
9510 default:
9511 llvm_unreachable("Invalid template parameter type.");
9512 case Decl::TemplateTypeParm: {
9513 const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
9514 const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
9515 const bool HasFirstDefaultArgument =
9516 FirstParam->hasDefaultArgument() &&
9517 !FirstParam->defaultArgumentWasInherited();
9518 const bool HasSecondDefaultArgument =
9519 SecondParam->hasDefaultArgument() &&
9520 !SecondParam->defaultArgumentWasInherited();
9521
9522 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9523 ODRDiagError(FirstDecl->getLocation(),
9524 FirstDecl->getSourceRange(),
9525 ParamSingleDefaultArgument)
9526 << HasFirstDefaultArgument;
9527 ODRDiagNote(SecondDecl->getLocation(),
9528 SecondDecl->getSourceRange(),
9529 ParamSingleDefaultArgument)
9530 << HasSecondDefaultArgument;
9531 break;
9532 }
9533
9534 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9535 "Expecting default arguments.");
9536
9537 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9538 ParamDifferentDefaultArgument);
9539 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9540 ParamDifferentDefaultArgument);
9541
9542 break;
9543 }
9544 case Decl::NonTypeTemplateParm: {
9545 const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
9546 const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
9547 const bool HasFirstDefaultArgument =
9548 FirstParam->hasDefaultArgument() &&
9549 !FirstParam->defaultArgumentWasInherited();
9550 const bool HasSecondDefaultArgument =
9551 SecondParam->hasDefaultArgument() &&
9552 !SecondParam->defaultArgumentWasInherited();
9553
9554 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9555 ODRDiagError(FirstDecl->getLocation(),
9556 FirstDecl->getSourceRange(),
9557 ParamSingleDefaultArgument)
9558 << HasFirstDefaultArgument;
9559 ODRDiagNote(SecondDecl->getLocation(),
9560 SecondDecl->getSourceRange(),
9561 ParamSingleDefaultArgument)
9562 << HasSecondDefaultArgument;
9563 break;
9564 }
9565
9566 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9567 "Expecting default arguments.");
9568
9569 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9570 ParamDifferentDefaultArgument);
9571 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9572 ParamDifferentDefaultArgument);
9573
9574 break;
9575 }
9576 case Decl::TemplateTemplateParm: {
9577 const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
9578 const auto *SecondParam =
9579 cast<TemplateTemplateParmDecl>(SecondDecl);
9580 const bool HasFirstDefaultArgument =
9581 FirstParam->hasDefaultArgument() &&
9582 !FirstParam->defaultArgumentWasInherited();
9583 const bool HasSecondDefaultArgument =
9584 SecondParam->hasDefaultArgument() &&
9585 !SecondParam->defaultArgumentWasInherited();
9586
9587 if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
9588 ODRDiagError(FirstDecl->getLocation(),
9589 FirstDecl->getSourceRange(),
9590 ParamSingleDefaultArgument)
9591 << HasFirstDefaultArgument;
9592 ODRDiagNote(SecondDecl->getLocation(),
9593 SecondDecl->getSourceRange(),
9594 ParamSingleDefaultArgument)
9595 << HasSecondDefaultArgument;
9596 break;
9597 }
9598
9599 assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
9600 "Expecting default arguments.");
9601
9602 ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
9603 ParamDifferentDefaultArgument);
9604 ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
9605 ParamDifferentDefaultArgument);
9606
9607 break;
9608 }
9609 }
9610
9611 break;
9612 }
9613
9614 if (FirstIt != FirstEnd) {
9615 Diagnosed = true;
9616 break;
9617 }
9618 }
9619
Richard Trieue7f7ed22017-02-22 01:11:25 +00009620 DeclHashes FirstHashes;
9621 DeclHashes SecondHashes;
9622 ODRHash Hash;
9623
9624 auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
9625 CXXRecordDecl *Record) {
9626 for (auto *D : Record->decls()) {
9627 // Due to decl merging, the first CXXRecordDecl is the parent of
9628 // Decls in both records.
9629 if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
9630 continue;
9631 Hash.clear();
9632 Hash.AddSubDecl(D);
9633 Hashes.emplace_back(D, Hash.CalculateHash());
9634 }
9635 };
9636 PopulateHashes(FirstHashes, FirstRecord);
9637 PopulateHashes(SecondHashes, SecondRecord);
9638
9639 // Used with err_module_odr_violation_mismatch_decl and
9640 // note_module_odr_violation_mismatch_decl
Richard Trieu11d566a2017-06-12 21:58:22 +00009641 // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
Richard Trieue7f7ed22017-02-22 01:11:25 +00009642 enum {
9643 EndOfClass,
9644 PublicSpecifer,
9645 PrivateSpecifer,
9646 ProtectedSpecifer,
Richard Trieu639d7b62017-02-22 22:22:42 +00009647 StaticAssert,
Richard Trieud0786092017-02-23 00:23:01 +00009648 Field,
Richard Trieu48143742017-02-28 21:24:38 +00009649 CXXMethod,
Richard Trieu11d566a2017-06-12 21:58:22 +00009650 TypeAlias,
9651 TypeDef,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009652 Var,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009653 Friend,
Richard Trieue7f7ed22017-02-22 01:11:25 +00009654 Other
9655 } FirstDiffType = Other,
9656 SecondDiffType = Other;
9657
9658 auto DifferenceSelector = [](Decl *D) {
9659 assert(D && "valid Decl required");
9660 switch (D->getKind()) {
9661 default:
9662 return Other;
9663 case Decl::AccessSpec:
9664 switch (D->getAccess()) {
9665 case AS_public:
9666 return PublicSpecifer;
9667 case AS_private:
9668 return PrivateSpecifer;
9669 case AS_protected:
9670 return ProtectedSpecifer;
9671 case AS_none:
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009672 break;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009673 }
Simon Pilgrimeeb1b302017-02-22 13:21:24 +00009674 llvm_unreachable("Invalid access specifier");
Richard Trieu639d7b62017-02-22 22:22:42 +00009675 case Decl::StaticAssert:
9676 return StaticAssert;
Richard Trieud0786092017-02-23 00:23:01 +00009677 case Decl::Field:
9678 return Field;
Richard Trieu48143742017-02-28 21:24:38 +00009679 case Decl::CXXMethod:
Richard Trieu1c71d512017-07-15 02:55:13 +00009680 case Decl::CXXConstructor:
9681 case Decl::CXXDestructor:
Richard Trieu48143742017-02-28 21:24:38 +00009682 return CXXMethod;
Richard Trieu11d566a2017-06-12 21:58:22 +00009683 case Decl::TypeAlias:
9684 return TypeAlias;
9685 case Decl::Typedef:
9686 return TypeDef;
Richard Trieu6e13ff32017-06-16 02:44:29 +00009687 case Decl::Var:
9688 return Var;
Richard Trieuac6a1b62017-07-08 02:04:42 +00009689 case Decl::Friend:
9690 return Friend;
Richard Trieue7f7ed22017-02-22 01:11:25 +00009691 }
9692 };
9693
9694 Decl *FirstDecl = nullptr;
9695 Decl *SecondDecl = nullptr;
9696 auto FirstIt = FirstHashes.begin();
9697 auto SecondIt = SecondHashes.begin();
9698
9699 // If there is a diagnoseable difference, FirstDiffType and
9700 // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
9701 // filled in if not EndOfClass.
9702 while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
Benjamin Kramer6f224d22017-02-22 10:19:45 +00009703 if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
9704 FirstIt->second == SecondIt->second) {
Richard Trieue7f7ed22017-02-22 01:11:25 +00009705 ++FirstIt;
9706 ++SecondIt;
9707 continue;
Richard Trieudc4cb022017-02-17 07:19:24 +00009708 }
Richard Smithcd45dbc2014-04-19 03:48:30 +00009709
Richard Trieue7f7ed22017-02-22 01:11:25 +00009710 FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
9711 SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
9712
9713 FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
9714 SecondDiffType =
9715 SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
9716
9717 break;
Richard Smithcd45dbc2014-04-19 03:48:30 +00009718 }
Richard Trieue7f7ed22017-02-22 01:11:25 +00009719
9720 if (FirstDiffType == Other || SecondDiffType == Other) {
9721 // Reaching this point means an unexpected Decl was encountered
9722 // or no difference was detected. This causes a generic error
9723 // message to be emitted.
9724 Diag(FirstRecord->getLocation(),
9725 diag::err_module_odr_violation_different_definitions)
9726 << FirstRecord << FirstModule.empty() << FirstModule;
9727
Richard Trieuca48d362017-06-21 01:43:13 +00009728 if (FirstDecl) {
9729 Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
9730 << FirstRecord << FirstDecl->getSourceRange();
9731 }
9732
Richard Trieue7f7ed22017-02-22 01:11:25 +00009733 Diag(SecondRecord->getLocation(),
9734 diag::note_module_odr_violation_different_definitions)
9735 << SecondModule;
Richard Trieuca48d362017-06-21 01:43:13 +00009736
9737 if (SecondDecl) {
9738 Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
9739 << SecondDecl->getSourceRange();
9740 }
9741
Richard Trieue7f7ed22017-02-22 01:11:25 +00009742 Diagnosed = true;
9743 break;
9744 }
9745
9746 if (FirstDiffType != SecondDiffType) {
9747 SourceLocation FirstLoc;
9748 SourceRange FirstRange;
9749 if (FirstDiffType == EndOfClass) {
9750 FirstLoc = FirstRecord->getBraceRange().getEnd();
9751 } else {
9752 FirstLoc = FirstIt->first->getLocation();
9753 FirstRange = FirstIt->first->getSourceRange();
9754 }
9755 Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
9756 << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
9757 << FirstDiffType;
9758
9759 SourceLocation SecondLoc;
9760 SourceRange SecondRange;
9761 if (SecondDiffType == EndOfClass) {
9762 SecondLoc = SecondRecord->getBraceRange().getEnd();
9763 } else {
9764 SecondLoc = SecondDecl->getLocation();
9765 SecondRange = SecondDecl->getSourceRange();
9766 }
9767 Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
9768 << SecondModule << SecondRange << SecondDiffType;
9769 Diagnosed = true;
9770 break;
9771 }
9772
Richard Trieu639d7b62017-02-22 22:22:42 +00009773 assert(FirstDiffType == SecondDiffType);
9774
9775 // Used with err_module_odr_violation_mismatch_decl_diff and
9776 // note_module_odr_violation_mismatch_decl_diff
9777 enum ODRDeclDifference{
9778 StaticAssertCondition,
9779 StaticAssertMessage,
9780 StaticAssertOnlyMessage,
Richard Trieud0786092017-02-23 00:23:01 +00009781 FieldName,
Richard Trieu8459ddf2017-02-24 02:59:12 +00009782 FieldTypeName,
Richard Trieu93772fc2017-02-24 20:59:28 +00009783 FieldSingleBitField,
Richard Trieu8d543e22017-02-24 23:35:37 +00009784 FieldDifferentWidthBitField,
9785 FieldSingleMutable,
9786 FieldSingleInitializer,
9787 FieldDifferentInitializers,
Richard Trieu48143742017-02-28 21:24:38 +00009788 MethodName,
Richard Trieu583e2c12017-03-04 00:08:58 +00009789 MethodDeleted,
9790 MethodVirtual,
9791 MethodStatic,
9792 MethodVolatile,
9793 MethodConst,
9794 MethodInline,
Richard Trieu02552272017-05-02 23:58:52 +00009795 MethodNumberParameters,
9796 MethodParameterType,
9797 MethodParameterName,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009798 MethodParameterSingleDefaultArgument,
9799 MethodParameterDifferentDefaultArgument,
Richard Trieu11d566a2017-06-12 21:58:22 +00009800 TypedefName,
9801 TypedefType,
Richard Trieu6e13ff32017-06-16 02:44:29 +00009802 VarName,
9803 VarType,
9804 VarSingleInitializer,
9805 VarDifferentInitializer,
9806 VarConstexpr,
Richard Trieuac6a1b62017-07-08 02:04:42 +00009807 FriendTypeFunction,
9808 FriendType,
9809 FriendFunction,
Richard Trieu639d7b62017-02-22 22:22:42 +00009810 };
9811
9812 // These lambdas have the common portions of the ODR diagnostics. This
9813 // has the same return as Diag(), so addition parameters can be passed
9814 // in with operator<<
9815 auto ODRDiagError = [FirstRecord, &FirstModule, this](
9816 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9817 return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
9818 << FirstRecord << FirstModule.empty() << FirstModule << Range
9819 << DiffType;
9820 };
9821 auto ODRDiagNote = [&SecondModule, this](
9822 SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
9823 return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
9824 << SecondModule << Range << DiffType;
9825 };
9826
9827 auto ComputeODRHash = [&Hash](const Stmt* S) {
9828 assert(S);
9829 Hash.clear();
9830 Hash.AddStmt(S);
9831 return Hash.CalculateHash();
9832 };
9833
Richard Trieu02552272017-05-02 23:58:52 +00009834 auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
9835 Hash.clear();
9836 Hash.AddQualType(Ty);
9837 return Hash.CalculateHash();
9838 };
9839
Richard Trieu639d7b62017-02-22 22:22:42 +00009840 switch (FirstDiffType) {
9841 case Other:
9842 case EndOfClass:
9843 case PublicSpecifer:
9844 case PrivateSpecifer:
9845 case ProtectedSpecifer:
9846 llvm_unreachable("Invalid diff type");
9847
9848 case StaticAssert: {
9849 StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
9850 StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
9851
9852 Expr *FirstExpr = FirstSA->getAssertExpr();
9853 Expr *SecondExpr = SecondSA->getAssertExpr();
9854 unsigned FirstODRHash = ComputeODRHash(FirstExpr);
9855 unsigned SecondODRHash = ComputeODRHash(SecondExpr);
9856 if (FirstODRHash != SecondODRHash) {
9857 ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
9858 StaticAssertCondition);
9859 ODRDiagNote(SecondExpr->getLocStart(),
9860 SecondExpr->getSourceRange(), StaticAssertCondition);
9861 Diagnosed = true;
9862 break;
9863 }
9864
9865 StringLiteral *FirstStr = FirstSA->getMessage();
9866 StringLiteral *SecondStr = SecondSA->getMessage();
9867 assert((FirstStr || SecondStr) && "Both messages cannot be empty");
9868 if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
9869 SourceLocation FirstLoc, SecondLoc;
9870 SourceRange FirstRange, SecondRange;
9871 if (FirstStr) {
9872 FirstLoc = FirstStr->getLocStart();
9873 FirstRange = FirstStr->getSourceRange();
9874 } else {
9875 FirstLoc = FirstSA->getLocStart();
9876 FirstRange = FirstSA->getSourceRange();
9877 }
9878 if (SecondStr) {
9879 SecondLoc = SecondStr->getLocStart();
9880 SecondRange = SecondStr->getSourceRange();
9881 } else {
9882 SecondLoc = SecondSA->getLocStart();
9883 SecondRange = SecondSA->getSourceRange();
9884 }
9885 ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
9886 << (FirstStr == nullptr);
9887 ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
9888 << (SecondStr == nullptr);
9889 Diagnosed = true;
9890 break;
9891 }
9892
9893 if (FirstStr && SecondStr &&
9894 FirstStr->getString() != SecondStr->getString()) {
9895 ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
9896 StaticAssertMessage);
9897 ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
9898 StaticAssertMessage);
9899 Diagnosed = true;
9900 break;
9901 }
9902 break;
9903 }
Richard Trieud0786092017-02-23 00:23:01 +00009904 case Field: {
9905 FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
9906 FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
9907 IdentifierInfo *FirstII = FirstField->getIdentifier();
9908 IdentifierInfo *SecondII = SecondField->getIdentifier();
9909 if (FirstII->getName() != SecondII->getName()) {
9910 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9911 FieldName)
9912 << FirstII;
9913 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9914 FieldName)
9915 << SecondII;
9916
9917 Diagnosed = true;
9918 break;
9919 }
Richard Trieu8459ddf2017-02-24 02:59:12 +00009920
Richard Smithdbafb6c2017-06-29 23:23:46 +00009921 assert(getContext().hasSameType(FirstField->getType(),
9922 SecondField->getType()));
Richard Trieu8459ddf2017-02-24 02:59:12 +00009923
9924 QualType FirstType = FirstField->getType();
9925 QualType SecondType = SecondField->getType();
Richard Trieuce81b192017-05-17 03:23:35 +00009926 if (ComputeQualTypeODRHash(FirstType) !=
9927 ComputeQualTypeODRHash(SecondType)) {
Richard Trieu8459ddf2017-02-24 02:59:12 +00009928 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9929 FieldTypeName)
9930 << FirstII << FirstType;
9931 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9932 FieldTypeName)
9933 << SecondII << SecondType;
9934
9935 Diagnosed = true;
9936 break;
9937 }
9938
Richard Trieu93772fc2017-02-24 20:59:28 +00009939 const bool IsFirstBitField = FirstField->isBitField();
9940 const bool IsSecondBitField = SecondField->isBitField();
9941 if (IsFirstBitField != IsSecondBitField) {
9942 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9943 FieldSingleBitField)
9944 << FirstII << IsFirstBitField;
9945 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9946 FieldSingleBitField)
9947 << SecondII << IsSecondBitField;
9948 Diagnosed = true;
9949 break;
9950 }
9951
9952 if (IsFirstBitField && IsSecondBitField) {
9953 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9954 FieldDifferentWidthBitField)
9955 << FirstII << FirstField->getBitWidth()->getSourceRange();
9956 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9957 FieldDifferentWidthBitField)
9958 << SecondII << SecondField->getBitWidth()->getSourceRange();
9959 Diagnosed = true;
9960 break;
9961 }
9962
Richard Trieu8d543e22017-02-24 23:35:37 +00009963 const bool IsFirstMutable = FirstField->isMutable();
9964 const bool IsSecondMutable = SecondField->isMutable();
9965 if (IsFirstMutable != IsSecondMutable) {
9966 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9967 FieldSingleMutable)
9968 << FirstII << IsFirstMutable;
9969 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9970 FieldSingleMutable)
9971 << SecondII << IsSecondMutable;
9972 Diagnosed = true;
9973 break;
9974 }
9975
9976 const Expr *FirstInitializer = FirstField->getInClassInitializer();
9977 const Expr *SecondInitializer = SecondField->getInClassInitializer();
9978 if ((!FirstInitializer && SecondInitializer) ||
9979 (FirstInitializer && !SecondInitializer)) {
9980 ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
9981 FieldSingleInitializer)
9982 << FirstII << (FirstInitializer != nullptr);
9983 ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
9984 FieldSingleInitializer)
9985 << SecondII << (SecondInitializer != nullptr);
9986 Diagnosed = true;
9987 break;
9988 }
9989
9990 if (FirstInitializer && SecondInitializer) {
9991 unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
9992 unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
9993 if (FirstInitHash != SecondInitHash) {
9994 ODRDiagError(FirstField->getLocation(),
9995 FirstField->getSourceRange(),
9996 FieldDifferentInitializers)
9997 << FirstII << FirstInitializer->getSourceRange();
9998 ODRDiagNote(SecondField->getLocation(),
9999 SecondField->getSourceRange(),
10000 FieldDifferentInitializers)
10001 << SecondII << SecondInitializer->getSourceRange();
10002 Diagnosed = true;
10003 break;
10004 }
10005 }
10006
Richard Trieud0786092017-02-23 00:23:01 +000010007 break;
10008 }
Richard Trieu48143742017-02-28 21:24:38 +000010009 case CXXMethod: {
Richard Trieu1c71d512017-07-15 02:55:13 +000010010 enum {
10011 DiagMethod,
10012 DiagConstructor,
10013 DiagDestructor,
10014 } FirstMethodType,
10015 SecondMethodType;
10016 auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
10017 if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
10018 if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
10019 return DiagMethod;
10020 };
Richard Trieu48143742017-02-28 21:24:38 +000010021 const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
10022 const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
Richard Trieu1c71d512017-07-15 02:55:13 +000010023 FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
10024 SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
Richard Trieu583e2c12017-03-04 00:08:58 +000010025 auto FirstName = FirstMethod->getDeclName();
10026 auto SecondName = SecondMethod->getDeclName();
Richard Trieu1c71d512017-07-15 02:55:13 +000010027 if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
Richard Trieu48143742017-02-28 21:24:38 +000010028 ODRDiagError(FirstMethod->getLocation(),
10029 FirstMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010030 << FirstMethodType << FirstName;
Richard Trieu48143742017-02-28 21:24:38 +000010031 ODRDiagNote(SecondMethod->getLocation(),
10032 SecondMethod->getSourceRange(), MethodName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010033 << SecondMethodType << SecondName;
Richard Trieu48143742017-02-28 21:24:38 +000010034
10035 Diagnosed = true;
10036 break;
10037 }
10038
Richard Trieu583e2c12017-03-04 00:08:58 +000010039 const bool FirstDeleted = FirstMethod->isDeleted();
10040 const bool SecondDeleted = SecondMethod->isDeleted();
10041 if (FirstDeleted != SecondDeleted) {
10042 ODRDiagError(FirstMethod->getLocation(),
10043 FirstMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010044 << FirstMethodType << FirstName << FirstDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010045
10046 ODRDiagNote(SecondMethod->getLocation(),
10047 SecondMethod->getSourceRange(), MethodDeleted)
Richard Trieu1c71d512017-07-15 02:55:13 +000010048 << SecondMethodType << SecondName << SecondDeleted;
Richard Trieu583e2c12017-03-04 00:08:58 +000010049 Diagnosed = true;
10050 break;
10051 }
10052
10053 const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
10054 const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
10055 const bool FirstPure = FirstMethod->isPure();
10056 const bool SecondPure = SecondMethod->isPure();
10057 if ((FirstVirtual || SecondVirtual) &&
10058 (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
10059 ODRDiagError(FirstMethod->getLocation(),
10060 FirstMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010061 << FirstMethodType << FirstName << FirstPure << FirstVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010062 ODRDiagNote(SecondMethod->getLocation(),
10063 SecondMethod->getSourceRange(), MethodVirtual)
Richard Trieu1c71d512017-07-15 02:55:13 +000010064 << SecondMethodType << SecondName << SecondPure << SecondVirtual;
Richard Trieu583e2c12017-03-04 00:08:58 +000010065 Diagnosed = true;
10066 break;
10067 }
10068
10069 // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
10070 // FirstDecl is the canonical Decl of SecondDecl, so the storage
10071 // class needs to be checked instead.
10072 const auto FirstStorage = FirstMethod->getStorageClass();
10073 const auto SecondStorage = SecondMethod->getStorageClass();
10074 const bool FirstStatic = FirstStorage == SC_Static;
10075 const bool SecondStatic = SecondStorage == SC_Static;
10076 if (FirstStatic != SecondStatic) {
10077 ODRDiagError(FirstMethod->getLocation(),
10078 FirstMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010079 << FirstMethodType << FirstName << FirstStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010080 ODRDiagNote(SecondMethod->getLocation(),
10081 SecondMethod->getSourceRange(), MethodStatic)
Richard Trieu1c71d512017-07-15 02:55:13 +000010082 << SecondMethodType << SecondName << SecondStatic;
Richard Trieu583e2c12017-03-04 00:08:58 +000010083 Diagnosed = true;
10084 break;
10085 }
10086
10087 const bool FirstVolatile = FirstMethod->isVolatile();
10088 const bool SecondVolatile = SecondMethod->isVolatile();
10089 if (FirstVolatile != SecondVolatile) {
10090 ODRDiagError(FirstMethod->getLocation(),
10091 FirstMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010092 << FirstMethodType << FirstName << FirstVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010093 ODRDiagNote(SecondMethod->getLocation(),
10094 SecondMethod->getSourceRange(), MethodVolatile)
Richard Trieu1c71d512017-07-15 02:55:13 +000010095 << SecondMethodType << SecondName << SecondVolatile;
Richard Trieu583e2c12017-03-04 00:08:58 +000010096 Diagnosed = true;
10097 break;
10098 }
10099
10100 const bool FirstConst = FirstMethod->isConst();
10101 const bool SecondConst = SecondMethod->isConst();
10102 if (FirstConst != SecondConst) {
10103 ODRDiagError(FirstMethod->getLocation(),
10104 FirstMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010105 << FirstMethodType << FirstName << FirstConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010106 ODRDiagNote(SecondMethod->getLocation(),
10107 SecondMethod->getSourceRange(), MethodConst)
Richard Trieu1c71d512017-07-15 02:55:13 +000010108 << SecondMethodType << SecondName << SecondConst;
Richard Trieu583e2c12017-03-04 00:08:58 +000010109 Diagnosed = true;
10110 break;
10111 }
10112
10113 const bool FirstInline = FirstMethod->isInlineSpecified();
10114 const bool SecondInline = SecondMethod->isInlineSpecified();
10115 if (FirstInline != SecondInline) {
10116 ODRDiagError(FirstMethod->getLocation(),
10117 FirstMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010118 << FirstMethodType << FirstName << FirstInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010119 ODRDiagNote(SecondMethod->getLocation(),
10120 SecondMethod->getSourceRange(), MethodInline)
Richard Trieu1c71d512017-07-15 02:55:13 +000010121 << SecondMethodType << SecondName << SecondInline;
Richard Trieu583e2c12017-03-04 00:08:58 +000010122 Diagnosed = true;
10123 break;
10124 }
10125
Richard Trieu02552272017-05-02 23:58:52 +000010126 const unsigned FirstNumParameters = FirstMethod->param_size();
10127 const unsigned SecondNumParameters = SecondMethod->param_size();
10128 if (FirstNumParameters != SecondNumParameters) {
10129 ODRDiagError(FirstMethod->getLocation(),
10130 FirstMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010131 << FirstMethodType << FirstName << FirstNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010132 ODRDiagNote(SecondMethod->getLocation(),
10133 SecondMethod->getSourceRange(), MethodNumberParameters)
Richard Trieu1c71d512017-07-15 02:55:13 +000010134 << SecondMethodType << SecondName << SecondNumParameters;
Richard Trieu02552272017-05-02 23:58:52 +000010135 Diagnosed = true;
10136 break;
10137 }
10138
10139 // Need this status boolean to know when break out of the switch.
10140 bool ParameterMismatch = false;
10141 for (unsigned I = 0; I < FirstNumParameters; ++I) {
10142 const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
10143 const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
10144
10145 QualType FirstParamType = FirstParam->getType();
10146 QualType SecondParamType = SecondParam->getType();
10147 if (FirstParamType != SecondParamType &&
10148 ComputeQualTypeODRHash(FirstParamType) !=
10149 ComputeQualTypeODRHash(SecondParamType)) {
10150 if (const DecayedType *ParamDecayedType =
10151 FirstParamType->getAs<DecayedType>()) {
10152 ODRDiagError(FirstMethod->getLocation(),
10153 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010154 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10155 << true << ParamDecayedType->getOriginalType();
Richard Trieu02552272017-05-02 23:58:52 +000010156 } else {
10157 ODRDiagError(FirstMethod->getLocation(),
10158 FirstMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010159 << FirstMethodType << FirstName << (I + 1) << FirstParamType
10160 << false;
Richard Trieu02552272017-05-02 23:58:52 +000010161 }
10162
10163 if (const DecayedType *ParamDecayedType =
10164 SecondParamType->getAs<DecayedType>()) {
10165 ODRDiagNote(SecondMethod->getLocation(),
10166 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010167 << SecondMethodType << SecondName << (I + 1)
10168 << SecondParamType << true
Richard Trieu02552272017-05-02 23:58:52 +000010169 << ParamDecayedType->getOriginalType();
10170 } else {
10171 ODRDiagNote(SecondMethod->getLocation(),
10172 SecondMethod->getSourceRange(), MethodParameterType)
Richard Trieu1c71d512017-07-15 02:55:13 +000010173 << SecondMethodType << SecondName << (I + 1)
10174 << SecondParamType << false;
Richard Trieu02552272017-05-02 23:58:52 +000010175 }
10176 ParameterMismatch = true;
10177 break;
10178 }
10179
10180 DeclarationName FirstParamName = FirstParam->getDeclName();
10181 DeclarationName SecondParamName = SecondParam->getDeclName();
10182 if (FirstParamName != SecondParamName) {
10183 ODRDiagError(FirstMethod->getLocation(),
10184 FirstMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010185 << FirstMethodType << FirstName << (I + 1) << FirstParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010186 ODRDiagNote(SecondMethod->getLocation(),
10187 SecondMethod->getSourceRange(), MethodParameterName)
Richard Trieu1c71d512017-07-15 02:55:13 +000010188 << SecondMethodType << SecondName << (I + 1) << SecondParamName;
Richard Trieu02552272017-05-02 23:58:52 +000010189 ParameterMismatch = true;
10190 break;
10191 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010192
10193 const Expr *FirstInit = FirstParam->getInit();
10194 const Expr *SecondInit = SecondParam->getInit();
10195 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10196 ODRDiagError(FirstMethod->getLocation(),
10197 FirstMethod->getSourceRange(),
10198 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010199 << FirstMethodType << FirstName << (I + 1)
10200 << (FirstInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010201 << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
10202 ODRDiagNote(SecondMethod->getLocation(),
10203 SecondMethod->getSourceRange(),
10204 MethodParameterSingleDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010205 << SecondMethodType << SecondName << (I + 1)
10206 << (SecondInit == nullptr)
Richard Trieu6e13ff32017-06-16 02:44:29 +000010207 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10208 ParameterMismatch = true;
10209 break;
10210 }
10211
10212 if (FirstInit && SecondInit &&
10213 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10214 ODRDiagError(FirstMethod->getLocation(),
10215 FirstMethod->getSourceRange(),
10216 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010217 << FirstMethodType << FirstName << (I + 1)
10218 << FirstInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010219 ODRDiagNote(SecondMethod->getLocation(),
10220 SecondMethod->getSourceRange(),
10221 MethodParameterDifferentDefaultArgument)
Richard Trieu1c71d512017-07-15 02:55:13 +000010222 << SecondMethodType << SecondName << (I + 1)
10223 << SecondInit->getSourceRange();
Richard Trieu6e13ff32017-06-16 02:44:29 +000010224 ParameterMismatch = true;
10225 break;
10226
10227 }
Richard Trieu02552272017-05-02 23:58:52 +000010228 }
10229
10230 if (ParameterMismatch) {
10231 Diagnosed = true;
10232 break;
10233 }
10234
Richard Trieu48143742017-02-28 21:24:38 +000010235 break;
10236 }
Richard Trieu11d566a2017-06-12 21:58:22 +000010237 case TypeAlias:
10238 case TypeDef: {
10239 TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
10240 TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
10241 auto FirstName = FirstTD->getDeclName();
10242 auto SecondName = SecondTD->getDeclName();
10243 if (FirstName != SecondName) {
10244 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10245 TypedefName)
10246 << (FirstDiffType == TypeAlias) << FirstName;
10247 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10248 TypedefName)
10249 << (FirstDiffType == TypeAlias) << SecondName;
10250 Diagnosed = true;
10251 break;
10252 }
10253
10254 QualType FirstType = FirstTD->getUnderlyingType();
10255 QualType SecondType = SecondTD->getUnderlyingType();
10256 if (ComputeQualTypeODRHash(FirstType) !=
10257 ComputeQualTypeODRHash(SecondType)) {
10258 ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
10259 TypedefType)
10260 << (FirstDiffType == TypeAlias) << FirstName << FirstType;
10261 ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
10262 TypedefType)
10263 << (FirstDiffType == TypeAlias) << SecondName << SecondType;
10264 Diagnosed = true;
10265 break;
10266 }
10267 break;
10268 }
Richard Trieu6e13ff32017-06-16 02:44:29 +000010269 case Var: {
10270 VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
10271 VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
10272 auto FirstName = FirstVD->getDeclName();
10273 auto SecondName = SecondVD->getDeclName();
10274 if (FirstName != SecondName) {
10275 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10276 VarName)
10277 << FirstName;
10278 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10279 VarName)
10280 << SecondName;
10281 Diagnosed = true;
10282 break;
10283 }
10284
10285 QualType FirstType = FirstVD->getType();
10286 QualType SecondType = SecondVD->getType();
10287 if (ComputeQualTypeODRHash(FirstType) !=
10288 ComputeQualTypeODRHash(SecondType)) {
10289 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10290 VarType)
10291 << FirstName << FirstType;
10292 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10293 VarType)
10294 << SecondName << SecondType;
10295 Diagnosed = true;
10296 break;
10297 }
10298
10299 const Expr *FirstInit = FirstVD->getInit();
10300 const Expr *SecondInit = SecondVD->getInit();
10301 if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
10302 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10303 VarSingleInitializer)
10304 << FirstName << (FirstInit == nullptr)
10305 << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
10306 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10307 VarSingleInitializer)
10308 << SecondName << (SecondInit == nullptr)
10309 << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
10310 Diagnosed = true;
10311 break;
10312 }
10313
10314 if (FirstInit && SecondInit &&
10315 ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
10316 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10317 VarDifferentInitializer)
10318 << FirstName << FirstInit->getSourceRange();
10319 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10320 VarDifferentInitializer)
10321 << SecondName << SecondInit->getSourceRange();
10322 Diagnosed = true;
10323 break;
10324 }
10325
10326 const bool FirstIsConstexpr = FirstVD->isConstexpr();
10327 const bool SecondIsConstexpr = SecondVD->isConstexpr();
10328 if (FirstIsConstexpr != SecondIsConstexpr) {
10329 ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
10330 VarConstexpr)
10331 << FirstName << FirstIsConstexpr;
10332 ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
10333 VarConstexpr)
10334 << SecondName << SecondIsConstexpr;
10335 Diagnosed = true;
10336 break;
10337 }
10338 break;
10339 }
Richard Trieuac6a1b62017-07-08 02:04:42 +000010340 case Friend: {
10341 FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
10342 FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
10343
10344 NamedDecl *FirstND = FirstFriend->getFriendDecl();
10345 NamedDecl *SecondND = SecondFriend->getFriendDecl();
10346
10347 TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
10348 TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
10349
10350 if (FirstND && SecondND) {
10351 ODRDiagError(FirstFriend->getFriendLoc(),
10352 FirstFriend->getSourceRange(), FriendFunction)
10353 << FirstND;
10354 ODRDiagNote(SecondFriend->getFriendLoc(),
10355 SecondFriend->getSourceRange(), FriendFunction)
10356 << SecondND;
10357
10358 Diagnosed = true;
10359 break;
10360 }
10361
10362 if (FirstTSI && SecondTSI) {
10363 QualType FirstFriendType = FirstTSI->getType();
10364 QualType SecondFriendType = SecondTSI->getType();
10365 assert(ComputeQualTypeODRHash(FirstFriendType) !=
10366 ComputeQualTypeODRHash(SecondFriendType));
10367 ODRDiagError(FirstFriend->getFriendLoc(),
10368 FirstFriend->getSourceRange(), FriendType)
10369 << FirstFriendType;
10370 ODRDiagNote(SecondFriend->getFriendLoc(),
10371 SecondFriend->getSourceRange(), FriendType)
10372 << SecondFriendType;
10373 Diagnosed = true;
10374 break;
10375 }
10376
10377 ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
10378 FriendTypeFunction)
10379 << (FirstTSI == nullptr);
10380 ODRDiagNote(SecondFriend->getFriendLoc(),
10381 SecondFriend->getSourceRange(), FriendTypeFunction)
10382 << (SecondTSI == nullptr);
10383
10384 Diagnosed = true;
10385 break;
10386 }
Richard Trieu639d7b62017-02-22 22:22:42 +000010387 }
10388
Richard Trieue7f7ed22017-02-22 01:11:25 +000010389 if (Diagnosed == true)
10390 continue;
10391
Richard Trieu708859a2017-06-08 00:56:21 +000010392 Diag(FirstDecl->getLocation(),
10393 diag::err_module_odr_violation_mismatch_decl_unknown)
10394 << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
10395 << FirstDecl->getSourceRange();
10396 Diag(SecondDecl->getLocation(),
10397 diag::note_module_odr_violation_mismatch_decl_unknown)
10398 << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
Richard Trieue7f7ed22017-02-22 01:11:25 +000010399 Diagnosed = true;
Richard Smithcd45dbc2014-04-19 03:48:30 +000010400 }
10401
10402 if (!Diagnosed) {
10403 // All definitions are updates to the same declaration. This happens if a
10404 // module instantiates the declaration of a class template specialization
10405 // and two or more other modules instantiate its definition.
10406 //
10407 // FIXME: Indicate which modules had instantiations of this definition.
10408 // FIXME: How can this even happen?
10409 Diag(Merge.first->getLocation(),
10410 diag::err_module_odr_violation_different_instantiations)
10411 << Merge.first;
10412 }
10413 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010414}
10415
Richard Smithce18a182015-07-14 00:26:00 +000010416void ASTReader::StartedDeserializing() {
David L. Jonesc4808b9e2016-12-15 20:53:26 +000010417 if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
Richard Smithce18a182015-07-14 00:26:00 +000010418 ReadTimer->startTimer();
10419}
10420
Guy Benyei11169dd2012-12-18 14:30:41 +000010421void ASTReader::FinishedDeserializing() {
10422 assert(NumCurrentElementsDeserializing &&
10423 "FinishedDeserializing not paired with StartedDeserializing");
10424 if (NumCurrentElementsDeserializing == 1) {
10425 // We decrease NumCurrentElementsDeserializing only after pending actions
10426 // are finished, to avoid recursively re-calling finishPendingActions().
10427 finishPendingActions();
10428 }
10429 --NumCurrentElementsDeserializing;
10430
Richard Smitha0ce9c42014-07-29 23:23:27 +000010431 if (NumCurrentElementsDeserializing == 0) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010432 // Propagate exception specification updates along redeclaration chains.
Richard Smith7226f2a2015-03-23 19:54:56 +000010433 while (!PendingExceptionSpecUpdates.empty()) {
10434 auto Updates = std::move(PendingExceptionSpecUpdates);
10435 PendingExceptionSpecUpdates.clear();
10436 for (auto Update : Updates) {
Vassil Vassilev19765fb2016-07-22 21:08:24 +000010437 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
Richard Smith7226f2a2015-03-23 19:54:56 +000010438 auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
Richard Smith1d0f1992015-08-19 21:09:32 +000010439 auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
Richard Smithdbafb6c2017-06-29 23:23:46 +000010440 if (auto *Listener = getContext().getASTMutationListener())
Richard Smithd88a7f12015-09-01 20:35:42 +000010441 Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
Richard Smith1d0f1992015-08-19 21:09:32 +000010442 for (auto *Redecl : Update.second->redecls())
Richard Smithdbafb6c2017-06-29 23:23:46 +000010443 getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
Richard Smith7226f2a2015-03-23 19:54:56 +000010444 }
Richard Smith9e2341d2015-03-23 03:25:59 +000010445 }
10446
Richard Smithce18a182015-07-14 00:26:00 +000010447 if (ReadTimer)
10448 ReadTimer->stopTimer();
10449
Richard Smith0f4e2c42015-08-06 04:23:48 +000010450 diagnoseOdrViolations();
10451
Richard Smith04d05b52014-03-23 00:27:18 +000010452 // We are not in recursive loading, so it's safe to pass the "interesting"
10453 // decls to the consumer.
Richard Smitha0ce9c42014-07-29 23:23:27 +000010454 if (Consumer)
10455 PassInterestingDeclsToConsumer();
Guy Benyei11169dd2012-12-18 14:30:41 +000010456 }
10457}
10458
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010459void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
Richard Smith9e2341d2015-03-23 03:25:59 +000010460 if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
10461 // Remove any fake results before adding any real ones.
10462 auto It = PendingFakeLookupResults.find(II);
10463 if (It != PendingFakeLookupResults.end()) {
Richard Smitha534a312015-07-21 23:54:07 +000010464 for (auto *ND : It->second)
Richard Smith9e2341d2015-03-23 03:25:59 +000010465 SemaObj->IdResolver.RemoveDecl(ND);
Ben Langmuireb8bd2d2015-04-10 22:25:42 +000010466 // FIXME: this works around module+PCH performance issue.
10467 // Rather than erase the result from the map, which is O(n), just clear
10468 // the vector of NamedDecls.
10469 It->second.clear();
Richard Smith9e2341d2015-03-23 03:25:59 +000010470 }
10471 }
Argyrios Kyrtzidise5edbf92013-04-26 21:33:35 +000010472
10473 if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
10474 SemaObj->TUScope->AddDecl(D);
10475 } else if (SemaObj->TUScope) {
10476 // Adding the decl to IdResolver may have failed because it was already in
10477 // (even though it was not added in scope). If it is already in, make sure
10478 // it gets in the scope as well.
10479 if (std::find(SemaObj->IdResolver.begin(Name),
10480 SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
10481 SemaObj->TUScope->AddDecl(D);
10482 }
10483}
10484
Richard Smithdbafb6c2017-06-29 23:23:46 +000010485ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
David Blaikie61137e12017-01-05 18:23:18 +000010486 const PCHContainerReader &PCHContainerRdr,
10487 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
10488 StringRef isysroot, bool DisableValidation,
10489 bool AllowASTWithCompilerErrors,
10490 bool AllowConfigurationMismatch, bool ValidateSystemInputs,
10491 bool UseGlobalIndex,
10492 std::unique_ptr<llvm::Timer> ReadTimer)
10493 : Listener(DisableValidation
10494 ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
10495 : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
David Blaikie61137e12017-01-05 18:23:18 +000010496 SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010497 PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
Richard Smithdbafb6c2017-06-29 23:23:46 +000010498 ContextObj(Context),
Boris Kolpackovd30446f2017-08-31 06:26:43 +000010499 ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
10500 PP.getHeaderSearchInfo()),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000010501 PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
10502 ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
David Blaikie61137e12017-01-05 18:23:18 +000010503 DisableValidation(DisableValidation),
Nico Weber824285e2014-05-08 04:26:47 +000010504 AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
10505 AllowConfigurationMismatch(AllowConfigurationMismatch),
10506 ValidateSystemInputs(ValidateSystemInputs),
David Blaikie9d7c1ba2017-01-05 18:45:43 +000010507 UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
Guy Benyei11169dd2012-12-18 14:30:41 +000010508 SourceMgr.setExternalSLocEntrySource(this);
Douglas Gregor6623e1f2015-11-03 18:33:07 +000010509
10510 for (const auto &Ext : Extensions) {
10511 auto BlockName = Ext->getExtensionMetadata().BlockName;
10512 auto Known = ModuleFileExtensions.find(BlockName);
10513 if (Known != ModuleFileExtensions.end()) {
10514 Diags.Report(diag::warn_duplicate_module_file_extension)
10515 << BlockName;
10516 continue;
10517 }
10518
10519 ModuleFileExtensions.insert({BlockName, Ext});
10520 }
Guy Benyei11169dd2012-12-18 14:30:41 +000010521}
10522
10523ASTReader::~ASTReader() {
Nico Weber824285e2014-05-08 04:26:47 +000010524 if (OwnsDeserializationListener)
10525 delete DeserializationListener;
Guy Benyei11169dd2012-12-18 14:30:41 +000010526}
Richard Smith10379092016-05-06 23:14:07 +000010527
10528IdentifierResolver &ASTReader::getIdResolver() {
10529 return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
10530}
David L. Jonesbe1557a2016-12-21 00:17:49 +000010531
10532unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
10533 unsigned AbbrevID) {
10534 Idx = 0;
10535 Record.clear();
10536 return Cursor.readRecord(AbbrevID, Record);
10537}